diff --git a/Build/Build.csproj b/Build/Build.csproj index 18210901274..1608becd0b7 100644 --- a/Build/Build.csproj +++ b/Build/Build.csproj @@ -1,4 +1,4 @@ - + Exe true @@ -11,7 +11,7 @@ latest Recommended true - CS0618,CA1305,CA1716,CA1725,CA5351 + CS0618,CA5351 true diff --git a/Build/Lifetime.cs b/Build/Lifetime.cs index 694182c6355..d8a58cd656c 100644 --- a/Build/Lifetime.cs +++ b/Build/Lifetime.cs @@ -7,7 +7,6 @@ namespace DotNetNuke.Build using Cake.Common; using Cake.Common.Diagnostics; using Cake.Core; - using Cake.Core.Diagnostics; using Cake.Core.IO; using Cake.Frosting; @@ -17,7 +16,7 @@ public sealed class Lifetime : FrostingLifetime private static readonly string[] CorepackToolNames = ["corepack", "corepack.cmd",]; /// - public override void Setup(Context context, ISetupContext setupContext) + public override void Setup(Context context, ISetupContext info) { context.IsRunningInCI = context.HasEnvironmentVariable("TF_BUILD"); context.Information("Is Running in CI : {0}", context.IsRunningInCI); diff --git a/Build/Tasks/CreateDatabase.cs b/Build/Tasks/CreateDatabase.cs index 39af558a203..4c5b3547777 100644 --- a/Build/Tasks/CreateDatabase.cs +++ b/Build/Tasks/CreateDatabase.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Build.Tasks { using System; + using System.Globalization; using System.Linq; using Cake.Common.Diagnostics; @@ -21,23 +22,23 @@ public sealed class CreateDatabase : FrostingTask /// public override void Run(Context context) { - var deleteScript = "if db_id('Dnn_Platform') is not null DROP DATABASE Dnn_Platform;"; + const string deleteScript = "if db_id('Dnn_Platform') is not null DROP DATABASE Dnn_Platform;"; context.Information("Dropping LocalDb: {0}", this.ExecuteSqlScript(context, deleteScript)); - var createDbScript = string.Format( - @" - CREATE DATABASE - [Dnn_Platform] - ON PRIMARY ( - NAME=Dnn_data, - FILENAME = '{0}\Dnn_Platform.mdf' - ) - LOG ON ( - NAME=Dnn_log, - FILENAME = '{0}\Dnn_Platform.ldf' - )", - context.TempDir); + var createDbScript = + $""" + CREATE DATABASE + [Dnn_Platform] + ON PRIMARY ( + NAME=Dnn_data, + FILENAME = '{context.TempDir}\Dnn_Platform.mdf' + ) + LOG ON ( + NAME=Dnn_log, + FILENAME = '{context.TempDir}\Dnn_Platform.ldf' + ) + """; var createDbStatus = this.ExecuteSqlScript(context, createDbScript); context.Information("Created LocalDb: {0}", createDbStatus); @@ -64,7 +65,7 @@ LOG ON ( + ".SqlDataProvider"); var sqlDelimiterRegex = new System.Text.RegularExpressions.Regex( - "(?<=(?:[^\\w]+|^))GO(?=(?: |\\t)*?(?:\\r?\\n|$))", + @"(?<=(?:[^\w]+|^))GO(?=(?: |\t)*?(?:\r?\n|$))", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline); string[] sqlStatements = sqlDelimiterRegex.Split(fileContents); foreach (string statement in sqlStatements) @@ -109,19 +110,15 @@ LOG ON ( .ToString(); var fileBits = currentFileToProcess.Split('.'); - int firstBit; - int secondBit; - int thirdBit; - - if (int.TryParse(fileBits[0], out firstBit) - && int.TryParse(fileBits[1], out secondBit) - && int.TryParse(fileBits[2], out thirdBit)) + if (int.TryParse(fileBits[0], out var firstBit) + && int.TryParse(fileBits[1], out var secondBit) + && int.TryParse(fileBits[2], out var thirdBit)) { var schemaVersionBits = schemaVersion.Split('.'); - int schemaFirstBit = int.Parse(schemaVersionBits[0]); - int schemaSecondBit = int.Parse(schemaVersionBits[1]); - int schemaThirdBit = int.Parse(schemaVersionBits[2]); + int schemaFirstBit = int.Parse(schemaVersionBits[0], CultureInfo.InvariantCulture); + int schemaSecondBit = int.Parse(schemaVersionBits[1], CultureInfo.InvariantCulture); + int schemaThirdBit = int.Parse(schemaVersionBits[2], CultureInfo.InvariantCulture); if ((firstBit == schemaFirstBit && (secondBit >= schemaSecondBit && thirdBit >= schemaThirdBit)) || firstBit > schemaFirstBit) diff --git a/Build/Tasks/Default.cs b/Build/Tasks/Default.cs deleted file mode 100644 index d5e82b2f190..00000000000 --- a/Build/Tasks/Default.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Build.Tasks -{ - using System; - using System.Linq; - - using Cake.Frosting; - - /// A cake task to build the platform and create packages. - /// This is the default Cake target if no target is supplied. - [IsDependentOn(typeof(CleanArtifacts))] - [IsDependentOn(typeof(UpdateDnnManifests))] - [IsDependentOn(typeof(CreateInstall))] - [IsDependentOn(typeof(CreateUpgrade))] - [IsDependentOn(typeof(CreateDeploy))] - [IsDependentOn(typeof(CreateSymbols))] - public sealed class Default : FrostingTask - { - } -} diff --git a/Build/Tasks/DefaultTask.cs b/Build/Tasks/DefaultTask.cs new file mode 100644 index 00000000000..5ba61b7bcb3 --- /dev/null +++ b/Build/Tasks/DefaultTask.cs @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Build.Tasks; + +using Cake.Frosting; + +/// A cake task to build the platform and create packages. +/// This is the default Cake target if no target is supplied. +[TaskName("Default")] +[IsDependentOn(typeof(CleanArtifacts))] +[IsDependentOn(typeof(UpdateDnnManifests))] +[IsDependentOn(typeof(CreateInstall))] +[IsDependentOn(typeof(CreateUpgrade))] +[IsDependentOn(typeof(CreateDeploy))] +[IsDependentOn(typeof(CreateSymbols))] +public sealed class DefaultTask : FrostingTask; diff --git a/Build/Tasks/GeneratePackagesChecksums.cs b/Build/Tasks/GeneratePackagesChecksums.cs index fb69832c0a8..61bb6a8edc7 100644 --- a/Build/Tasks/GeneratePackagesChecksums.cs +++ b/Build/Tasks/GeneratePackagesChecksums.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Build.Tasks { using System; + using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -49,7 +50,7 @@ public override void Run(Context context) } } - sb.AppendLine($"| {fileName} | {hash} |"); + sb.AppendLine(CultureInfo.InvariantCulture, $"| {fileName} | {hash} |"); } sb.AppendLine(); diff --git a/DNN Platform/Connectors/Azure/Components/AzureConnector.cs b/DNN Platform/Connectors/Azure/Components/AzureConnector.cs index ec16b0a29ff..6a6111375f7 100644 --- a/DNN Platform/Connectors/Azure/Components/AzureConnector.cs +++ b/DNN Platform/Connectors/Azure/Components/AzureConnector.cs @@ -6,6 +6,7 @@ namespace Dnn.AzureConnector.Components using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Collections; @@ -99,11 +100,11 @@ public IEnumerable GetConnectors(int portalId) var connectors = this.FindAzureFolderMappings(portalId); if (connectors != null && connectors.Count != 0) { - connectors.ForEach(x => { this.Id = x.FolderMappingID.ToString(); }); + connectors.ForEach(x => { this.Id = x.FolderMappingID.ToString(CultureInfo.InvariantCulture); }); var finalCon = connectors.Select(x => (IConnector)Activator.CreateInstance(this.GetType())).ToList(); finalCon.ForEach(x => { - x.Id = connectors[finalCon.IndexOf(x)].FolderMappingID.ToString(); + x.Id = connectors[finalCon.IndexOf(x)].FolderMappingID.ToString(CultureInfo.InvariantCulture); x.DisplayName = connectors[finalCon.IndexOf(x)].MappingName; }); return finalCon; @@ -130,7 +131,7 @@ public void DeleteConnector(int portalId) public bool HasConfig(int portalId) { var folderMapping = this.FindAzureFolderMapping(portalId, false, true); - this.Id = Convert.ToString(folderMapping?.FolderMappingID); + this.Id = Convert.ToString(folderMapping?.FolderMappingID, CultureInfo.InvariantCulture); return this.GetConfig(portalId)["Connected"] == "true"; } @@ -150,7 +151,7 @@ public IDictionary GetConfig(int portalId) // This setting will improve the UI to set password-type inputs on secure settings configs.Add("SecureSettings", "AccountKey"); - configs.Add("Id", Convert.ToString(folderMapping?.FolderMappingID)); + configs.Add("Id", Convert.ToString(folderMapping?.FolderMappingID, CultureInfo.InvariantCulture)); return configs; } @@ -182,7 +183,7 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo return true; } - if (this.FolderMappingNameExists(portalId, this.DisplayName, Convert.ToInt32(!string.IsNullOrEmpty(this.Id) ? this.Id : null))) + if (this.FolderMappingNameExists(portalId, this.DisplayName, Convert.ToInt32(!string.IsNullOrEmpty(this.Id) ? this.Id : null, CultureInfo.InvariantCulture))) { throw new AzureConnectorException(Localization.GetString("ErrorMappingNameExists", Constants.LocalResourceFile)); } @@ -193,7 +194,7 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo FolderMappingInfo folderMapping; if (this.SupportsMultiple && !string.IsNullOrEmpty(this.Id)) { - folderMapping = folderMappings.FirstOrDefault(x => x.FolderMappingID.ToString() == this.Id); + folderMapping = folderMappings.FirstOrDefault(x => x.FolderMappingID.ToString(CultureInfo.InvariantCulture) == this.Id); } else { @@ -251,7 +252,7 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo if (!folderMapping.FolderMappingSettings.ContainsKey(Constants.SyncBatchSize)) { - folderMapping.FolderMappingSettings[Constants.SyncBatchSize] = Constants.DefaultSyncBatchSize.ToString(); + folderMapping.FolderMappingSettings[Constants.SyncBatchSize] = Constants.DefaultSyncBatchSize.ToString(CultureInfo.InvariantCulture); } this.folderMappingController.UpdateFolderMapping(folderMapping); @@ -438,10 +439,8 @@ var file in var removableFolders = folders.Where( f => f.FolderMappingID == folderMappingId && !folders1.Any(f2 => f2.FolderID != f.FolderID && - f2.FolderPath.StartsWith( - f.FolderPath) && - f2.FolderMappingID != - folderMappingId)); + f2.FolderPath.StartsWith(f.FolderPath, StringComparison.OrdinalIgnoreCase) && + f2.FolderMappingID != folderMappingId)); if (removableFolders.Any()) { @@ -486,7 +485,7 @@ private FolderMappingInfo FindAzureFolderMapping(int portalId, bool autoCreate = return folderMappings.FirstOrDefault(); } - var folderMapping = folderMappings.FirstOrDefault(x => x.FolderMappingID.ToString() == this.Id); + var folderMapping = folderMappings.FirstOrDefault(x => x.FolderMappingID.ToString(CultureInfo.InvariantCulture) == this.Id); if (folderMapping == null && autoCreate) { @@ -514,7 +513,7 @@ private bool FolderMappingNameExists(int portalId, string mappingName, int? exce private FolderMappingInfo CreateAzureFolderMapping(int portalId, string mappingName = "") { var folderMapping = CreateAzureFolderMappingStatic(this.folderMappingController, portalId, mappingName); - this.Id = folderMapping.FolderMappingID.ToString(); + this.Id = folderMapping.FolderMappingID.ToString(CultureInfo.InvariantCulture); return folderMapping; } } diff --git a/DNN Platform/Connectors/Azure/Dnn.AzureConnector.csproj b/DNN Platform/Connectors/Azure/Dnn.AzureConnector.csproj index 6468b740d26..49073bc31d6 100644 --- a/DNN Platform/Connectors/Azure/Dnn.AzureConnector.csproj +++ b/DNN Platform/Connectors/Azure/Dnn.AzureConnector.csproj @@ -11,7 +11,6 @@ Recommended true CS1591 - CA1305,CA1310,CA1725 true false diff --git a/DNN Platform/Connectors/Azure/Services/ServiceRouteMapper.cs b/DNN Platform/Connectors/Azure/Services/ServiceRouteMapper.cs index 371963ae980..1359e3c17fb 100644 --- a/DNN Platform/Connectors/Azure/Services/ServiceRouteMapper.cs +++ b/DNN Platform/Connectors/Azure/Services/ServiceRouteMapper.cs @@ -11,9 +11,9 @@ public class ServiceRouteMapper : IServiceRouteMapper private static readonly string[] Namespaces = ["Dnn.AzureConnector.Services",]; /// - public void RegisterRoutes(IMapRoute routeManager) + public void RegisterRoutes(IMapRoute mapRouteManager) { - routeManager.MapHttpRoute( + mapRouteManager.MapHttpRoute( "AzureConnector", "default", "{controller}/{action}", diff --git a/DNN Platform/Connectors/GoogleAnalytics/Dnn.GoogleAnalyticsConnector.csproj b/DNN Platform/Connectors/GoogleAnalytics/Dnn.GoogleAnalyticsConnector.csproj index 5c4ccc70d99..0033c888d53 100644 --- a/DNN Platform/Connectors/GoogleAnalytics/Dnn.GoogleAnalyticsConnector.csproj +++ b/DNN Platform/Connectors/GoogleAnalytics/Dnn.GoogleAnalyticsConnector.csproj @@ -13,7 +13,6 @@ Recommended true CS1591 - CA1311 true false diff --git a/DNN Platform/Connectors/GoogleAnalytics4/Dnn.GoogleAnalytics4Connector.csproj b/DNN Platform/Connectors/GoogleAnalytics4/Dnn.GoogleAnalytics4Connector.csproj index aadc63ded04..e14e1b874f3 100644 --- a/DNN Platform/Connectors/GoogleAnalytics4/Dnn.GoogleAnalytics4Connector.csproj +++ b/DNN Platform/Connectors/GoogleAnalytics4/Dnn.GoogleAnalytics4Connector.csproj @@ -13,7 +13,7 @@ Recommended true CS1591 - CA1311,CA3075 + CA3075 true false diff --git a/DNN Platform/Connectors/GoogleTagManager/Dnn.GoogleTagManagerConnector.csproj b/DNN Platform/Connectors/GoogleTagManager/Dnn.GoogleTagManagerConnector.csproj index ab3f463f0ea..2782965ccfe 100644 --- a/DNN Platform/Connectors/GoogleTagManager/Dnn.GoogleTagManagerConnector.csproj +++ b/DNN Platform/Connectors/GoogleTagManager/Dnn.GoogleTagManagerConnector.csproj @@ -13,7 +13,7 @@ Recommended true CS1591 - CA1311,CA3075 + CA3075 true false diff --git a/DNN Platform/Controls/CountryListBox/CountryListBox.csproj b/DNN Platform/Controls/CountryListBox/CountryListBox.csproj index ecad421a81e..64b25b2ca95 100644 --- a/DNN Platform/Controls/CountryListBox/CountryListBox.csproj +++ b/DNN Platform/Controls/CountryListBox/CountryListBox.csproj @@ -9,7 +9,6 @@ Recommended true CS1591 - CA1305,CA1707 true false diff --git a/DNN Platform/Controls/CountryListBox/CountryLookup.cs b/DNN Platform/Controls/CountryListBox/CountryLookup.cs index 1b3b6c3f4ab..edd86e614a4 100644 --- a/DNN Platform/Controls/CountryListBox/CountryLookup.cs +++ b/DNN Platform/Controls/CountryListBox/CountryLookup.cs @@ -4,6 +4,8 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Net; @@ -89,6 +91,7 @@ public CountryLookup(string fileLocation) /// Gets the GeoIP data file stream. #pragma warning disable SA1300 // Element should begin with upper-case letter + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] public MemoryStream m_MemoryStream { get; } #pragma warning restore SA1300 // Element should begin with upper-case letter @@ -272,7 +275,7 @@ private static long ConvertIPAddressToNumber(IPAddress ipAddress) var address = ipAddress.ToString().Split('.'); if (address.Length == 4) { - return Convert.ToInt64((16777216 * Convert.ToDouble(address[0])) + (65536 * Convert.ToDouble(address[1])) + (256 * Convert.ToDouble(address[2])) + Convert.ToDouble(address[3])); + return Convert.ToInt64((16777216 * Convert.ToDouble(address[0], CultureInfo.InvariantCulture)) + (65536 * Convert.ToDouble(address[1], CultureInfo.InvariantCulture)) + (256 * Convert.ToDouble(address[2], CultureInfo.InvariantCulture)) + Convert.ToDouble(address[3], CultureInfo.InvariantCulture)); } else { @@ -283,11 +286,11 @@ private static long ConvertIPAddressToNumber(IPAddress ipAddress) private static string ConvertIPNumberToAddress(long ipNumber) { // Convert an IP Number to the IP Address equivalent - string ipNumberPart1 = Convert.ToString(((int)(ipNumber / 16777216)) % 256); - string ipNumberPart2 = Convert.ToString(((int)(ipNumber / 65536)) % 256); - string ipNumberPart3 = Convert.ToString(((int)(ipNumber / 256)) % 256); - string ipNumberPart4 = Convert.ToString(((int)ipNumber) % 256); - return ipNumberPart1 + "." + ipNumberPart2 + "." + ipNumberPart3 + "." + ipNumberPart4; + string ipNumberPart1 = Convert.ToString(((int)(ipNumber / 16777216)) % 256, CultureInfo.InvariantCulture); + string ipNumberPart2 = Convert.ToString(((int)(ipNumber / 65536)) % 256, CultureInfo.InvariantCulture); + string ipNumberPart3 = Convert.ToString(((int)(ipNumber / 256)) % 256, CultureInfo.InvariantCulture); + string ipNumberPart4 = Convert.ToString(((int)ipNumber) % 256, CultureInfo.InvariantCulture); + return $"{ipNumberPart1}.{ipNumberPart2}.{ipNumberPart3}.{ipNumberPart4}"; } } } diff --git a/DNN Platform/DotNetNuke.Abstractions/Application/IHostSettings.cs b/DNN Platform/DotNetNuke.Abstractions/Application/IHostSettings.cs index 023087bca4c..e4d7ced9227 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Application/IHostSettings.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Application/IHostSettings.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Abstractions.Application; using System; +using System.Diagnostics.CodeAnalysis; using DotNetNuke.Abstractions.Security; using DotNetNuke.Internal.SourceGenerators; @@ -41,15 +42,15 @@ public interface IHostSettings public bool AllowControlPanelToDetermineVisibility { get; } /// Gets a value indicating whether Composite Files are enabled at the host level. - [DnnDeprecated(10, 2, 0, "Bundling is no longer supported, there is no replacement within DNN for this functionality.")] + [Obsolete("Deprecated in DotNetNuke 10.2.0. Bundling is no longer supported, there is no replacement within DNN for this functionality. Scheduled removal in v12.0.0.")] public bool CrmEnableCompositeFiles { get; } /// Gets a value indicating whether CSS Minification is enabled at the host level. - [DnnDeprecated(10, 2, 0, "Minification is no longer supported, there is no replacement within DNN for this functionality.")] + [Obsolete("Deprecated in DotNetNuke 10.2.0. Minification is no longer supported, there is no replacement within DNN for this functionality. Scheduled removal in v12.0.0.")] public bool CrmMinifyCss { get; } /// Gets a value indicating whether JS Minification is enabled at the host level. - [DnnDeprecated(10, 2, 0, "Minification is no longer supported, there is no replacement within DNN for this functionality.")] + [Obsolete("Deprecated in DotNetNuke 10.2.0. Minification is no longer supported, there is no replacement within DNN for this functionality. Scheduled removal in v12.0.0.")] public bool CrmMinifyJs { get; } /// Gets the Client Resource Management version number. @@ -126,9 +127,10 @@ public interface IHostSettings public IFileExtensionAllowList AllowedExtensionAllowList { get; } /// Gets default list of extensions an end user is allowed to upload. - public IFileExtensionAllowList DefaultEndUserExtensionAllowList { get; } - + public IFileExtensionAllowList DefaultEndUserExtensionAllowList { get; } + /// Gets the host GUID. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] public string Guid { get; } /// Gets the Help URL. diff --git a/DNN Platform/DotNetNuke.Abstractions/Application/SchedulerMode.cs b/DNN Platform/DotNetNuke.Abstractions/Application/SchedulerMode.cs index 59683834c00..b787db3b911 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Application/SchedulerMode.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Application/SchedulerMode.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Abstractions.Application; using System; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; /// The method for triggering scheduled tasks. public enum SchedulerMode @@ -19,6 +20,7 @@ public enum SchedulerMode /// [Obsolete("Use TimerMethod instead")] [EditorBrowsable(EditorBrowsableState.Never)] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] TIMER_METHOD = TimerMethod, /// The scheduler is running when triggered by HTTP requests. @@ -27,5 +29,6 @@ public enum SchedulerMode /// [Obsolete("Use RequestMethod instead")] [EditorBrowsable(EditorBrowsableState.Never)] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] REQUEST_METHOD = RequestMethod, } diff --git a/DNN Platform/DotNetNuke.Abstractions/DnnDeprecatedAttribute.cs b/DNN Platform/DotNetNuke.Abstractions/DnnDeprecatedAttribute.cs index 82fa906c3b4..544d811258b 100644 --- a/DNN Platform/DotNetNuke.Abstractions/DnnDeprecatedAttribute.cs +++ b/DNN Platform/DotNetNuke.Abstractions/DnnDeprecatedAttribute.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Internal.SourceGenerators; /// Marks a type or member as deprecated. [Conditional("DNN_SOURCE_GENERATOR")] +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Method)] public class DnnDeprecatedAttribute : Attribute { /// Initializes a new instance of the class. diff --git a/DNN Platform/DotNetNuke.Abstractions/DotNetNuke.Abstractions.csproj b/DNN Platform/DotNetNuke.Abstractions/DotNetNuke.Abstractions.csproj index 8b32d3208ae..24f2cec1f59 100644 --- a/DNN Platform/DotNetNuke.Abstractions/DotNetNuke.Abstractions.csproj +++ b/DNN Platform/DotNetNuke.Abstractions/DotNetNuke.Abstractions.csproj @@ -9,7 +9,6 @@ latest Recommended true - CA1018,CA1305,CA1707,CA1710,CA1716,CA1720 bin/$(Configuration)/$(TargetFramework)/DotNetNuke.Abstractions.xml false diff --git a/DNN Platform/DotNetNuke.Abstractions/ISerializationManager.cs b/DNN Platform/DotNetNuke.Abstractions/ISerializationManager.cs index 1692c628d48..6960031dab5 100644 --- a/DNN Platform/DotNetNuke.Abstractions/ISerializationManager.cs +++ b/DNN Platform/DotNetNuke.Abstractions/ISerializationManager.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Abstractions { using System; + using System.Diagnostics.CodeAnalysis; using System.Reflection; /// @@ -30,14 +31,16 @@ public interface ISerializationManager /// The object to serialize. /// The property info. /// A serialized string. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] string SerializeProperty(T myObject, PropertyInfo property); /// Serialize the property. /// The type to serialize. - /// The object to serialize.. + /// The object to serialize. /// The property info. /// The name of a type implementing DotNetNuke.Entities.Modules.Settings.ISettingsSerializer{T} to use in serializing the property. /// A serialized string. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] string SerializeProperty(T myObject, PropertyInfo property, string serializer); /// Deserializes the string value. @@ -58,19 +61,21 @@ public interface ISerializationManager /// Deserializes the string property. /// The object the string should be deserialized into. /// The object. - /// The property info.. + /// The property info. /// The serialized string. /// The could not be deserialized into the given type. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void DeserializeProperty(T myObject, PropertyInfo property, string propertyValue) where T : class, new(); /// Deserializes the string property. /// The object the string should be deserialized into. - /// The object.. - /// The property info.. + /// The object. + /// The property info. /// The serialized string. /// The name of a type implementing DotNetNuke.Entities.Modules.Settings.ISettingsSerializer{T} to use in deserializing the property. /// The could not be deserialized into the given type. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void DeserializeProperty(T myObject, PropertyInfo property, string propertyValue, string serializer) where T : class, new(); } diff --git a/DNN Platform/DotNetNuke.Abstractions/Logging/EventLogType.cs b/DNN Platform/DotNetNuke.Abstractions/Logging/EventLogType.cs index 589071aceba..30eba43c4f1 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Logging/EventLogType.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Logging/EventLogType.cs @@ -3,481 +3,641 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Abstractions.Logging { + using System.Diagnostics.CodeAnalysis; + /// System Event Log Types. public enum EventLogType - { + { /// User Created. - USER_CREATED = 0, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_CREATED = 0, + /// User Deleted. - USER_DELETED = 1, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_DELETED = 1, + /// Login Super User. - LOGIN_SUPERUSER = 2, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LOGIN_SUPERUSER = 2, + /// Log Success. - LOGIN_SUCCESS = 3, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LOGIN_SUCCESS = 3, + /// Login failure. - LOGIN_FAILURE = 4, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LOGIN_FAILURE = 4, + /// Login user locked out. - LOGIN_USERLOCKEDOUT = 5, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LOGIN_USERLOCKEDOUT = 5, + /// Login user not approved. - LOGIN_USERNOTAPPROVED = 6, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LOGIN_USERNOTAPPROVED = 6, + /// Cache refreshed. - CACHE_REFRESHED = 7, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + CACHE_REFRESHED = 7, + /// Password sent success. - PASSWORD_SENT_SUCCESS = 8, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PASSWORD_SENT_SUCCESS = 8, + /// Password sent failure. - PASSWORD_SENT_FAILURE = 9, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PASSWORD_SENT_FAILURE = 9, + /// log notification failure. - LOG_NOTIFICATION_FAILURE = 10, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LOG_NOTIFICATION_FAILURE = 10, + /// Portal created. - PORTAL_CREATED = 11, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTAL_CREATED = 11, + /// Portal deleted. - PORTAL_DELETED = 12, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTAL_DELETED = 12, + /// Portal group created. - PORTALGROUP_CREATED = 13, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALGROUP_CREATED = 13, + /// Portal group deleted. - PORTALGROUP_DELETED = 14, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALGROUP_DELETED = 14, + /// Portal added to portal group. - PORTAL_ADDEDTOPORTALGROUP = 15, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTAL_ADDEDTOPORTALGROUP = 15, + /// Portal removed from portal group. - PORTAL_REMOVEDFROMPORTALGROUP = 16, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTAL_REMOVEDFROMPORTALGROUP = 16, + /// Tab created. - TAB_CREATED = 17, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_CREATED = 17, + /// Tab updated. - TAB_UPDATED = 18, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_UPDATED = 18, + /// Tab deleted. - TAB_DELETED = 19, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_DELETED = 19, + /// Tab sent to recycle bin. - TAB_SENT_TO_RECYCLE_BIN = 20, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_SENT_TO_RECYCLE_BIN = 20, + /// Tab restored. - TAB_RESTORED = 21, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_RESTORED = 21, + /// User role created. - USER_ROLE_CREATED = 22, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_ROLE_CREATED = 22, + /// User role deleted. - USER_ROLE_DELETED = 23, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_ROLE_DELETED = 23, + /// User role updated. - USER_ROLE_UPDATED = 24, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_ROLE_UPDATED = 24, + /// Role created. - ROLE_CREATED = 25, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + ROLE_CREATED = 25, + /// Role updated. - ROLE_UPDATED = 26, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + ROLE_UPDATED = 26, + /// Role deleted. - ROLE_DELETED = 27, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + ROLE_DELETED = 27, + /// Module created. - MODULE_CREATED = 28, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + MODULE_CREATED = 28, + /// Module updated. - MODULE_UPDATED = 29, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + MODULE_UPDATED = 29, + /// Module deleted. - MODULE_DELETED = 30, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + MODULE_DELETED = 30, + /// Module sent to recycle bin. - MODULE_SENT_TO_RECYCLE_BIN = 31, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + MODULE_SENT_TO_RECYCLE_BIN = 31, + /// Module restored. - MODULE_RESTORED = 32, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + MODULE_RESTORED = 32, + /// scheduler event started. - SCHEDULER_EVENT_STARTED = 33, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULER_EVENT_STARTED = 33, + /// Scheduler event progressing. - SCHEDULER_EVENT_PROGRESSING = 34, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULER_EVENT_PROGRESSING = 34, + /// Scheduler event completed. - SCHEDULER_EVENT_COMPLETED = 35, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULER_EVENT_COMPLETED = 35, + /// Application start. - APPLICATION_START = 36, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + APPLICATION_START = 36, + /// Application end. - APPLICATION_END = 37, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + APPLICATION_END = 37, + /// Application shutting down. - APPLICATION_SHUTTING_DOWN = 38, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + APPLICATION_SHUTTING_DOWN = 38, + /// Scheduler started. - SCHEDULER_STARTED = 39, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULER_STARTED = 39, + /// Scheduler shutting down. - SCHEDULER_SHUTTING_DOWN = 40, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULER_SHUTTING_DOWN = 40, + /// Scheduler stopped. - SCHEDULER_STOPPED = 41, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULER_STOPPED = 41, + /// Admin alert. - ADMIN_ALERT = 42, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + ADMIN_ALERT = 42, + /// Host alert. - HOST_ALERT = 43, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + HOST_ALERT = 43, + /// Cache removed. - CACHE_REMOVED = 44, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + CACHE_REMOVED = 44, + /// Cache expired. - CACHE_EXPIRED = 45, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + CACHE_EXPIRED = 45, + /// Cache under used. - CACHE_UNDERUSED = 46, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + CACHE_UNDERUSED = 46, + /// Cache dependency changed. - CACHE_DEPENDENCYCHANGED = 47, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + CACHE_DEPENDENCYCHANGED = 47, + /// Cache overflow. - CACHE_OVERFLOW = 48, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + CACHE_OVERFLOW = 48, + /// Cache refresh. - CACHE_REFRESH = 49, - - /// Lisentry created. - LISTENTRY_CREATED = 50, - - /// Lisentry updated. - LISTENTRY_UPDATED = 51, - - /// Lisentry deleted. - LISTENTRY_DELETED = 52, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + CACHE_REFRESH = 49, + + /// List entry created. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LISTENTRY_CREATED = 50, + + /// List entry updated. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LISTENTRY_UPDATED = 51, + + /// List entry deleted. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LISTENTRY_DELETED = 52, + /// Desktop Module created. - DESKTOPMODULE_CREATED = 53, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + DESKTOPMODULE_CREATED = 53, + /// Desktop Module updated. - DESKTOPMODULE_UPDATED = 54, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + DESKTOPMODULE_UPDATED = 54, + /// Desktop Module deleted. - DESKTOPMODULE_DELETED = 55, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + DESKTOPMODULE_DELETED = 55, + /// Skin control created. - SKINCONTROL_CREATED = 56, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SKINCONTROL_CREATED = 56, + /// Skin control updated. - SKINCONTROL_UPDATED = 57, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SKINCONTROL_UPDATED = 57, + /// Skin control deleted. - SKINCONTROL_DELETED = 58, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SKINCONTROL_DELETED = 58, + /// Portal alias created. - PORTALALIAS_CREATED = 59, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALALIAS_CREATED = 59, + /// Portal alias updated. - PORTALALIAS_UPDATED = 60, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALALIAS_UPDATED = 60, + /// Portal alias deleted. - PORTALALIAS_DELETED = 61, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALALIAS_DELETED = 61, + /// Profile property created. - PROFILEPROPERTY_CREATED = 62, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PROFILEPROPERTY_CREATED = 62, + /// Profile property updated. - PROFILEPROPERTY_UPDATED = 63, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PROFILEPROPERTY_UPDATED = 63, + /// Profile property deleted. - PROFILEPROPERTY_DELETED = 64, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PROFILEPROPERTY_DELETED = 64, + /// User updated. - USER_UPDATED = 65, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_UPDATED = 65, + /// Desktop module permission created. - DESKTOPMODULEPERMISSION_CREATED = 66, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + DESKTOPMODULEPERMISSION_CREATED = 66, + /// Desktop module permission updated. - DESKTOPMODULEPERMISSION_UPDATED = 67, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + DESKTOPMODULEPERMISSION_UPDATED = 67, + /// Desktop module permission deleted. - DESKTOPMODULEPERMISSION_DELETED = 68, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + DESKTOPMODULEPERMISSION_DELETED = 68, + /// Permission created. - PERMISSION_CREATED = 69, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PERMISSION_CREATED = 69, + /// Permission updated. - PERMISSION_UPDATED = 70, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PERMISSION_UPDATED = 70, + /// Permission deleted. - PERMISSION_DELETED = 71, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PERMISSION_DELETED = 71, + /// Tab permission created. - TABPERMISSION_CREATED = 72, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABPERMISSION_CREATED = 72, + /// Tab permission updated. - TABPERMISSION_UPDATED = 73, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABPERMISSION_UPDATED = 73, + /// Tab permission deleted. - TABPERMISSION_DELETED = 74, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABPERMISSION_DELETED = 74, + /// Authentication created. - AUTHENTICATION_CREATED = 75, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + AUTHENTICATION_CREATED = 75, + /// Authentication updated. - AUTHENTICATION_UPDATED = 76, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + AUTHENTICATION_UPDATED = 76, + /// Authentication deleted. - AUTHENTICATION_DELETED = 77, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + AUTHENTICATION_DELETED = 77, + /// File added. - FILE_ADDED = 78, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FILE_ADDED = 78, + /// File changed. - FILE_CHANGED = 79, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FILE_CHANGED = 79, + /// File deleted. - FILE_DELETED = 80, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FILE_DELETED = 80, + /// File downloaded. - FILE_DOWNLOADED = 81, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FILE_DOWNLOADED = 81, + /// File moved. - FILE_MOVED = 82, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FILE_MOVED = 82, + /// File overwritten. - FILE_OVERWRITTEN = 83, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FILE_OVERWRITTEN = 83, + /// File renamed. - FILE_RENAMED = 84, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FILE_RENAMED = 84, + /// File metadata changed. - FILE_METADATACHANGED = 85, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FILE_METADATACHANGED = 85, + /// Folder created. - FOLDER_CREATED = 86, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FOLDER_CREATED = 86, + /// Folder updated. - FOLDER_UPDATED = 87, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FOLDER_UPDATED = 87, + /// Folder deleted. - FOLDER_DELETED = 88, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FOLDER_DELETED = 88, + /// Package created. - PACKAGE_CREATED = 89, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PACKAGE_CREATED = 89, + /// Package updated. - PACKAGE_UPDATED = 90, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PACKAGE_UPDATED = 90, + /// Package deleted. - PACKAGE_DELETED = 91, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PACKAGE_DELETED = 91, + /// Language pack created. - LANGUAGEPACK_CREATED = 92, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGEPACK_CREATED = 92, + /// Language pack updated. - LANGUAGEPACK_UPDATED = 93, - - /// Langauge pack deleted. - LANGUAGEPACK_DELETED = 94, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGEPACK_UPDATED = 93, + + /// Language pack deleted. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGEPACK_DELETED = 94, + /// Language created. - LANGUAGE_CREATED = 95, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGE_CREATED = 95, + /// Language updated. - LANGUAGE_UPDATED = 96, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGE_UPDATED = 96, + /// Language deleted. - LANGUAGE_DELETED = 97, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGE_DELETED = 97, + /// Library updated. - LIBRARY_UPDATED = 98, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LIBRARY_UPDATED = 98, + /// Skin package created. - SKINPACKAGE_CREATED = 99, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SKINPACKAGE_CREATED = 99, + /// Skin package updated. - SKINPACKAGE_UPDATED = 100, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SKINPACKAGE_UPDATED = 100, + /// Skin package deleted. - SKINPACKAGE_DELETED = 101, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SKINPACKAGE_DELETED = 101, + /// Schedule created. - SCHEDULE_CREATED = 102, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULE_CREATED = 102, + /// Schedule updated. - SCHEDULE_UPDATED = 103, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULE_UPDATED = 103, + /// schedule deleted. - SCHEDULE_DELETED = 104, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCHEDULE_DELETED = 104, + /// Host setting created. - HOST_SETTING_CREATED = 105, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + HOST_SETTING_CREATED = 105, + /// Host setting updated. - HOST_SETTING_UPDATED = 106, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + HOST_SETTING_UPDATED = 106, + /// Host setting deleted. - HOST_SETTING_DELETED = 107, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + HOST_SETTING_DELETED = 107, + /// Portal desktop module created. - PORTALDESKTOPMODULE_CREATED = 108, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALDESKTOPMODULE_CREATED = 108, + /// Portal desktop module updated. - PORTALDESKTOPMODULE_UPDATED = 109, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALDESKTOPMODULE_UPDATED = 109, + /// Portal desktop module deleted. - PORTALDESKTOPMODULE_DELETED = 110, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALDESKTOPMODULE_DELETED = 110, + /// Tab module created. - TABMODULE_CREATED = 111, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABMODULE_CREATED = 111, + /// Tab module updated. - TABMODULE_UPDATED = 112, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABMODULE_UPDATED = 112, + /// Tab module deleted. - TABMODULE_DELETED = 113, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABMODULE_DELETED = 113, + /// Tab module setting created. - TABMODULE_SETTING_CREATED = 114, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABMODULE_SETTING_CREATED = 114, + /// Tab module setting updated. - TABMODULE_SETTING_UPDATED = 115, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABMODULE_SETTING_UPDATED = 115, + /// Tab module setting deleted. - TABMODULE_SETTING_DELETED = 116, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABMODULE_SETTING_DELETED = 116, + /// Module setting created. - MODULE_SETTING_CREATED = 117, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + MODULE_SETTING_CREATED = 117, + /// Module setting updated. - MODULE_SETTING_UPDATED = 118, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + MODULE_SETTING_UPDATED = 118, + /// Module setting deleted. - MODULE_SETTING_DELETED = 119, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + MODULE_SETTING_DELETED = 119, + /// Portal setting created. - PORTAL_SETTING_CREATED = 120, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTAL_SETTING_CREATED = 120, + /// Portal setting updated. - PORTAL_SETTING_UPDATED = 121, - - /// POrtal setting deleted. - PORTAL_SETTING_DELETED = 122, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTAL_SETTING_UPDATED = 121, + + /// Portal setting deleted. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTAL_SETTING_DELETED = 122, + /// Portal info created. - PORTALINFO_CREATED = 123, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALINFO_CREATED = 123, + /// Portal info updated. - PORTALINFO_UPDATED = 124, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALINFO_UPDATED = 124, + /// Portal info deleted. - PORTALINFO_DELETED = 125, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PORTALINFO_DELETED = 125, + /// Authentication user created. - AUTHENTICATION_USER_CREATED = 126, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + AUTHENTICATION_USER_CREATED = 126, + /// Authentication user updated. - AUTHENTICATION_USER_UPDATED = 127, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + AUTHENTICATION_USER_UPDATED = 127, + /// Authentication user deleted. - AUTHENTICATION_USER_DELETED = 128, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + AUTHENTICATION_USER_DELETED = 128, + /// Language to portal created. - LANGUAGETOPORTAL_CREATED = 129, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGETOPORTAL_CREATED = 129, + /// Language to portal updated. - LANGUAGETOPORTAL_UPDATED = 130, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGETOPORTAL_UPDATED = 130, + /// Language to portal deleted. - LANGUAGETOPORTAL_DELETED = 131, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + LANGUAGETOPORTAL_DELETED = 131, + /// Tab order updated. - TAB_ORDER_UPDATED = 132, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_ORDER_UPDATED = 132, + /// Tab setting created. - TAB_SETTING_CREATED = 133, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_SETTING_CREATED = 133, + /// Tab setting updated. - TAB_SETTING_UPDATED = 134, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_SETTING_UPDATED = 134, + /// Tab setting deleted. - TAB_SETTING_DELETED = 135, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TAB_SETTING_DELETED = 135, + /// Host SQL executed. - HOST_SQL_EXECUTED = 136, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + HOST_SQL_EXECUTED = 136, + /// User restored. - USER_RESTORED = 137, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_RESTORED = 137, + /// User removed. - USER_REMOVED = 138, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_REMOVED = 138, + /// User impersonated. - USER_IMPERSONATED = 139, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USER_IMPERSONATED = 139, + /// Username updated. - USERNAME_UPDATED = 140, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + USERNAME_UPDATED = 140, + /// IP Login banned. - IP_LOGIN_BANNED = 141, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + IP_LOGIN_BANNED = 141, + /// Page Not Found 404. - PAGE_NOT_FOUND_404 = 142, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + PAGE_NOT_FOUND_404 = 142, + /// Tab URL created. - TABURL_CREATED = 143, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABURL_CREATED = 143, + /// Tab URL updated. - TABURL_UPDATED = 144, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABURL_UPDATED = 144, + /// Tab URL deleted. - TABURL_DELETED = 145, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + TABURL_DELETED = 145, + /// Script collision. - SCRIPT_COLLISION = 146, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + SCRIPT_COLLISION = 146, + /// Potential paypal payment fraud. - POTENTIAL_PAYPAL_PAYMENT_FRAUD = 147, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + POTENTIAL_PAYPAL_PAYMENT_FRAUD = 147, + /// Webserver created. - WEBSERVER_CREATED = 148, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + WEBSERVER_CREATED = 148, + /// Webserver updated. - WEBSERVER_UPDATED = 149, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + WEBSERVER_UPDATED = 149, + /// Webserver disabled. - WEBSERVER_DISABLED = 150, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + WEBSERVER_DISABLED = 150, + /// Webserver enabled. - WEBSERVER_ENABLED = 151, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + WEBSERVER_ENABLED = 151, + /// Webserver ping failed. - WEBSERVER_PINGFAILED = 152, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + WEBSERVER_PINGFAILED = 152, + /// Folder moved. - FOLDER_MOVED = 153, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + FOLDER_MOVED = 153, + /// API Token Authentication Failed. - APITOKEN_AUTHENTICATION_FAILED = 154, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + APITOKEN_AUTHENTICATION_FAILED = 154, + /// API Token Created. - APITOKEN_CREATED = 155, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + APITOKEN_CREATED = 155, + /// API Token Deleted. - APITOKEN_DELETED = 156, - + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + APITOKEN_DELETED = 156, + /// API Token Revoked. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] APITOKEN_REVOKED = 157, } } diff --git a/DNN Platform/DotNetNuke.Abstractions/Logging/ILogProperties.cs b/DNN Platform/DotNetNuke.Abstractions/Logging/ILogProperties.cs index a0889c00dea..ed6aa6d4740 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Logging/ILogProperties.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Logging/ILogProperties.cs @@ -3,11 +3,11 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Abstractions.Logging { - using System; - using System.Collections; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; /// add xml docs. + [SuppressMessage("Microsoft.Design", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Breaking change")] public interface ILogProperties : ICollection { /// Gets the Summary. diff --git a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalAliasService.cs b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalAliasService.cs index 9135319e7af..f2ba999a28e 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalAliasService.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalAliasService.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Abstractions.Portals { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; /// Portal Alias APIs for managing the different Portal Alias. public interface IPortalAliasService @@ -38,12 +39,14 @@ public interface IPortalAliasService /// Get a portal alias by name. /// The name of the portal alias. /// The portal alias. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] IPortalAliasInfo GetPortalAlias(string alias); /// Gets the portal alias. /// The portal alias. /// The portal ID. /// Portal Alias Info. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] IPortalAliasInfo GetPortalAlias(string alias, int portalId); /// Gets the portal alias by portal alias ID. diff --git a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalInfo.cs b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalInfo.cs index 043a3453661..e9833dada7f 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalInfo.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalInfo.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Abstractions.Portals { using System; + using System.Diagnostics.CodeAnalysis; /// The portal info. public interface IPortalInfo @@ -72,9 +73,10 @@ public interface IPortalInfo /// Gets or sets GUID of the portal info object. /// Portal info Object GUID. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] Guid GUID { get; set; } - /// Gets or sets tabdId of the Home page. + /// Gets or sets tab ID of the Home page. /// TabId of the Home page. int HomeTabId { get; set; } diff --git a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs index ddd390191a8..64b495ab992 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Abstractions.Portals { using System; + using System.Diagnostics.CodeAnalysis; /// /// The PortalSettings class encapsulates all of the settings for the Portal, @@ -169,6 +170,7 @@ public interface IPortalSettings string FooterText { get; set; } /// Gets or sets the portal GUID. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] Guid GUID { get; set; } /// Gets a value indicating whether folders which are hidden or whose name begins with underscore are included in folder synchronization. diff --git a/DNN Platform/DotNetNuke.Abstractions/Portals/StyleColor.cs b/DNN Platform/DotNetNuke.Abstractions/Portals/StyleColor.cs index 4d2485bafa7..969ed93c47b 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Portals/StyleColor.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Portals/StyleColor.cs @@ -5,11 +5,10 @@ namespace DotNetNuke.Abstractions.Portals { using System; + using System.Globalization; using System.Text.RegularExpressions; - /// - /// Represents a CSS color and its components. - /// + /// Represents a CSS color and its components. public struct StyleColor { private static readonly Regex HexColorRegex = new Regex(@"([\da-f]{3}){1,2}", RegexOptions.IgnoreCase | RegexOptions.Compiled); @@ -19,26 +18,22 @@ public struct StyleColor private readonly byte blue; private string hex; - /// - /// Initializes a new instance of the struct. - /// + /// Initializes a new instance of the struct. public StyleColor() : this("FFFFFF") { } - /// - /// Initializes a new instance of the struct. - /// + /// Initializes a new instance of the struct. /// The hex value to use. public StyleColor(string hexValue) { AssertIsValidCssColor(hexValue); this.HexValue = hexValue; - this.red = byte.Parse(this.HexValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); - this.green = byte.Parse(this.HexValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber); - this.blue = byte.Parse(this.HexValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber); + this.red = byte.Parse(this.HexValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); + this.green = byte.Parse(this.HexValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); + this.blue = byte.Parse(this.HexValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); } private enum Component diff --git a/DNN Platform/DotNetNuke.Abstractions/Portals/Templates/IPortalTemplateController.cs b/DNN Platform/DotNetNuke.Abstractions/Portals/Templates/IPortalTemplateController.cs index 6deb1b1aeef..dbddae8eed0 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Portals/Templates/IPortalTemplateController.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Portals/Templates/IPortalTemplateController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Abstractions.Portals.Templates { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; /// Work with Portal Templates. public interface IPortalTemplateController @@ -17,10 +18,11 @@ public interface IPortalTemplateController /// Flag to determine whether the template is applied to an existing portal or a newly created one. /// /// When creating a new portal in DNN (PortalController.CreatePortal) the entry in the DB is first created and the - /// necessary folders on disk. After that this method is run to finish setting up the new potral. But one can also apply + /// necessary folders on disk. After that this method is run to finish setting up the new portal. But one can also apply /// a template to an existing portal. How clashes are handled is determined by the mergeTabs argument. /// The roles and settings nodes will only be processed on the portal template file. /// + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void ApplyPortalTemplate(int portalId, IPortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal); /// Export a portal into a portal template. @@ -28,7 +30,7 @@ public interface IPortalTemplateController /// The filename to use when writing the portal template to disk. Note it will be written to the host /// directory (Portals/_default). /// Description of the template. - /// Whether the template is a multi language template. + /// Whether the template is a multi-language template. /// A list of locales that are to be exported. /// The default locale. /// A list of tab ids to export. These should be checked beforehand to ensure they form a continuous diff --git a/DNN Platform/DotNetNuke.Abstractions/Prompt/ICommandHelp.cs b/DNN Platform/DotNetNuke.Abstractions/Prompt/ICommandHelp.cs index 19e7874afb1..d6f04451e42 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Prompt/ICommandHelp.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Prompt/ICommandHelp.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Abstractions.Prompt { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; /// This is used to send the result back to the client when a user asks help for a command. public interface ICommandHelp @@ -21,6 +22,7 @@ public interface ICommandHelp string ResultHtml { get; set; } /// Gets or sets any error produced while trying to retrieve help for this command. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] string Error { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs b/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs index 9fe3430331d..e749d3fccc4 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Instrumentation { using System; using System.Diagnostics; + using System.Globalization; using System.IO; using System.Linq; using System.Web.Compilation; @@ -62,7 +63,7 @@ public static void MethodEntry() if (Logger.Logger.IsEnabledFor(DnnLogger.LevelTrace)) { - Logger.TraceFormat("Entering Method [{0}]", CallingFrame.GetMethod().Name); + Logger.TraceFormat(CultureInfo.InvariantCulture, "Entering Method [{0}]", CallingFrame.GetMethod().Name); } } @@ -79,7 +80,7 @@ public static void MethodExit(object returnObject) returnObject = "NULL"; } - Logger.TraceFormat("Method [{0}] Returned [{1}]", CallingFrame.GetMethod().Name, returnObject); + Logger.TraceFormat(CultureInfo.InvariantCulture, "Method [{0}] Returned [{1}]", CallingFrame.GetMethod().Name, returnObject); } } @@ -90,7 +91,7 @@ public static void MethodExit() if (Logger.Logger.IsEnabledFor(DnnLogger.LevelTrace)) { - Logger.TraceFormat("Method [{0}] Returned", CallingFrame.GetMethod().Name); + Logger.TraceFormat(CultureInfo.InvariantCulture, "Method [{0}] Returned", CallingFrame.GetMethod().Name); } } @@ -110,14 +111,7 @@ public static void Trace(string message) /// A composite format string. /// An object array that contains zero or more objects to format. public static void Trace(string format, params object[] args) - { - EnsureConfig(); - - if (Logger.Logger.IsEnabledFor(DnnLogger.LevelTrace)) - { - Logger.TraceFormat(format, args); - } - } + => Trace(CultureInfo.InvariantCulture, format, args); /// Log a message at the Trace log level. /// An object that supplies culture-specific formatting information. @@ -160,7 +154,7 @@ public static void Debug(string format, params object[] args) } else { - Logger.DebugFormat(format, args); + Logger.DebugFormat(CultureInfo.InvariantCulture, format, args); } } } @@ -217,7 +211,7 @@ public static void Info(string format, params object[] args) } else { - Logger.InfoFormat(format, args); + Logger.InfoFormat(CultureInfo.InvariantCulture, format, args); } } } @@ -272,7 +266,7 @@ public static void Warn(string format, params object[] args) } else { - Logger.WarnFormat(format, args); + Logger.WarnFormat(CultureInfo.InvariantCulture, format, args); } } } @@ -335,11 +329,11 @@ public static void Error(string format, params object[] args) { if (args.Length == 0) { - Logger.ErrorFormat(format); + Logger.Error(format); } else { - Logger.ErrorFormat(format, args); + Logger.ErrorFormat(CultureInfo.InvariantCulture, format, args); } } } @@ -394,7 +388,7 @@ public static void Fatal(string format, params object[] args) } else { - Logger.FatalFormat(format, args); + Logger.FatalFormat(CultureInfo.InvariantCulture, format, args); } } } diff --git a/DNN Platform/DotNetNuke.Instrumentation/DotNetNuke.Instrumentation.csproj b/DNN Platform/DotNetNuke.Instrumentation/DotNetNuke.Instrumentation.csproj index cb48e4422ba..b982efa93ef 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/DotNetNuke.Instrumentation.csproj +++ b/DNN Platform/DotNetNuke.Instrumentation/DotNetNuke.Instrumentation.csproj @@ -12,7 +12,6 @@ Recommended true 1591,0649 - CA1305,CA1711,CA1716 true false diff --git a/DNN Platform/DotNetNuke.Instrumentation/ILog.cs b/DNN Platform/DotNetNuke.Instrumentation/ILog.cs index 0829b69760b..f7fc6363f8b 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/ILog.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/ILog.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Instrumentation { using System; + using System.Diagnostics.CodeAnalysis; /// A contract specifying the ability to log information. public interface ILog @@ -108,11 +109,13 @@ public interface ILog /// Log a message at the Error log level. /// An object to display as the message. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void Error(object message); /// Log a message and exception details at the Error log level. /// An object to display as the message. /// An exception to include in the log. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void Error(object message, Exception exception); /// Log a message at the Error log level. diff --git a/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs b/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs index 69863cad7a0..fad44c6e173 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Instrumentation { using System; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; @@ -16,6 +17,7 @@ namespace DotNetNuke.Instrumentation using log4net.Util; /// An implementation. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public class LoggerSourceImpl : ILoggerSource { /// @@ -248,7 +250,7 @@ private static void AddGlobalContext() { try { - GlobalContext.Properties["appdomain"] = AppDomain.CurrentDomain.Id.ToString("D"); + GlobalContext.Properties["appdomain"] = AppDomain.CurrentDomain.Id.ToString("D", CultureInfo.InvariantCulture); } catch { diff --git a/DNN Platform/DotNetNuke.Maintenance/DotNetNuke.Maintenance.csproj b/DNN Platform/DotNetNuke.Maintenance/DotNetNuke.Maintenance.csproj index 7ce2770b6fe..4c658af7fb1 100644 --- a/DNN Platform/DotNetNuke.Maintenance/DotNetNuke.Maintenance.csproj +++ b/DNN Platform/DotNetNuke.Maintenance/DotNetNuke.Maintenance.csproj @@ -10,7 +10,6 @@ Recommended true NU1701 - CA1305,CA1310 bin/$(Configuration)/$(TargetFramework)/DotNetNuke.Maintenance.xml false diff --git a/DNN Platform/DotNetNuke.Maintenance/Shims/InstallerShim.cs b/DNN Platform/DotNetNuke.Maintenance/Shims/InstallerShim.cs index 009ad6fe70c..e93252a13e7 100644 --- a/DNN Platform/DotNetNuke.Maintenance/Shims/InstallerShim.cs +++ b/DNN Platform/DotNetNuke.Maintenance/Shims/InstallerShim.cs @@ -4,11 +4,13 @@ namespace DotNetNuke.Maintenance.Shims { + using System; + using DotNetNuke.Services.Installer; using DotNetNuke.Services.Installer.Packages; /// An implementation of that relies on the class. - internal sealed class InstallerShim : IInstaller + internal sealed class InstallerShim : IInstaller, IDisposable { private readonly Installer installer; @@ -23,5 +25,11 @@ public bool UnInstall(bool deleteFiles) { return this.installer.UnInstall(deleteFiles); } + + /// + public void Dispose() + { + this.installer?.Dispose(); + } } } diff --git a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/DamUninstaller.cs b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/DamUninstaller.cs index 42ab6e4285c..6bde1a5f3ec 100644 --- a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/DamUninstaller.cs +++ b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/DamUninstaller.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Maintenance.Telerik.Removal { using System; using System.Collections; + using System.Globalization; /// internal sealed class DamUninstaller : UnInstaller, IDamUninstaller @@ -66,7 +67,7 @@ private Hashtable MigrateSettings(Hashtable oldSettings) } } - settings.Add("RM_Mode", newMode.ToString()); + settings.Add("RM_Mode", newMode.ToString(CultureInfo.InvariantCulture)); var rootFolder = oldSettings["RootFolderId"]; if (rootFolder != null) diff --git a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/DeleteFilesStep.cs b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/DeleteFilesStep.cs index c8ef8f0949e..d0846f1ebcb 100644 --- a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/DeleteFilesStep.cs +++ b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/DeleteFilesStep.cs @@ -53,7 +53,7 @@ public DeleteFilesStep( protected override void ExecuteInternal() { var count = 0; - var appPath = this.applicationStatusInfo.ApplicationMapPath + "\\"; + var appPath = this.applicationStatusInfo.ApplicationMapPath + @"\"; var fullPath = Path.GetFullPath(Path.Combine(appPath, this.RelativePath)); var files = this.fileSystemProvider.EnumerateFiles(fullPath, this.SearchPattern, this.SearchOption); diff --git a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/RemoveExtensionStep.cs b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/RemoveExtensionStep.cs index 1d6c6fcac4b..12bf253392b 100644 --- a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/RemoveExtensionStep.cs +++ b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/RemoveExtensionStep.cs @@ -54,15 +54,13 @@ protected override void ExecuteInternal() private IStep RemoveSystemAttributeFromPackage() { - var commandFormat = string.Join( - Environment.NewLine, - "UPDATE {{databaseOwner}}{{objectQualifier}}Packages", - "SET IsSystemPackage = 0", - "WHERE [Name] = '{0}'"); - var step = this.GetService(); step.Name = this.LocalizeFormat("UninstallStepRemoveSystemAttribute", this.PackageName); - step.CommandText = string.Format(commandFormat, this.PackageName); + step.CommandText = $$""" + UPDATE {databaseOwner}{objectQualifier}Packages + SET IsSystemPackage = 0 + WHERE [Name] = '{{this.PackageName}}' + """; return step; } @@ -83,14 +81,12 @@ private IStep UninstallExtension() private IStep DeleteDependencyRecords() { - var commandFormat = string.Join( - Environment.NewLine, - "DELETE FROM {{databaseOwner}}{{objectQualifier}}PackageDependencies", - "WHERE PackageName = '{0}'"); - var step = this.GetService(); step.Name = this.LocalizeFormat("UninstallStepCleanupDependencyRecords", this.PackageName); - step.CommandText = string.Format(commandFormat, this.PackageName); + step.CommandText = $$""" + DELETE FROM {databaseOwner}{objectQualifier}PackageDependencies + WHERE PackageName = '{{this.PackageName}}' + """; return step; } diff --git a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/XmlStepBase.cs b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/XmlStepBase.cs index 9228d65c4f3..07b4637f7b5 100644 --- a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/XmlStepBase.cs +++ b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/Steps/XmlStepBase.cs @@ -42,7 +42,7 @@ public XmlStepBase( protected override void ExecuteInternal() { var doc = new XmlDocument { PreserveWhitespace = true }; - var root = this.applicationStatusInfo.ApplicationMapPath + "\\"; + var root = this.applicationStatusInfo.ApplicationMapPath + @"\"; var fullPath = Path.GetFullPath(Path.Combine(root, this.RelativeFilePath)); doc.Load(fullPath); diff --git a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/UnInstaller.cs b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/UnInstaller.cs index 48296f9390c..5c2e5929831 100644 --- a/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/UnInstaller.cs +++ b/DNN Platform/DotNetNuke.Maintenance/Telerik/Removal/UnInstaller.cs @@ -87,15 +87,13 @@ private protected IStep RemoveFile(string relativePath, string searchPattern) /// of the data type updater. private protected IStep UpdateDataTypeList(string value) { - var commandFormat = string.Join( - Environment.NewLine, - "UPDATE {{databaseOwner}}[{{objectQualifier}}Lists]", - "SET Text = 'DotNetNuke.Web.UI.WebControls.Internal.PropertyEditorControls.{0}EditControl, DotNetNuke.Web'", - "WHERE ListName = 'DataType' AND Value = '{0}'"); - var step = this.GetService(); step.Name = this.localizer.LocalizeFormat("UninstallStepUpdateDataTypeListFormat", value); - step.CommandText = string.Format(commandFormat, value); + step.CommandText = $$""" + UPDATE {databaseOwner}[{objectQualifier}Lists] + SET Text = 'DotNetNuke.Web.UI.WebControls.Internal.PropertyEditorControls.{{value}}EditControl, DotNetNuke.Web' + WHERE ListName = 'DataType' AND Value = '{{value}}' + """; return step; } diff --git a/DNN Platform/DotNetNuke.Maintenance/Telerik/TelerikUtils.cs b/DNN Platform/DotNetNuke.Maintenance/Telerik/TelerikUtils.cs index 662db1fdc55..d1bf78c32ed 100644 --- a/DNN Platform/DotNetNuke.Maintenance/Telerik/TelerikUtils.cs +++ b/DNN Platform/DotNetNuke.Maintenance/Telerik/TelerikUtils.cs @@ -18,13 +18,13 @@ public class TelerikUtils : ITelerikUtils /// The file name of the Telerik Web UI assembly. public static readonly string TelerikWebUIFileName = "Telerik.Web.UI.dll"; - private static readonly string[] Vendors = new[] - { + private static readonly string[] Vendors = + [ "Microsoft", "System", - }; + ]; - private static readonly string[] WellKnownAssemblies = new[] + private static readonly HashSet WellKnownAssemblies = new(StringComparer.OrdinalIgnoreCase) { "Telerik.Web.UI.Skins.dll", "DotNetNuke.Website.Deprecated.dll", @@ -122,7 +122,7 @@ private static bool IsNotWellKnownAssembly(string path) { var fileName = Path.GetFileName(path); return !WellKnownAssemblies.Contains(fileName) && - !Vendors.Any(vendor => fileName.StartsWith($"{vendor}.")); + !Vendors.Any(vendor => fileName.StartsWith($"{vendor}.", StringComparison.OrdinalIgnoreCase)); } private bool AssemblyDependsOnTelerik(string path, AppDomain domain) diff --git a/DNN Platform/DotNetNuke.Web.Client.ResourceManager/ClientResourceController.cs b/DNN Platform/DotNetNuke.Web.Client.ResourceManager/ClientResourceController.cs index a193839dc09..680df7924f9 100644 --- a/DNN Platform/DotNetNuke.Web.Client.ResourceManager/ClientResourceController.cs +++ b/DNN Platform/DotNetNuke.Web.Client.ResourceManager/ClientResourceController.cs @@ -277,7 +277,7 @@ private string ResolvePath(string filePath, string pathNameAlias) } // Path is either a relative path including the application path or a path starting with a tilde or a path relative to the path name alias - filePath = filePath.Replace("\\", "/"); + filePath = filePath.Replace(@"\", "/"); if (!string.IsNullOrEmpty(pathNameAlias)) { if (this.PathNameAliases.TryGetValue(pathNameAlias, out var alias)) diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs index dcc7cad6114..55434bb8854 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Web.Client.ClientResourceManagement { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Web.UI.WebControls; @@ -22,8 +23,8 @@ public class DnnHtmlInclude : Literal private const string MatchAllAttributes = "(\\S+)=[\"']?((?:.(?![\"']?\\s+(?:\\S+)=|[>\"']))+.)[\"']?"; - private static readonly Regex LinkTagRegex = new Regex(string.Format(TagPattern, "link"), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex ScriptTagRegex = new Regex(string.Format(TagPattern, "script"), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex LinkTagRegex = new Regex(string.Format(CultureInfo.InvariantCulture, TagPattern, "link"), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex ScriptTagRegex = new Regex(string.Format(CultureInfo.InvariantCulture, TagPattern, "script"), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private readonly IClientResourceController clientResourceController; diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs index c2fe8fe6669..1b2ef5cfc4a 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs @@ -2,47 +2,48 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Client.ClientResourceManagement -{ - using System.Web.UI; - using System.Web.UI.WebControls; +namespace DotNetNuke.Web.Client.ClientResourceManagement +{ + using System; + using System.Web.UI; + using System.Web.UI.WebControls; - /// Emit a fallback block for a script in the same part of the page. - public class DnnJsIncludeFallback : WebControl + /// Emit a fallback block for a script in the same part of the page. + public class DnnJsIncludeFallback : WebControl { /// Initializes a new instance of the class. /// The JS object name to verify is defined in global scope. /// The path to load if the object is not defined. - public DnnJsIncludeFallback(string objectName, string fileName) - { - this.ObjectName = objectName; - this.FileName = fileName; - } - - public string ObjectName { get; set; } - + public DnnJsIncludeFallback(string objectName, string fileName) + { + this.ObjectName = objectName; + this.FileName = fileName; + } + + public string ObjectName { get; set; } + public string FileName { get; set; } /// - public override void RenderControl(HtmlTextWriter writer) - { - writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript"); - writer.RenderBeginTag(HtmlTextWriterTag.Script); - - if (this.ObjectName.Contains(".")) - { - // generate function check - writer.Write("if (typeof " + this.ObjectName + " != 'function') {"); - } - else - { - // generate object check - writer.Write("if (typeof " + this.ObjectName + " == 'undefined') {"); - } - - writer.Write("document.write(']]> - public const string glbScriptFormat = ""; - - /// Validates for a valid email address. - public static readonly Regex EmailValidatorRegex = new Regex(glbEmailRegEx, RegexOptions.Compiled); - - /// Finds non-alphanumeric characters. - public static readonly Regex NonAlphanumericCharacters = new Regex("[^A-Za-z0-9]", RegexOptions.Compiled | RegexOptions.CultureInvariant); - - /// Finds any character that is not a letter, a number, an underscore or a dash. - public static readonly Regex InvalidCharacters = new Regex("[^A-Za-z0-9_-]", RegexOptions.Compiled | RegexOptions.CultureInvariant); - - /// Validates if the first character is a letter. - public static readonly Regex InvalidInitialCharacters = new Regex("^[^A-Za-z]", RegexOptions.Compiled | RegexOptions.CultureInvariant); - - /// Validates if the string contains only numbers. - public static readonly Regex NumberMatchRegex = new Regex(@"^\d+$", RegexOptions.Compiled); - - /// Validates if a tag is an html 'base' tag. - public static readonly Regex BaseTagRegex = new Regex("]*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - /// Finds common file escaping characters. - public static readonly Regex FileEscapingRegex = new Regex("[\\\\/]\\.\\.[\\\\/]", RegexOptions.Compiled); - - /// Checks if a string is a valid Windows file extension. - public static readonly Regex FileExtensionRegex = new Regex(@"\..+;", RegexOptions.Compiled); - - /// Checks if a string is a valid Windows filename. - public static readonly Regex FileValidNameRegex = new Regex(@"^(?!(?:PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d)(?:\..+)?$)[^\x00-\x1F\xA5\\?*:\"";|\/<>]+(?Checks if a url part is a valid services framework url. - public static readonly Regex ServicesFrameworkRegex = new Regex("/API/|DESKTOPMODULES/.+/API/", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - - /// Checks for invalid usernames. - public static readonly string USERNAME_UNALLOWED_ASCII = "!\"#$%&'()*+,/:;<=>?[\\]^`{|}"; - - private const string tabPathInvalidCharsEx = "[&\\? \\./'#:\\*]"; // this value should keep same with the value used in sp BuildTabLevelAndPath to remove invalid chars. - - private static readonly Regex TabPathInvalidCharsRx = new Regex(tabPathInvalidCharsEx, RegexOptions.Compiled); - - private static readonly Stopwatch AppStopwatch = Stopwatch.StartNew(); - - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Globals)); - private static string applicationPath; - private static string desktopModulePath; - private static string imagePath; - private static string hostMapPath; - private static string hostPath; - private static string installMapPath; - private static string installPath; - - private static IServiceProvider dependencyProvider; - private static IApplicationStatusInfo applicationStatusInfo; - private static INavigationManager navigationManager; - - // global constants for the life of the application ( set in Application_Start ) - - /// - public enum PerformanceSettings - { - /// - NoCaching = 0, - - /// - LightCaching = 1, - - /// - ModerateCaching = 3, - - /// - HeavyCaching = 6, - } - - /// Enumeration Of Registration Type for portal. - /// - /// NoRegistration: Disabled registration in portal. - /// PrivateRegistration: Once user's account information has been submitted, - /// the portal Administrator will be notified and user's application will be subjected to a screening procedure. - /// If user's application is authorized, the user will receive notification of access to the portal environment. - /// PublicRegistration: Once user's account information has been submitted, - /// user will be immediately granted access to the portal environment. - /// VerifiedRegistration: Once user's account information has been submitted, - /// user will receive an email containing unique Verification Code. - /// The Verification Code will be required the first time when user attempt to sign in to the portal environment. - /// - public enum PortalRegistrationType - { - /// Disabled Registration. - NoRegistration = 0, - - /// Account need be approved by portal's administrator. - PrivateRegistration = 1, - - /// Account will be available after post registration data successful. - PublicRegistration = 2, - - /// Account will be available by verify code. - VerifiedRegistration = 3, - } - - /// Enumeration Of Application upgrade status. - public enum UpgradeStatus - { - /// The application need update to a higher version. - Upgrade = 0, - - /// The application need to install itself. - Install = 1, - - /// The application is normal running. - None = 2, - - /// The application occur error when running. - Error = 3, - - /// The application status is unknown. - /// This status should never be returned. its is only used as a flag that Status hasn't been determined. - Unknown = 4, - } - - /// Gets the application path. - public static string ApplicationPath - { - get - { - if (applicationPath == null && (HttpContext.Current != null)) - { - if (HttpContext.Current.Request.ApplicationPath == "/") - { - applicationPath = string.IsNullOrEmpty(Config.GetSetting("InstallationSubfolder")) ? string.Empty : (Config.GetSetting("InstallationSubfolder") + "/").ToLowerInvariant(); - } - else - { - applicationPath = HttpContext.Current.Request.ApplicationPath.ToLowerInvariant(); - } - } - - return applicationPath; - } - } - - /// Gets the application map path. - /// - /// The application map path. - /// - [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] - public static string ApplicationMapPath => applicationStatusInfo.ApplicationMapPath; - - /// Gets the desktop module path. - /// ApplicationPath + "/DesktopModules/". - public static string DesktopModulePath - { - get - { - if (desktopModulePath == null) - { - desktopModulePath = ApplicationPath + "/DesktopModules/"; - } - - return desktopModulePath; - } - } - - /// Gets the image path. - /// ApplicationPath + "/Images/". - public static string ImagePath - { - get - { - if (imagePath == null) - { - imagePath = ApplicationPath + "/Images/"; - } - - return imagePath; - } - } - - /// Gets the database version. - [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] - public static Version DataBaseVersion { get => applicationStatusInfo.DatabaseVersion; } - - /// Gets the host map path. - /// ApplicationMapPath + "Portals\_default\". - public static string HostMapPath - { - get - { - if (hostMapPath == null) - { - hostMapPath = Path.Combine(applicationStatusInfo.ApplicationMapPath, @"Portals\_default\"); - } - - return hostMapPath; - } - } - - /// Gets the host path. - /// ApplicationPath + "/Portals/_default/". - public static string HostPath - { - get - { - if (hostPath == null) - { - hostPath = ApplicationPath + "/Portals/_default/"; - } - - return hostPath; - } - } - - /// Gets the install map path. - /// server map path of InstallPath. - public static string InstallMapPath - { - get - { - if (installMapPath == null) - { - installMapPath = applicationStatusInfo.ApplicationMapPath + "\\Install\\"; - } - - return installMapPath; - } - } - - /// Gets the install path. - /// ApplicationPath + "/Install/". - public static string InstallPath - { - get - { - if (installPath == null) - { - installPath = ApplicationPath + "/Install/"; - } - - return installPath; - } - } - - /// Gets the status of application. - /// - [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] - public static UpgradeStatus Status { get => (UpgradeStatus)applicationStatusInfo.Status; } - - /// Gets image file types. - /// Values read from ImageTypes List. If there is not a List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico. - [Obsolete("Deprecated in DotNetNuke 9.8.1. Use ImageFileTypes instead. Scheduled removal in v11.0.0.")] - [System.Diagnostics.CodeAnalysis.SuppressMessage( - "StyleCop.CSharp.NamingRules", - "SA1300:Element should begin with upper-case letter", - Justification = "Kept to prevent a breaking change, new overload created.")] - public static string glbImageFileTypes => ImageFileTypes; - - /// Gets image file types. - /// Values read from ImageTypes List. If there is not a List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico. - public static string ImageFileTypes - { - get - { - var listController = new ListController(); - var listEntries = listController.GetListEntryInfoItems("ImageTypes"); - if (listEntries == null || !listEntries.Any()) - { - return "jpg,jpeg,jpe,gif,bmp,png,svg,ico"; - } - - return string.Join(",", listEntries.Select(l => l.Value)); - } - } - - /// Gets a value indicating for how long the application has been running. - public static TimeSpan ElapsedSinceAppStart => AppStopwatch.Elapsed; - - /// Gets or sets the name of the IIS app. - /// - /// request.ServerVariables["APPL_MD_PATH"]. - /// - public static string IISAppName { get; set; } - - /// Gets or sets the name of the server. - /// - /// server name in config file or the server's machine name. - /// - public static string ServerName { get; set; } - - /// Gets or sets the operating system version. - /// - /// The operating system version. - /// - public static Version OperatingSystemVersion { get; set; } - - /// Gets or sets the NET framework version. - /// - /// The NET framework version. - /// - public static Version NETFrameworkVersion { get; set; } - - /// Gets the .Net framework version text. - /// The .Net framework version text. - public static string FormattedNetFrameworkVersion => FormatVersion(NETFrameworkVersion, "0", 3, "."); - - /// Gets or sets the database engine version. - /// - /// The database engine version. - /// - public static Version DatabaseEngineVersion { get; set; } - - /// Gets or sets the Dependency Service. - /// The Dependency Service. - internal static IServiceProvider DependencyProvider - { - get => dependencyProvider; - set - { - dependencyProvider = value; - if (dependencyProvider is INotifyPropertyChanged hasPropertyChanged) - { - hasPropertyChanged.PropertyChanged += OnDependencyProviderChanged; - } - else - { - OnDependencyProviderChanged(null, null); - } - } - } - - /// Redirects the specified URL. - /// The URL. - /// if set to [end response]. - public static void Redirect(string url, bool endResponse) - { - try - { - HttpContext.Current.Response.Redirect(url, endResponse); - } - catch (ThreadAbortException) - { - // we are ignoreing this error simply because there is no graceful way to redirect the user, wihtout the threadabort exception. - // RobC - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - - /// Checks if incremental sqlDataProvider files exist. - /// If a 09.08.01.01.sqlDataProvider file exists for a provided version 09.08.01 this method will return true. - /// The version. - /// A value indicating whether any incremental sql script file exists. - [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] - public static partial bool IncrementalVersionExists(Version version) => applicationStatusInfo.IncrementalVersionExists(version); - - /// Builds the cross tab dataset. - /// Name of the data set. - /// The result. - /// The fixed columns. - /// The variable columns. - /// The key column. - /// The field column. - /// The field type column. - /// The string value column. - /// The numeric value column. - /// the dataset instance. - [DnnDeprecated(9, 8, 1, "No replacement")] - public static partial DataSet BuildCrossTabDataSet( - string dataSetName, - IDataReader result, - string fixedColumns, - string variableColumns, - string keyColumn, - string fieldColumn, - string fieldTypeColumn, - string stringValueColumn, - string numericValueColumn) - { - return BuildCrossTabDataSet(dataSetName, result, fixedColumns, variableColumns, keyColumn, fieldColumn, fieldTypeColumn, stringValueColumn, numericValueColumn, CultureInfo.CurrentCulture); - } - - /// converts a data reader with serialized fields into a typed data set. - /// Name of the dataset to be created. - /// Data reader that contains all field values serialized. - /// List of fixed columns, delimited by commas. Columns must be contained in DataReader. - /// List of variable columns, delimited by commas. Columns must be contained in DataReader. - /// Name of the column, that contains the row ID. Column must be contained in DataReader. - /// Name of the column, that contains the field name. Column must be contained in DataReader. - /// Name of the column, that contains the field type name. Column must be contained in DataReader. - /// Name of the column, that contains the field value, if stored as string. Column must be contained in DataReader. - /// Name of the column, that contains the field value, if stored as number. Column must be contained in DataReader. - /// culture of the field values in data reader's string value column. - /// The generated DataSet. - [DnnDeprecated(9, 8, 1, "No replacement")] - public static partial DataSet BuildCrossTabDataSet( - string dataSetName, - IDataReader result, - string fixedColumns, - string variableColumns, - string keyColumn, - string fieldColumn, - string fieldTypeColumn, - string stringValueColumn, - string numericValueColumn, - CultureInfo culture) - { - string[] arrFixedColumns = null; - string[] arrVariableColumns = null; - string[] arrField; - string fieldType; - int intColumn; - int intKeyColumn; - - // create dataset - var crosstab = new DataSet(dataSetName); - crosstab.Namespace = "NetFrameWork"; - - // create table - var tab = new DataTable(dataSetName); - - // split fixed columns - arrFixedColumns = fixedColumns.Split(','); - - // add fixed columns to table - for (intColumn = 0; intColumn < arrFixedColumns.Length; intColumn++) - { - arrField = arrFixedColumns[intColumn].Split('|'); - var col = new DataColumn(arrField[0], Type.GetType("System." + arrField[1])); - tab.Columns.Add(col); - } - - // split variable columns - if (!string.IsNullOrEmpty(variableColumns)) - { - arrVariableColumns = variableColumns.Split(','); - - // add varible columns to table - for (intColumn = 0; intColumn < arrVariableColumns.Length; intColumn++) - { - arrField = arrVariableColumns[intColumn].Split('|'); - var col = new DataColumn(arrField[0], Type.GetType("System." + arrField[1])); - col.AllowDBNull = true; - tab.Columns.Add(col); - } - } - - // add table to dataset - crosstab.Tables.Add(tab); - - // add rows to table - intKeyColumn = -1; - DataRow row = null; - while (result.Read()) - { - // loop using KeyColumn as control break - if (Convert.ToInt32(result[keyColumn]) != intKeyColumn) - { - // add row - if (intKeyColumn != -1) - { - tab.Rows.Add(row); - } - - // create new row - row = tab.NewRow(); - - // assign fixed column values - for (intColumn = 0; intColumn < arrFixedColumns.Length; intColumn++) - { - arrField = arrFixedColumns[intColumn].Split('|'); - row[arrField[0]] = result[arrField[0]]; - } - - // initialize variable column values - if (!string.IsNullOrEmpty(variableColumns)) - { - for (intColumn = 0; intColumn < arrVariableColumns.Length; intColumn++) - { - arrField = arrVariableColumns[intColumn].Split('|'); - switch (arrField[1]) - { - case "Decimal": - row[arrField[0]] = 0; - break; - case "String": - row[arrField[0]] = string.Empty; - break; - } - } - } - - intKeyColumn = Convert.ToInt32(result[keyColumn]); - } - - // assign pivot column value - if (!string.IsNullOrEmpty(fieldTypeColumn)) - { - fieldType = result[fieldTypeColumn].ToString(); - } - else - { - fieldType = "String"; - } - - switch (fieldType) - { - case "Decimal": - row[Convert.ToInt32(result[fieldColumn])] = result[numericValueColumn]; - break; - case "String": - if (ReferenceEquals(culture, CultureInfo.CurrentCulture)) - { - row[result[fieldColumn].ToString()] = result[stringValueColumn]; - } - else - { - switch (tab.Columns[result[fieldColumn].ToString()].DataType.ToString()) - { - case "System.Decimal": - case "System.Currency": - row[result[fieldColumn].ToString()] = decimal.Parse(result[stringValueColumn].ToString(), culture); - break; - case "System.Int32": - row[result[fieldColumn].ToString()] = int.Parse(result[stringValueColumn].ToString(), culture); - break; - default: - row[result[fieldColumn].ToString()] = result[stringValueColumn]; - break; - } - } - - break; - } - } - - result.Close(); - - // add row - if (intKeyColumn != -1) - { - tab.Rows.Add(row); - } - - // finalize dataset - crosstab.AcceptChanges(); - - // return the dataset - return crosstab; - } - - /// Converts the datareader to dataset. - /// The reader. - /// the dataset instance. - public static DataSet ConvertDataReaderToDataSet(IDataReader reader) - { - // add datatable to dataset - var objDataSet = new DataSet(); - - try - { - do - { - objDataSet.Tables.Add(ConvertDataReaderToDataTable(reader, false)); - } - while (reader.NextResult()); - } - finally - { - reader.Close(); - } - - return objDataSet; - } - - /// Converts the datareader to datatable. - /// The reader. - /// the datatable instance. - public static DataTable ConvertDataReaderToDataTable(IDataReader reader) - { - return ConvertDataReaderToDataTable(reader, true); - } - - /// Converts the datareader to datatable. - /// The reader. - /// Whether close reader. - /// the datatable instance. - public static DataTable ConvertDataReaderToDataTable(IDataReader reader, bool closeReader) - { - try - { - // create datatable from datareader - var objDataTable = new DataTable(); - int intFieldCount = reader.FieldCount; - int intCounter; - for (intCounter = 0; intCounter <= intFieldCount - 1; intCounter++) - { - objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter)); - } - - // populate datatable - objDataTable.BeginLoadData(); - var objValues = new object[intFieldCount]; - while (reader.Read()) - { - reader.GetValues(objValues); - objDataTable.LoadDataRow(objValues, true); - } - - objDataTable.EndLoadData(); - return objDataTable; - } - finally - { - if (closeReader) - { - reader.Close(); - } - } - } - - /// Gets the absolute server path. - /// The request. - /// absolute server path. - public static string GetAbsoluteServerPath(HttpRequest request) - { - string strServerPath; - strServerPath = request.MapPath(request.ApplicationPath); - if (!strServerPath.EndsWith("\\")) - { - strServerPath += "\\"; - } - - return strServerPath; - } - - /// Gets the ApplicationName for the MemberRole API. - /// - /// This overload is used to get the current ApplcationName. The Application - /// Name is in the form Prefix_Id, where Prefix is the object qualifier - /// for this instance of DotNetNuke, and Id is the current PortalId for normal - /// users or glbSuperUserAppName for SuperUsers. - /// - /// A string representing the application name. - public static string GetApplicationName() - { - string appName; - if (HttpContext.Current.Items["ApplicationName"] == null || string.IsNullOrEmpty(HttpContext.Current.Items["ApplicationName"].ToString())) - { - var portalSettings = PortalController.Instance.GetCurrentSettings(); - if (portalSettings == null) - { - appName = "/"; - } - else - { - appName = GetApplicationName(portalSettings.PortalId); - } - } - else - { - appName = Convert.ToString(HttpContext.Current.Items["ApplicationName"]); - } - - return appName; - } - - /// Gets the ApplicationName for the MemberRole API. - /// - /// This overload is used to build the Application Name from the Portal Id. - /// - /// The id of the portal (site). - /// A string representing the application name. - public static string GetApplicationName(int portalID) - { - string appName; - - // Get the Data Provider Configuration - ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration("data"); - - // Read the configuration specific information for the current Provider - var objProvider = (Provider)providerConfiguration.Providers[providerConfiguration.DefaultProvider]; - - // Get the Object Qualifier from the Provider Configuration - string objectQualifier = objProvider.Attributes["objectQualifier"]; - if (!string.IsNullOrEmpty(objectQualifier) && objectQualifier.EndsWith("_") == false) - { - objectQualifier += "_"; - } - - appName = objectQualifier + Convert.ToString(portalID); - return appName; - } - - /// Finds the database version. - /// The major. - /// The minor. - /// The build. - /// return if can find the specific version, otherwise will retur . - public static bool FindDatabaseVersion(int major, int minor, int build) - { - bool version = false; - IDataReader dr = null; - try - { - dr = DataProvider.Instance().FindDatabaseVersion(major, minor, build); - if (dr.Read()) - { - version = true; - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return version; - } - - /// Updates the database version. - /// The version. - [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] - public static partial void UpdateDataBaseVersion(Version version) => applicationStatusInfo.UpdateDatabaseVersion(version); - - /// Updates the database version. - /// The version. - /// The increment (revision) number. - [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] - public static partial void UpdateDataBaseVersionIncrement(Version version, int increment) => - applicationStatusInfo.UpdateDatabaseVersionIncrement(version, increment); - - /// Gets the last applied iteration (revision). - /// The version for which to check the last revision. - /// The last applied iteration (revision) for the requested version. - [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] - public static partial int GetLastAppliedIteration(Version version) => - applicationStatusInfo.GetLastAppliedIteration(version); - - /// Adds the port. - /// The HTTP alias. - /// The original URL. - /// url with port if the post number is not 80. - public static string AddPort(string httpAlias, string originalUrl) - { - var uri = new Uri(originalUrl); - var aliasUri = new Uri(httpAlias); - - if (!uri.IsDefaultPort) - { - httpAlias = AddHTTP(aliasUri.Host + ":" + uri.Port + aliasUri.LocalPath); - } - - return httpAlias; - } - - /// Gets the name of the domain. - /// The request. - /// domain name. - public static string GetDomainName(HttpRequest request) - { - return GetDomainName(new HttpRequestWrapper(request), false); - } - - /// Gets the name of the domain. - /// The request. - /// domain name. - public static string GetDomainName(HttpRequestBase request) - { - return GetDomainName(request, false); - } - - /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ). - /// The request. - /// if set to [parse port number]. - /// domain name. - public static string GetDomainName(HttpRequest request, bool parsePortNumber) - { - return GetDomainName(new HttpRequestWrapper(request), parsePortNumber); - } - - /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ). - /// The request. - /// if set to [parse port number]. - /// domain name. - public static string GetDomainName(HttpRequestBase request, bool parsePortNumber) - { - return TestableGlobals.Instance.GetDomainName(request.Url, parsePortNumber); - } - - /// Determin whether use port number by the value in config file. - /// - /// if use port number, otherwise, return . - /// - public static bool UsePortNumber() - { - bool usePort = true; - if (Config.GetSetting("UsePortNumber") != null) - { - usePort = bool.Parse(Config.GetSetting("UsePortNumber")); - } - - return usePort; - } - - /// Gets the file list. - /// file list. - public static ArrayList GetFileList() - { - return GetFileList(-1, string.Empty, true, string.Empty, false); - } - - /// Gets the file list. - /// The portal id. - /// file list. - public static ArrayList GetFileList(int portalId) - { - return GetFileList(portalId, string.Empty, true, string.Empty, false); - } - - /// Gets the file list. - /// The portal id. - /// The STR extensions. - /// file list. - public static ArrayList GetFileList(int portalId, string strExtensions) - { - return GetFileList(portalId, strExtensions, true, string.Empty, false); - } - - /// Gets the file list. - /// The portal id. - /// The STR extensions. - /// if set to [none specified]. - /// file list. - public static ArrayList GetFileList(int portalId, string strExtensions, bool noneSpecified) - { - return GetFileList(portalId, strExtensions, noneSpecified, string.Empty, false); - } - - /// Gets the file list. - /// The portal id. - /// The STR extensions. - /// if set to [none specified]. - /// The folder. - /// file list. - public static ArrayList GetFileList(int portalId, string strExtensions, bool noneSpecified, string folder) - { - return GetFileList(portalId, strExtensions, noneSpecified, folder, false); - } - - /// Gets the file list. - /// The portal id. - /// The STR extensions. - /// if set to [none specified]. - /// The folder. - /// if set to [include hidden]. - /// file list. - public static ArrayList GetFileList(int portalId, string strExtensions, bool noneSpecified, string folder, bool includeHidden) - { - var arrFileList = new ArrayList(); - if (noneSpecified) - { - arrFileList.Add(new FileItem(string.Empty, "<" + Localization.GetString("None_Specified") + ">")); - } - - var objFolder = FolderManager.Instance.GetFolder(portalId, folder); - - if (objFolder != null) - { - try - { - var files = FolderManager.Instance.GetFiles(objFolder); - var fileManager = FileManager.Instance; - - foreach (var file in files) - { - if (FilenameMatchesExtensions(file.FileName, strExtensions)) - { - if (file.SupportsFileAttributes) - { - if (fileManager.FileExists(objFolder, file.FileName)) - { - if (includeHidden) - { - arrFileList.Add(new FileItem(file.FileId.ToString(), file.FileName)); - } - else - { - var attributes = file.FileAttributes; - - if ((attributes & FileAttributes.Hidden) != FileAttributes.Hidden) - { - arrFileList.Add(new FileItem(file.FileId.ToString(), file.FileName)); - } - } - } - } - else - { - // File is stored in DB - Just add to arraylist - arrFileList.Add(new FileItem(file.FileId.ToString(), file.FileName)); - } - } - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - } - - return arrFileList; - } - - /// Gets the host portal settings. - /// Host portal settings. - [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] - public static partial PortalSettings GetHostPortalSettings() - => GetHostPortalSettings(GetCurrentServiceProvider().GetRequiredService()); - - /// Gets the host portal settings. - /// The host settings. - /// Host portal settings. - public static PortalSettings GetHostPortalSettings(IHostSettings hostSettings) - { - int tabId = -1; - int portalId = -1; - IPortalAliasInfo objPortalAliasInfo = null; - - // if the portal alias exists - if (hostSettings.HostPortalId > Null.NullInteger) - { - portalId = hostSettings.HostPortalId; - - // use the host portal - objPortalAliasInfo = new PortalAliasInfo(); - objPortalAliasInfo.PortalId = portalId; - } - - // load the PortalSettings into current context - return new PortalSettings(tabId, objPortalAliasInfo as PortalAliasInfo); - } - - /// Gets the portal domain name. - /// The portal alias. - /// The request or null. - /// if set to calls on the result. - /// domain name. - public static string GetPortalDomainName(string strPortalAlias, HttpRequest request, bool blnAddHTTP) - { - string strDomainName = string.Empty; - string strURL = string.Empty; - int intAlias; - if (request != null) - { - strURL = GetDomainName(request); - } - - string[] arrPortalAlias = strPortalAlias.Split(','); - for (intAlias = 0; intAlias <= arrPortalAlias.Length - 1; intAlias++) - { - if (arrPortalAlias[intAlias] == strURL) - { - strDomainName = arrPortalAlias[intAlias]; - } - } - - if (string.IsNullOrEmpty(strDomainName)) - { - strDomainName = arrPortalAlias[0]; - } - - if (blnAddHTTP) - { - strDomainName = AddHTTP(strDomainName); - } - - return strDomainName; - } - - /// Gets the portal settings. - /// Portal settings. - public static PortalSettings GetPortalSettings() - { - PortalSettings portalSettings = null; - - // Try getting the settings from the Context - if (HttpContext.Current != null) - { - portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; - } - - // If nothing then try getting the Host Settings - if (portalSettings == null) - { - portalSettings = GetHostPortalSettings(); - } - - return portalSettings; - } - - /// Returns the folder path under the root for the portal. - /// The folder the absolute path. - /// Portal Id. - /// A string containing the subfolder path. - public static string GetSubFolderPath(string strFileNamePath, int portalId) - { - string parentFolderName; - if (portalId == Null.NullInteger) - { - parentFolderName = HostMapPath.Replace("/", "\\"); - } - else - { - PortalInfo objPortal = PortalController.Instance.GetPortal(portalId); - parentFolderName = objPortal.HomeDirectoryMapPath.Replace("/", "\\"); - } - - string strFolderpath = strFileNamePath.Substring(0, strFileNamePath.LastIndexOf("\\") + 1); - return strFolderpath.Substring(parentFolderName.Length).Replace("\\", "/"); - } - - /// The GetTotalRecords method gets the number of Records returned. - /// An containing the Total number of records. - /// The total number of records in the data reader. - public static int GetTotalRecords(ref IDataReader dr) - { - int total = 0; - if (dr.Read()) - { - try - { - total = Convert.ToInt32(dr["TotalRecords"]); - } - catch (Exception exc) - { - Logger.Error(exc); - total = -1; - } - } - - return total; - } - - /// Sets the status. - /// The status. - [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] - public static partial void SetStatus(UpgradeStatus status) => - applicationStatusInfo.SetStatus((DotNetNuke.Abstractions.Application.UpgradeStatus)status); - - /// - /// ImportFile - converts a file url (/Portals/0/somefile.gif) to the appropriate - /// FileID=xx identification for use in importing portals, tabs and modules. - /// - /// The id of the portal (site) on which the file is imported. - /// The url to the file. - /// The file handler url for the file (FileID=xxxx). - public static string ImportFile(int portalId, string url) - { - string strUrl = url; - if (GetURLType(url) == TabType.File) - { - var fileName = Path.GetFileName(url); - - var folderPath = url.Substring(0, url.LastIndexOf(fileName)); - var folder = FolderManager.Instance.GetFolder(portalId, folderPath); - - if (folder != null) - { - var file = FileManager.Instance.GetFile(folder, fileName); - if (file != null) - { - strUrl = "FileID=" + file.FileId; - } - } - } - - return strUrl; - } - - /// Encode the post url. - /// The post url. - /// encoded value. - public static string HTTPPOSTEncode(string strPost) - { - strPost = strPost.Replace("\\", string.Empty); - strPost = HttpUtility.UrlEncode(strPost); - strPost = strPost.Replace("%2f", "/"); - return strPost; - } - - /// Sets the ApplicationName for the MemberRole API. - /// - /// This overload takes a the PortalId. - /// - /// The Portal ID. - public static void SetApplicationName(int portalId) - { - HttpContext.Current.Items["ApplicationName"] = GetApplicationName(portalId); - } - - /// Sets the ApplicationName for the MemberRole API. - /// - /// This overload takes a the PortalId. - /// - /// The Application Name to set. - public static void SetApplicationName(string applicationName) - { - HttpContext.Current.Items["ApplicationName"] = applicationName; - } - - /// Formats the address on a single line ( ie. Unit, Street, City, Region, Country, PostalCode ). - /// The unit. - /// The street. - /// The city. - /// The region. - /// The country. - /// The postal code. - /// A string containing the whole address on a single line. - public static string FormatAddress(object unit, object street, object city, object region, object country, object postalCode) - { - string strAddress = string.Empty; - if (unit != null) - { - if (!string.IsNullOrEmpty(unit.ToString().Trim())) - { - strAddress += ", " + unit; - } - } - - if (street != null) - { - if (!string.IsNullOrEmpty(street.ToString().Trim())) - { - strAddress += ", " + street; - } - } - - if (city != null) - { - if (!string.IsNullOrEmpty(city.ToString().Trim())) - { - strAddress += ", " + city; - } - } - - if (region != null) - { - if (!string.IsNullOrEmpty(region.ToString().Trim())) - { - strAddress += ", " + region; - } - } - - if (country != null) - { - if (!string.IsNullOrEmpty(country.ToString().Trim())) - { - strAddress += ", " + country; - } - } - - if (postalCode != null) - { - if (!string.IsNullOrEmpty(postalCode.ToString().Trim())) - { - strAddress += ", " + postalCode; - } - } - - if (!string.IsNullOrEmpty(strAddress.Trim())) - { - strAddress = strAddress.Substring(2); - } - - return strAddress; - } - - /// Formats the system.version into the standard format nn.nn.nn. - /// The version. - /// Formatted version as string. - public static string FormatVersion(Version version) - { - return FormatVersion(version, false); - } - - /// Formats the version. - /// The version. - /// if set to [include build]. - /// Formatted version as string. - /// - /// - /// var version = new Version(6, 0, 0, 147); - /// string formattedVersion = FormatVersion(version, true); // formattedVersion's value will be: 06.00.00(147) - /// - /// - public static string FormatVersion(Version version, bool includeBuild) - { - string strVersion = version.Major.ToString("00") + "." + version.Minor.ToString("00") + "." + version.Build.ToString("00"); - if (includeBuild) - { - strVersion += " (" + version.Revision + ")"; - } - - return strVersion; - } - - /// Formats a version into the standard format nn.nn.nn. - /// The version to be formatted. - /// The field format. - /// The field count. - /// The delimiter character. - /// Formatted version as a string. - public static string FormatVersion(Version version, string fieldFormat, int fieldCount, string delimiterCharacter) - { - string strVersion = string.Empty; - int intZero = 0; - if (version != null) - { - if (fieldCount > 0) - { - if (version.Major >= 0) - { - strVersion += version.Major.ToString(fieldFormat); - } - else - { - strVersion += intZero.ToString(fieldFormat); - } - } - - if (fieldCount > 1) - { - strVersion += delimiterCharacter; - if (version.Minor >= 0) - { - strVersion += version.Minor.ToString(fieldFormat); - } - else - { - strVersion += intZero.ToString(fieldFormat); - } - } - - if (fieldCount > 2) - { - strVersion += delimiterCharacter; - if (version.Build >= 0) - { - strVersion += version.Build.ToString(fieldFormat); - } - else - { - strVersion += intZero.ToString(fieldFormat); - } - } - - if (fieldCount > 3) - { - strVersion += delimiterCharacter; - if (version.Revision >= 0) - { - strVersion += version.Revision.ToString(fieldFormat); - } - else - { - strVersion += intZero.ToString(fieldFormat); - } - } - } - - return strVersion; - } - - /// Cloaks the text, obfuscate sensitive data to prevent collection by robots and spiders and crawlers. - /// The personal info. - /// obfuscated sensitive data by hustling ASCII characters. - public static string CloakText(string personalInfo) - { - if (personalInfo == null) - { - return Null.NullString; - } - - const string Script = @" - - "; - - var characterCodes = personalInfo.Select(ch => ((int)ch).ToString(CultureInfo.InvariantCulture)); - return string.Format(Script, string.Join(",", characterCodes.ToArray())); - } - - /// Gets the medium date by current culture. - /// The date. - /// return formatted content of the date if paramter isn't empty, else return the parameter. - /// - /// - /// var mediumDate = GetMediumDate("6/1/2011"); - /// - /// - public static string GetMediumDate(string strDate) - { - if (!string.IsNullOrEmpty(strDate)) - { - DateTime datDate = Convert.ToDateTime(strDate); - string strYear = datDate.Year.ToString(); - string strMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(datDate.Month); - string strDay = datDate.Day.ToString(); - strDate = strDay + "-" + strMonth + "-" + strYear; - } - - return strDate; - } - - /// Gets the short date. - /// The date. - /// short date content of the input. - public static string GetShortDate(string strDate) - { - if (!string.IsNullOrEmpty(strDate)) - { - DateTime datDate = Convert.ToDateTime(strDate); - string strYear = datDate.Year.ToString(); - string strMonth = datDate.Month.ToString(); - string strDay = datDate.Day.ToString(); - strDate = strMonth + "/" + strDay + "/" + strYear; - } - - return strDate; - } - - /// Determines whether current request contains admin control information. - /// - /// if current request contains admin control information; otherwise, . - /// - public static bool IsAdminControl() - { - // This is needed to avoid an exception if there is no Context. This will occur if code is called from the Scheduler - if (HttpContext.Current == null) - { - return false; - } - - return (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) || (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"])); - } - - /// Determines whether current request use admin skin. - /// - /// if current request use admin skin; otherwise, . - /// - public static bool IsAdminSkin() - { - bool isAdminSkin = Null.NullBoolean; - if (HttpContext.Current != null) - { - string adminKeys = "tab,module,importmodule,exportmodule,help"; - string controlKey = string.Empty; - if (HttpContext.Current.Request.QueryString["ctl"] != null) - { - controlKey = HttpContext.Current.Request.QueryString["ctl"].ToLowerInvariant(); - } - - int moduleID = -1; - if (HttpContext.Current.Request.QueryString["mid"] != null) - { - if (!int.TryParse(HttpContext.Current.Request.QueryString["mid"], out moduleID)) - { - moduleID = -1; - } - } - - isAdminSkin = (!string.IsNullOrEmpty(controlKey) && controlKey != "view" && moduleID != -1) || - (!string.IsNullOrEmpty(controlKey) && adminKeys.IndexOf(controlKey) != -1 && moduleID == -1); - } - - return isAdminSkin; - } - - /// Returns whether the current tab is in EditMode. - /// if the tab is in Edit mode; otherwise . - public static bool IsEditMode() - { - return Personalization.GetUserMode() == PortalSettings.Mode.Edit && TabPermissionController.CanAddContentToPage(); - } - - /// Returns whether the current tab is in LayoutMode. - /// if the current tab is in layout mode; otherwise . - public static bool IsLayoutMode() - { - return TabPermissionController.CanAddContentToPage() && Personalization.GetUserMode() == PortalSettings.Mode.Layout; - } - - /// Creates the RSS. - /// The dr. - /// The title field. - /// The URL field. - /// The created date field. - /// The syndicate field. - /// Name of the domain. - /// Name of the file. - public static void CreateRSS( - IDataReader dr, - string titleField, - string urlField, - string createdDateField, - string syndicateField, - string domainName, - string fileName) - { - // Obtain PortalSettings from Current Context - var portalSettings = PortalController.Instance.GetCurrentSettings(); - var strRSS = new StringBuilder(); - var strRelativePath = domainName + fileName.Substring(fileName.IndexOf("\\Portals", StringComparison.InvariantCultureIgnoreCase)).Replace("\\", "/"); - strRelativePath = strRelativePath.Substring(0, strRelativePath.LastIndexOf("/", StringComparison.InvariantCulture)); - try - { - while (dr.Read()) - { - if (!int.TryParse((dr[syndicateField] ?? string.Empty).ToString(), out var field) || field <= 0) - { - continue; - } - - strRSS.AppendLine(" "); - strRSS.AppendLine(" " + dr[titleField] + ""); - var drUrl = (dr["URL"] ?? string.Empty).ToString(); - if (drUrl.IndexOf("://", StringComparison.InvariantCulture) == -1) - { - strRSS.Append(" "); - if (NumberMatchRegex.IsMatch(drUrl)) - { - strRSS.Append(domainName + "/" + glbDefaultPage + "?tabid=" + dr[urlField]); - } - else - { - strRSS.Append(strRelativePath + dr[urlField]); - } - - strRSS.AppendLine(""); - } - else - { - strRSS.AppendLine(" " + dr[urlField] + ""); - } - - strRSS.AppendLine(" " + portalSettings.PortalName + " " + GetMediumDate(dr[createdDateField].ToString()) + ""); - strRSS.AppendLine(" "); - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - CBO.CloseDataReader(dr, true); - } - - if (strRSS.Length == 0) - { - strRSS.Append("" + Environment.NewLine + "" + Environment.NewLine + " " + Environment.NewLine + " " + - portalSettings.PortalName + "" + Environment.NewLine + " " + domainName + "" + Environment.NewLine + " " + - portalSettings.PortalName + "" + Environment.NewLine + " en-us" + Environment.NewLine + " " + - (!string.IsNullOrEmpty(portalSettings.FooterText) ? portalSettings.FooterText.Replace("[year]", DateTime.Now.Year.ToString()) : string.Empty) + - "" + Environment.NewLine + " " + portalSettings.Email + "" + Environment.NewLine + strRSS + " " + Environment.NewLine + - ""); - File.WriteAllText(fileName, strRSS.ToString()); - } - else - { - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - } - } - - /// injects the upload directory into raw HTML for src and background tags. - /// raw HTML text. - /// path of portal image directory. - /// HTML with paths for images and background corrected. - public static string ManageUploadDirectory(string strHTML, string strUploadDirectory) - { - strHTML = ManageTokenUploadDirectory(strHTML, strUploadDirectory, "src"); - return ManageTokenUploadDirectory(strHTML, strUploadDirectory, "background"); - } - - /// Injects the upload directory into raw HTML for a single token. - /// The raw HTML text. - /// The path of portal image directory. - /// The token to be replaced. - /// HTML with paths for images and background corrected. - /// - /// Called by ManageUploadDirectory for each token. - /// - public static string ManageTokenUploadDirectory(string strHTML, string strUploadDirectory, string strToken) - { - int tokenStartPosition; - int endOfUrl; - int urlStartPosition = 0; - int tokenLength; - string strURL; - var sbBuff = new StringBuilder(string.Empty); - if (!string.IsNullOrEmpty(strHTML)) - { - tokenLength = strToken.Length + 2; - string uploadDirectory = strUploadDirectory.ToLowerInvariant(); - - tokenStartPosition = strHTML.IndexOf(strToken + "=\"", StringComparison.InvariantCultureIgnoreCase); - while (tokenStartPosition != -1) - { - sbBuff.Append(strHTML.Substring(urlStartPosition, tokenStartPosition - urlStartPosition + tokenLength)); // keep characters left of URL - urlStartPosition = tokenStartPosition + tokenLength; - endOfUrl = strHTML.IndexOf("\"", urlStartPosition); - if (endOfUrl >= 0) - { - strURL = strHTML.Substring(urlStartPosition, endOfUrl - urlStartPosition).ToLowerInvariant(); - } - else - { - strURL = strHTML.Substring(urlStartPosition).ToLowerInvariant(); - } - - // add upload directory if we are linking internally and the upload directory is not already included - if (!strURL.Contains("://") && !strURL.StartsWith("/") && !strURL.StartsWith(uploadDirectory)) - { - sbBuff.Append(strUploadDirectory); - } - - // find position of next occurrance: - tokenStartPosition = strHTML.IndexOf(strToken + "=\"", urlStartPosition + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); - } - - if (urlStartPosition > -1) - { - sbBuff.Append(strHTML.Substring(urlStartPosition)); - } - } - - return sbBuff.ToString(); - } - - /// Finds the control recursive from child to parent. - /// current control. - /// the control name which want to find out. - /// control which'name is strControlName, or else return null if didn't match any control. - public static Control FindControlRecursive(Control objControl, string strControlName) - { - if (objControl.Parent == null) - { - return null; - } - else - { - if (objControl.Parent.FindControl(strControlName) != null) - { - return objControl.Parent.FindControl(strControlName); - } - else - { - return FindControlRecursive(objControl.Parent, strControlName); - } - } - } - - /// Searches control hierarchy from top down to find a control matching the passed in name. - /// Root control to begin searching. - /// Name of control to look for. - /// The found control or null. - /// - /// This differs from FindControlRecursive in that it looks down the control hierarchy, whereas, the - /// FindControlRecursive starts at the passed in control and walks the tree up. Therefore, this function is - /// more a expensive task. - /// - public static Control FindControlRecursiveDown(Control objParent, string strControlName) - { - Control objCtl; - objCtl = objParent.FindControl(strControlName); - if (objCtl == null) - { - foreach (Control objChild in objParent.Controls) - { - objCtl = FindControlRecursiveDown(objChild, strControlName); - if (objCtl != null) - { - break; - } - } - } - - return objCtl; - } - - /// Sets the form focus. - /// The control. - public static void SetFormFocus(Control control) - { - if (control.Page != null && control.Visible) - { - if (control.Page.Request.Browser.EcmaScriptVersion.Major >= 1) - { - // JH dnn.js mod - if (ClientAPI.ClientAPIDisabled() == false) - { - JavaScript.RegisterClientReference(control.Page, ClientAPI.ClientNamespaceReferences.dnn); - DNNClientAPI.SetInitialFocus(control.Page, control); - } - else - { - // Create JavaScript - var sb = new StringBuilder(); - sb.Append(""); - - // Register Client Script - ClientAPI.RegisterClientScriptBlock(control.Page, "InitialFocus", sb.ToString()); - } - } - } - } - - /// Gets the external request. - /// The address. - /// Web request. - [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] - public static partial HttpWebRequest GetExternalRequest(string address) - => GetExternalRequest(GetCurrentServiceProvider().GetRequiredService(), address); - - /// Gets the external request. - /// The host settings. - /// The address. - /// Web request. - public static HttpWebRequest GetExternalRequest(IHostSettings hostSettings, string address) - { - // Create the request object - var objRequest = (HttpWebRequest)WebRequest.Create(address); - - // Set a time-out to the request ... 10 seconds - objRequest.Timeout = (int)hostSettings.WebRequestTimeout.TotalMilliseconds; - - // Attach a User Agent to the request - objRequest.UserAgent = "DotNetNuke"; - - // If there is Proxy info, apply it to the request - if (!string.IsNullOrEmpty(hostSettings.ProxyServer)) - { - // Create a new Proxy - WebProxy proxy; - - // Create a new Network Credentials item - NetworkCredential proxyCredentials; - - // Fill Proxy info from host settings - proxy = new WebProxy(hostSettings.ProxyServer, hostSettings.ProxyPort); - if (!string.IsNullOrEmpty(hostSettings.ProxyUsername)) - { - // Fill the credential info from host settings - proxyCredentials = new NetworkCredential(hostSettings.ProxyUsername, hostSettings.ProxyPassword); - - // Apply credentials to proxy - proxy.Credentials = proxyCredentials; - } - - // Apply Proxy to request - objRequest.Proxy = proxy; - } - - return objRequest; - } - - /// Gets the external request. - /// The address. - /// The credentials. - /// Web request. - [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] - public static partial HttpWebRequest GetExternalRequest(string address, NetworkCredential credentials) - => GetExternalRequest(GetCurrentServiceProvider().GetRequiredService(), address, credentials); - - /// Gets the external request. - /// The host settings. - /// The address. - /// The credentials. - /// Web request. - public static HttpWebRequest GetExternalRequest(IHostSettings hostSettings, string address, NetworkCredential credentials) - { - // Create the request object - var objRequest = (HttpWebRequest)WebRequest.Create(address); - - // Set a time-out to the request ... 10 seconds - objRequest.Timeout = (int)hostSettings.WebRequestTimeout.TotalMilliseconds; - - // Attach a User Agent to the request - objRequest.UserAgent = "DotNetNuke"; - - // Attach supplied credentials - if (credentials.UserName != null) - { - objRequest.Credentials = credentials; - } - - // If there is Proxy info, apply it to the request - if (!string.IsNullOrEmpty(hostSettings.ProxyServer)) - { - // Create a new Proxy - WebProxy proxy; - - // Create a new Network Credentials item - NetworkCredential proxyCredentials; - - // Fill Proxy info from host settings - proxy = new WebProxy(hostSettings.ProxyServer, hostSettings.ProxyPort); - if (!string.IsNullOrEmpty(hostSettings.ProxyUsername)) - { - // Fill the credential info from host settings - proxyCredentials = new NetworkCredential(hostSettings.ProxyUsername, hostSettings.ProxyPassword); - - // Apply credentials to proxy - proxy.Credentials = proxyCredentials; - } - - objRequest.Proxy = proxy; - } - - return objRequest; - } - - /// Deletes the folder recursive, include the folder itself will be deleted. - /// The root. - public static void DeleteFolderRecursive(string strRoot) - => FileSystemUtils.DeleteFolderRecursive(strRoot); - - /// Deletes the folder recursive, include the folder itself will be deleted. - /// The root. - /// The cancellation token. - /// A indicating completion. - public static async Task DeleteFolderRecursiveAsync(string strRoot, CancellationToken cancellationToken = default) - => await FileSystemUtils.DeleteFolderRecursiveAsync(strRoot, cancellationToken); - - /// Deletes the files recursive which match the filter, will not delete folders and will ignore folder which is hidden or system. - /// The root. - /// The filter. - public static void DeleteFilesRecursive(string strRoot, string filter) - => FileSystemUtils.DeleteFilesRecursive(strRoot, filter); - - /// Deletes the files recursive which match the filter, will not delete folders and will ignore folder which is hidden or system. - /// The root. - /// The filter. - /// The cancellation token. - /// A indicating completion. - public static async Task DeleteFilesRecursiveAsync(string strRoot, string filter, CancellationToken cancellationToken = default) - => await FileSystemUtils.DeleteFilesRecursiveAsync(strRoot, filter, cancellationToken); - - /// Cleans the name of the file. - /// Name of the file. - /// clean name. - public static string CleanFileName(string fileName) - { - return CleanFileName(fileName, string.Empty, string.Empty); - } - - /// Cleans the name of the file. - /// Name of the file. - /// The bad chars. - /// clean name. - public static string CleanFileName(string fileName, string badChars) - { - return CleanFileName(fileName, badChars, string.Empty); - } - - /// Cleans the name of the file. - /// Name of the file. - /// The bad chars. - /// The replace char. - /// clean name. - public static string CleanFileName(string fileName, string badChars, string replaceChar) - { - string strFileName = fileName; - if (string.IsNullOrEmpty(badChars)) - { - badChars = ":/\\?*|" + ((char)34) + ((char)39) + ((char)9); - } - - if (string.IsNullOrEmpty(replaceChar)) - { - replaceChar = "_"; - } - - int intCounter; - for (intCounter = 0; intCounter <= badChars.Length - 1; intCounter++) - { - strFileName = strFileName.Replace(badChars.Substring(intCounter, 1), replaceChar); - } - - return strFileName; - } - - /// - /// CleanName - removes characters from Module/Tab names that are being used for file names - /// in Module/Tab Import/Export. - /// - /// The name to clean. - /// A cleaned string. - public static string CleanName(string name) - { - string strName = name; - string strBadChars = ". ~`!@#$%^&*()-_+={[}]|\\:;<,>?/" + ((char)34) + ((char)39); - int intCounter; - for (intCounter = 0; intCounter <= strBadChars.Length - 1; intCounter++) - { - strName = strName.Replace(strBadChars.Substring(intCounter, 1), string.Empty); - } - - return strName; - } - - /// - /// CreateValidClass - removes characters from Module/Tab names which are invalid - /// for use as an XHTML class attribute / CSS class selector value and optionally - /// prepends the letter 'A' if the first character is not alphabetic. This differs - /// from CreateValidID which replaces invalid characters with an underscore - /// and replaces the first letter with an 'A' if it is not alphabetic. - /// - /// String to use to create the class value. - /// If set true, validate whether the first character - /// is alphabetic and, if not, prepend the letter 'A' to the returned value. - /// A string suitable for use as a class value. - public static string CreateValidClass(string inputValue, bool validateFirstChar) - { - string returnValue = Null.NullString; - - // Regex is expensive so we will cache the results in a lookup table - var validClassLookupDictionary = CBO.GetCachedObject>( - new CacheItemArgs("ValidClassLookup", 200, CacheItemPriority.NotRemovable), - (CacheItemArgs cacheItemArgs) => new SharedDictionary()); - - bool idFound = Null.NullBoolean; - using (ISharedCollectionLock readLock = validClassLookupDictionary.GetReadLock()) - { - if (validClassLookupDictionary.TryGetValue(inputValue, out var className)) - { - // Return value - returnValue = className; - idFound = true; - } - } - - if (!idFound) - { - using (ISharedCollectionLock writeLock = validClassLookupDictionary.GetWriteLock()) - { - if (!validClassLookupDictionary.ContainsKey(inputValue)) - { - // Create Valid Class - // letters ([a-zA-Z]), digits ([0-9]), hyphens ("-") and underscores ("_") are valid in class values - // Remove all characters that aren't in the list - returnValue = InvalidCharacters.Replace(inputValue, string.Empty); - - // If we're asked to validate the first character... - if (validateFirstChar) - { - // classes should begin with a letter ([A-Za-z])' - // prepend a starting non-letter character with an A - if (InvalidCharacters.IsMatch(returnValue)) - { - returnValue = "A" + returnValue; - } - } - - // put in Dictionary - validClassLookupDictionary[inputValue] = returnValue; - } - } - } - - // Return Value - return returnValue; - } - - /// Creates the valid ID. - /// The input value. - /// String with a valid ID. - public static string CreateValidID(string inputValue) - { - string returnValue = Null.NullString; - - // Regex is expensive so we will cache the results in a lookup table - var validIDLookupDictionary = CBO.GetCachedObject>( - new CacheItemArgs("ValidIDLookup", 200, CacheItemPriority.NotRemovable), - (CacheItemArgs cacheItemArgs) => new SharedDictionary()); - - bool idFound = Null.NullBoolean; - using (ISharedCollectionLock readLock = validIDLookupDictionary.GetReadLock()) - { - if (validIDLookupDictionary.TryGetValue(inputValue, out var id)) - { - // Return value - returnValue = id; - idFound = true; - } - } - - if (!idFound) - { - using (ISharedCollectionLock writeLock = validIDLookupDictionary.GetWriteLock()) - { - if (!validIDLookupDictionary.ContainsKey(inputValue)) - { - // Create Valid ID - // '... letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".")' are valid identifiers - // We aren't allowing hyphens or periods, even though they're valid, since the previous version of this function didn't - // Replace all characters that aren't in the list with an underscore - returnValue = InvalidCharacters.Replace(inputValue, "_"); - - // identifiers '... must begin with a letter ([A-Za-z])' - // replace a starting non-letter character with an A - returnValue = InvalidInitialCharacters.Replace(returnValue, "A"); - - // put in Dictionary - validIDLookupDictionary[inputValue] = returnValue; - } - } - } - - return returnValue; - } - - /// Get the URL to show the "access denied" message. - /// URL to access denied view. - public static string AccessDeniedURL() - { - return AccessDeniedURL(string.Empty); - } - - /// Get the URL to show the "access denied" message. - /// The message to display. - /// URL to access denied view. - public static string AccessDeniedURL(string message) - { - string strURL = string.Empty; - - var currentTabId = TabController.CurrentPage.TabID; - var currentUserId = UserController.Instance.GetCurrentUserInfo().UserID; - if (HttpContext.Current.Request.IsAuthenticated) - { - if (string.IsNullOrEmpty(message)) - { - // redirect to access denied page - strURL = navigationManager.NavigateURL(currentTabId, "Access Denied"); - } - else - { - // redirect to access denied page with custom message - var messageGuid = DataProvider.Instance().AddRedirectMessage( - currentUserId, currentTabId, message).ToString("N"); - strURL = navigationManager.NavigateURL(currentTabId, "Access Denied", "message=" + messageGuid); - } - } - else - { - strURL = LoginURL(HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl), false); - } - - return strURL; - } - - /// Adds the current request's protocol ("http://" or "https://") to the given URL, if it does not already have a protocol specified. - /// The URL. - /// The formatted URL. - public static string AddHTTP(string strURL) - { - if (!string.IsNullOrEmpty(strURL)) - { - if (strURL.IndexOf("mailto:") == -1 && strURL.IndexOf("://") == -1 && strURL.IndexOf("~") == -1 && strURL.IndexOf("\\\\") == -1) - { - strURL = ((HttpContext.Current != null && UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request)) ? "https://" : "http://") + strURL; - } - } - - return strURL; - } - - /// Generates the Application root url (including the tab/page). - /// - /// This overload assumes the current page. - /// - /// The formatted root url. - public static string ApplicationURL() - { - var currentPage = TabController.CurrentPage; - if (currentPage != null && currentPage.HasAVisibleVersion) - { - return ApplicationURL(currentPage.TabID); - } - - return ApplicationURL(-1); - } - - /// Generates the Application root url (including the tab/page). - /// - /// This overload takes the tabid (page id) as a parameter. - /// - /// The id of the tab/page. - /// The formatted root url. - public static string ApplicationURL(int tabID) - { - string strURL = "~/" + glbDefaultPage; - if (tabID != -1) - { - strURL += "?tabid=" + tabID; - } - - return strURL; - } - - /// Formats the help URL, adding query-string parameters and a protocol (if missing). - /// The help URL. - /// The portal settings. - /// The name of the module. - /// Formatted URL. - public static string FormatHelpUrl(string helpUrl, PortalSettings objPortalSettings, string name) - { - return FormatHelpUrl(helpUrl, objPortalSettings, name, string.Empty); - } - - /// Formats the help URL, adding query-string parameters and a protocol (if missing). - /// The help URL. - /// The portal settings. - /// The name of the module. - /// The version of the module. - /// Formatted URL. - public static string FormatHelpUrl(string helpUrl, PortalSettings objPortalSettings, string name, string version) - { - string strURL = helpUrl; - if (strURL.IndexOf("?") != -1) - { - strURL += "&helpculture="; - } - else - { - strURL += "?helpculture="; - } - - if (!string.IsNullOrEmpty(Thread.CurrentThread.CurrentUICulture.ToString().ToLowerInvariant())) - { - strURL += Thread.CurrentThread.CurrentUICulture.ToString().ToLowerInvariant(); - } - else - { - strURL += objPortalSettings.DefaultLanguage.ToLowerInvariant(); - } - - if (!string.IsNullOrEmpty(name)) - { - strURL += "&helpmodule=" + HttpUtility.UrlEncode(name); - } - - if (!string.IsNullOrEmpty(version)) - { - strURL += "&helpversion=" + HttpUtility.UrlEncode(version); - } - - return AddHTTP(strURL); - } - - /// Generates the correctly formatted friendly URL. - /// - /// Assumes Default.aspx, and that portalsettings are saved to Context. - /// - /// The current tab. - /// The path to format. - /// The formatted (friendly) URL. - public static string FriendlyUrl(TabInfo tab, string path) - { - return FriendlyUrl(tab, path, glbDefaultPage); - } - - /// Generates the correctly formatted friendly URL. - /// - /// This overload includes an optional page to include in the url. - /// - /// The current tab. - /// The path to format. - /// The page to include in the url. - /// The formatted (friendly) URL. - public static string FriendlyUrl(TabInfo tab, string path, string pageName) - { - var portalSettings = PortalController.Instance.GetCurrentSettings(); - return FriendlyUrl(tab, path, pageName, portalSettings); - } - - /// Generates the correctly formatted friendly URL. - /// - /// This overload includes the portal settings for the site. - /// - /// The current tab. - /// The path to format. - /// The portal settings. - /// The formatted (friendly) URL. - [DnnDeprecated(9, 4, 3, "Use the IPortalSettings overload")] - public static partial string FriendlyUrl(TabInfo tab, string path, PortalSettings settings) - { - return FriendlyUrl(tab, path, (IPortalSettings)settings); - } - - /// Generates the correctly formatted friendly URL. - /// - /// This overload includes the portal settings for the site. - /// - /// The current tab. - /// The path to format. - /// The portal settings. - /// The formatted (friendly) URL. - public static string FriendlyUrl(TabInfo tab, string path, IPortalSettings settings) - { - return FriendlyUrl(tab, path, glbDefaultPage, settings); - } - - /// Generates the correctly formatted friendly URL. - /// - /// This overload includes an optional page to include in the URL, and the portal - /// settings for the site. - /// - /// The current tab. - /// The path to format. - /// The page to include in the URL. - /// The portal settings. - /// The formatted (friendly) url. - [DnnDeprecated(9, 4, 3, "Use the IPortalSettings overload")] - public static partial string FriendlyUrl(TabInfo tab, string path, string pageName, PortalSettings settings) - { - return FriendlyUrl(tab, path, pageName, (IPortalSettings)settings); - } - - /// Generates the correctly formatted friendly URL. - /// - /// This overload includes an optional page to include in the URL, and the portal - /// settings for the site. - /// - /// The current tab. - /// The path to format. - /// The page to include in the URL. - /// The portal settings. - /// The formatted (friendly) url. - public static string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings) - { - return FriendlyUrlProvider.Instance().FriendlyUrl(tab, path, pageName, settings); - } - - /// Generates the correctly formatted friendly url. - /// - /// This overload includes an optional page to include in the url, and the portal - /// alias for the site. - /// - /// The current tab. - /// The path to format. - /// The page to include in the URL. - /// The portal alias for the site. - /// The formatted (friendly) URL. - public static string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) - { - return FriendlyUrlProvider.Instance().FriendlyUrl(tab, path, pageName, portalAlias); - } - - /// Returns the type of URl (T=other tab, F=file, U=URL, N=normal). - /// The url. - /// The url type. - public static TabType GetURLType(string url) - { - if (string.IsNullOrEmpty(url)) - { - return TabType.Normal; - } - - if (url.StartsWith("mailto:", StringComparison.InvariantCultureIgnoreCase) == false && url.IndexOf("://") == -1 && url.StartsWith("~") == false && url.StartsWith("\\\\") == false && url.StartsWith("/") == false) - { - if (NumberMatchRegex.IsMatch(url)) - { - return TabType.Tab; - } - - if (url.StartsWith("userid=", StringComparison.InvariantCultureIgnoreCase)) - { - return TabType.Member; - } - - return TabType.File; - } - - return TabType.Url; - } - - /// - /// Url's as internal links to Files, Tabs and Users should only be imported if - /// those files, tabs and users exist. This function parses the url, and checks - /// whether the internal links exist. - /// If the link does not exist, the function will return an empty string. - /// - /// The id of the module (unused). - /// the url to import. - /// If an internal link does not exist, an empty string is returned, otherwise the passed in url is returned as is. - [DnnDeprecated(9, 8, 1, "moduleId is not used in the method, use the overload that takes only the url")] - public static partial string ImportUrl(int moduleId, string url) - { - return ImportUrl(url); - } - - /// - /// Url's as internal links to Files, Tabs and Users should only be imported if - /// those files, tabs and users exist. This function parses the url, and checks - /// whether the internal links exist. - /// If the link does not exist, the function will return an empty string. - /// - /// The url to import. - /// If an internal link does not exist, an empty string is returned, otherwise the passed in url is returned as is. - public static string ImportUrl(string url) - { - string strUrl = url; - TabType urlType = GetURLType(url); - int intId = -1; - PortalSettings portalSettings = GetPortalSettings(); - switch (urlType) - { - case TabType.File: - if (int.TryParse(url.Replace("FileID=", string.Empty), out intId)) - { - var objFile = FileManager.Instance.GetFile(intId); - if (objFile == null) - { - // fileId does not exist in the portal - strUrl = string.Empty; - } - } - else - { - // failed to get fileId - strUrl = string.Empty; - } - - break; - case TabType.Member: - if (int.TryParse(url.Replace("UserID=", string.Empty), out intId)) - { - if (UserController.GetUserById(portalSettings.PortalId, intId) == null) - { - // UserId does not exist for this portal - strUrl = string.Empty; - } - } - else - { - // failed to get UserId - strUrl = string.Empty; - } - - break; - case TabType.Tab: - if (int.TryParse(url, out intId)) - { - if (TabController.Instance.GetTab(intId, portalSettings.PortalId, false) == null) - { - // the tab does not exist - strUrl = string.Empty; - } - } - else - { - // failed to get TabId - strUrl = string.Empty; - } - - break; - } - - return strUrl; - } - - /// Gets the login URL. - /// The URL to redirect to after logging in. - /// if set to , show the login control on the current page, even if there is a login page defined for the site. - /// Formatted URL. - public static string LoginURL(string returnUrl, bool overrideSetting) - { - return LoginURL(returnUrl, overrideSetting, PortalController.Instance.GetCurrentSettings()); - } - - /// Gets the login URL. - /// The URL to redirect to after logging in. - /// if set to , show the login control on the current page, even if there is a login page defined for the site. - /// The Portal Settings. - /// Formatted URL. - [DnnDeprecated(9, 8, 1, "Use the overload that takes IPortalSettings instead")] - public static partial string LoginURL(string returnUrl, bool overrideSetting, PortalSettings portalSettings) - { - return LoginURL(returnUrl, overrideSetting, (IPortalSettings)portalSettings); - } - - /// Gets the login URL. - /// The URL to redirect to after logging in. - /// if set to , show the login control on the current page, even if there is a login page defined for the site. - /// The Portal Settings. - /// Formatted URL. - public static string LoginURL(string returnUrl, bool overrideSetting, IPortalSettings portalSettings) - { - string loginUrl; - var currentTabId = TabController.CurrentPage.TabID; - - if (!string.IsNullOrEmpty(returnUrl)) - { - returnUrl = string.Format("returnurl={0}", returnUrl); - } - - var popUpParameter = string.Empty; - if (HttpUtility.UrlDecode(returnUrl).IndexOf("popUp=true", StringComparison.OrdinalIgnoreCase) >= 0) - { - popUpParameter = "popUp=true"; - } - - if (portalSettings.LoginTabId != -1 && !overrideSetting) - { - if (ValidateLoginTabID(portalSettings.LoginTabId)) - { - loginUrl = string.IsNullOrEmpty(returnUrl) - ? navigationManager.NavigateURL(portalSettings.LoginTabId, string.Empty, popUpParameter) - : navigationManager.NavigateURL(portalSettings.LoginTabId, string.Empty, returnUrl, popUpParameter); - } - else - { - string strMessage = string.Format("error={0}", Localization.GetString("NoLoginControl", Localization.GlobalResourceFile)); - - // No account module so use portal tab - loginUrl = string.IsNullOrEmpty(returnUrl) - ? navigationManager.NavigateURL(currentTabId, "Login", strMessage, popUpParameter) - : navigationManager.NavigateURL(currentTabId, "Login", returnUrl, strMessage, popUpParameter); - } - } - else - { - // portal tab - loginUrl = string.IsNullOrEmpty(returnUrl) - ? navigationManager.NavigateURL(currentTabId, "Login", popUpParameter) - : navigationManager.NavigateURL(currentTabId, "Login", returnUrl, popUpParameter); - } - - return loginUrl; - } - - /// Gets User profile URL. - /// The user id. - /// Formatted url. - public static string UserProfileURL(int userId) - { - string strURL = string.Empty; - var portalSettings = PortalController.Instance.GetCurrentSettings(); - - strURL = navigationManager.NavigateURL(portalSettings.UserTabId, string.Empty, string.Format("userId={0}", userId)); - - return strURL; - } - - /// Gets the URL to the current page. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL() - { - return navigationManager.NavigateURL(); - } - - /// Gets the URL to the given page. - /// The tab ID. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(int tabID) - { - return navigationManager.NavigateURL(tabID); - } - - /// Gets the URL to the given page. - /// The tab ID. - /// if set to the page is a "super-tab," i.e. a host-level page. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(int tabID, bool isSuperTab) - { - return navigationManager.NavigateURL(tabID, isSuperTab); - } - - /// Gets the URL to show the control associated with the given control key. - /// The control key, or or null. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(string controlKey) - { - return navigationManager.NavigateURL(controlKey); - } - - /// Gets the URL to show the control associated with the given control key. - /// The control key, or or null. - /// Any additional parameters, in "key=value" format. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(string controlKey, params string[] additionalParameters) - { - return navigationManager.NavigateURL(controlKey, additionalParameters); - } - - /// Gets the URL to show the control associated with the given control key on the given page. - /// The tab ID. - /// The control key, or or null. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(int tabID, string controlKey) - { - return navigationManager.NavigateURL(tabID, controlKey); - } - - /// Gets the URL to show the given page. - /// The tab ID. - /// The control key, or or null. - /// Any additional parameters. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(int tabID, string controlKey, params string[] additionalParameters) - { - return navigationManager.NavigateURL(tabID, controlKey, additionalParameters); - } - - /// Gets the URL to show the given page. - /// The tab ID. - /// The portal settings. - /// The control key, or or null. - /// Any additional parameters. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(int tabID, PortalSettings settings, string controlKey, params string[] additionalParameters) - { - return navigationManager.NavigateURL(tabID, settings, controlKey, additionalParameters); - } - - /// Gets the URL to show the given page. - /// The tab ID. - /// if set to the page is a "super-tab," i.e. a host-level page. - /// The portal settings. - /// The control key, or or null. - /// Any additional parameters. - /// Formatted URL. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, params string[] additionalParameters) - { - return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, additionalParameters); - } - - /// Gets the URL to show the given page. - /// The tab ID. - /// if set to the page is a "super-tab," i.e. a host-level page. - /// The portal settings. - /// The control key, or or null. - /// The language code. - /// Any additional parameters. - /// Formatted URL. - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, params string[] additionalParameters) - { - return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, additionalParameters); - } - - /// Gets the URL to show the given page. - /// The tab ID. - /// if set to the page is a "super-tab," i.e. a host-level page. - /// The portal settings. - /// The control key, or or null. - /// The language code. - /// The page name to pass to . - /// Any additional parameters. - /// Formatted url. - [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] - public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, string pageName, params string[] additionalParameters) - { - return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, pageName, additionalParameters); - } - - /// UrlEncode query string. - /// The query string. - /// Encoded content. - public static string QueryStringEncode(string queryString) - { - queryString = HttpUtility.UrlEncode(queryString); - return queryString; - } - - /// UrlDecode query string. - /// The query string. - /// Decoded content. - public static string QueryStringDecode(string queryString) - { - queryString = HttpUtility.UrlDecode(queryString); - string fullPath; - try - { - fullPath = HttpContext.Current.Request.MapPath(queryString, HttpContext.Current.Request.ApplicationPath, false); - } - catch (HttpException exc) - { - Exceptions.ProcessHttpException(exc); - } - - string strDoubleDecodeURL = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Server.UrlDecode(queryString)); - if (queryString.IndexOf("..") != -1 || strDoubleDecodeURL.IndexOf("..") != -1) - { - Exceptions.ProcessHttpException(); - } - - return queryString; - } - - /// Gets Register URL. - /// The return URL. - /// The original URL. - /// Formatted url. - public static string RegisterURL(string returnURL, string originalURL) - { - string strURL; - - var portalSettings = PortalController.Instance.GetCurrentSettings(); - string extraParams = string.Empty; - if (!string.IsNullOrEmpty(returnURL)) - { - extraParams = string.Concat("returnurl=", returnURL); - } - - if (!string.IsNullOrEmpty(originalURL)) - { - extraParams += string.Concat("&orignalurl=", originalURL); - } - - if (portalSettings.RegisterTabId != -1) - { - // user defined tab - strURL = navigationManager.NavigateURL(portalSettings.RegisterTabId, string.Empty, extraParams); - } - else - { - strURL = navigationManager.NavigateURL(TabController.CurrentPage.TabID, "Register", extraParams); - } - - return strURL; - } - - /// Generates the correctly formatted url. - /// The url to format. - /// The formatted (resolved) url. - public static string ResolveUrl(string url) - { - // String is Empty, just return Url - if (string.IsNullOrEmpty(url)) - { - return url; - } - - // String does not contain a ~, so just return Url - if (url.StartsWith("~") == false) - { - return url; - } - - // There is just the ~ in the Url, return the appPath - if (url.Length == 1) - { - return ApplicationPath; - } - - if (url.ToCharArray()[1] == '/' || url.ToCharArray()[1] == '\\') - { - // Url looks like ~/ or ~\ - if (!string.IsNullOrEmpty(ApplicationPath) && ApplicationPath.Length > 1) - { - return ApplicationPath + "/" + url.Substring(2); - } - else - { - return "/" + url.Substring(2); - } - } - else - { - // Url look like ~something - if (!string.IsNullOrEmpty(ApplicationPath) && ApplicationPath.Length > 1) - { - return ApplicationPath + "/" + url.Substring(1); - } - else - { - return ApplicationPath + url.Substring(1); - } - } - } - - /// Encodes the reserved characters. - /// The query string. - /// Encoded content. - [DnnDeprecated(9, 8, 1, "Use System.Net.WebUtility.UrlEncode instead")] - public static partial string EncodeReservedCharacters(string queryString) - { - queryString = queryString.Replace("$", "%24"); - queryString = queryString.Replace("&", "%26"); - queryString = queryString.Replace("+", "%2B"); - queryString = queryString.Replace(",", "%2C"); - queryString = queryString.Replace("/", "%2F"); - queryString = queryString.Replace(":", "%3A"); - queryString = queryString.Replace(";", "%3B"); - queryString = queryString.Replace("=", "%3D"); - queryString = queryString.Replace("?", "%3F"); - queryString = queryString.Replace("@", "%40"); - return queryString; - } - - /// Dates to string. - /// The date value. - /// return value of input with SortableDateTimePattern. - [DnnDeprecated(9, 8, 1, @"Use DateTime.ToString(""s"") instead")] - public static partial string DateToString(DateTime dateValue) - { - try - { - if (!Null.IsNull(dateValue)) - { - return dateValue.ToString("s"); - } - else - { - return Null.NullString; - } - } - catch (Exception exc) - { - Logger.Error(exc); - - return Null.NullString; - } - } - - /// Gets the hash value. - /// The hash object. - /// The default value. - /// HashOject's value or DefaultValue if HashObject is null. - [DnnDeprecated(9, 8, 1, "No replacement")] - public static partial string GetHashValue(object hashObject, string defaultValue) - { - if (hashObject != null) - { - if (!string.IsNullOrEmpty(hashObject.ToString())) - { - return Convert.ToString(hashObject); - } - else - { - return defaultValue; - } - } - else - { - return defaultValue; - } - } - - /// Gets Link click url. - /// The link. - /// The tab ID. - /// The module ID. - /// Formatted url. - public static string LinkClick(string link, int tabId, int moduleId) - { - return LinkClick(link, tabId, moduleId, true, string.Empty); - } - - /// Gets Link click url. - /// The link. - /// The tab ID. - /// The module ID. - /// if set to [track clicks]. - /// Formatted url. - public static string LinkClick(string link, int tabId, int moduleId, bool trackClicks) - { - return LinkClick(link, tabId, moduleId, trackClicks, string.Empty); - } - - /// Gets Link click url. - /// The link. - /// The tab ID. - /// The module ID. - /// if set to [track clicks]. - /// Type of the content. - /// Formatted url. - public static string LinkClick(string link, int tabId, int moduleId, bool trackClicks, string contentType) - { - return LinkClick(link, tabId, moduleId, trackClicks, !string.IsNullOrEmpty(contentType)); - } - - /// Gets Link click url. - /// The link. - /// The tab ID. - /// The module ID. - /// if set to [track clicks]. - /// if set to [force download]. - /// Formatted url. - public static string LinkClick(string link, int tabId, int moduleId, bool trackClicks, bool forceDownload) - { - var portalSettings = PortalController.Instance.GetCurrentSettings(); - return LinkClick(link, tabId, moduleId, trackClicks, forceDownload, portalSettings.PortalId, portalSettings.EnableUrlLanguage, portalSettings.GUID.ToString()); - } - - /// Gets Link click url. - /// The link. - /// The tab ID. - /// The module ID. - /// if set to [track clicks]. - /// if set to [force download]. - /// The portal id. - /// if set to [enable URL language]. - /// The portal GUID. - /// Formatted url. - public static string LinkClick( - string link, - int tabId, - int moduleId, - bool trackClicks, - bool forceDownload, - int portalId, - bool enableUrlLanguage, - string portalGuid) - { - string strLink = string.Empty; - TabType urlType = GetURLType(link); - if (urlType == TabType.Member) - { - strLink = UserProfileURL(Convert.ToInt32(UrlUtils.GetParameterValue(link))); - } - else if (trackClicks || forceDownload || urlType == TabType.File) - { - // format LinkClick wrapper - if (link.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) - { - strLink = ApplicationPath + "/LinkClick.aspx?fileticket=" + UrlUtils.EncryptParameter(UrlUtils.GetParameterValue(link), portalGuid); - if (portalId == Null.NullInteger) - { - // To track Host files - strLink += "&hf=1"; - } - } - - if (string.IsNullOrEmpty(strLink)) - { - strLink = ApplicationPath + "/LinkClick.aspx?link=" + HttpUtility.UrlEncode(link); - } - - // tabid is required to identify the portal where the click originated - if (tabId != Null.NullInteger) - { - strLink += "&tabid=" + tabId; - } - - // append portal id to query string to identity portal the click originated. - if (portalId != Null.NullInteger) - { - strLink += "&portalid=" + portalId; - } - - // moduleid is used to identify the module where the url is stored - if (moduleId != -1) - { - strLink += "&mid=" + moduleId; - } - - // only add language to url if more than one locale is enabled, and if admin did not turn it off - if (LocaleController.Instance.GetLocales(portalId).Count > 1 && enableUrlLanguage) - { - strLink += "&language=" + Thread.CurrentThread.CurrentCulture.Name; - } - - // force a download dialog - if (forceDownload) - { - strLink += "&forcedownload=true"; - } - } - else - { - switch (urlType) - { - case TabType.Tab: - strLink = navigationManager.NavigateURL(int.Parse(link)); - break; - default: - strLink = link; - break; - } - } - - return strLink; - } - - /// Gets the name of the role. - /// The role ID. - /// Role Name. - [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] - public static partial string GetRoleName(int roleId) - => GetRoleName(GetCurrentServiceProvider().GetRequiredService(), roleId); - - /// Gets the name of the role. - /// The host settings. - /// The role ID. - /// Role Name. - public static string GetRoleName(IHostSettings hostSettings, int roleId) - { - switch (Convert.ToString(roleId)) - { - case glbRoleAllUsers: - return glbRoleAllUsersName; - case glbRoleUnauthUser: - return glbRoleUnauthUserName; - } - - Hashtable htRoles = null; - if (hostSettings.PerformanceSetting != DotNetNuke.Abstractions.Application.PerformanceSettings.NoCaching) - { - htRoles = (Hashtable)DataCache.GetCache("GetRoles"); - } - - if (htRoles == null) - { - var roles = RoleController.Instance.GetRoles(Null.NullInteger, r => r.SecurityMode != SecurityMode.SocialGroup); - htRoles = new Hashtable(); - int i; - for (i = 0; i <= roles.Count - 1; i++) - { - RoleInfo role = roles[i]; - htRoles.Add(role.RoleID, role.RoleName); - } - - if (hostSettings.PerformanceSetting != DotNetNuke.Abstractions.Application.PerformanceSettings.NoCaching) - { - DataCache.SetCache("GetRoles", htRoles); - } - } - - return Convert.ToString(htRoles[roleId]); - } - - /// Gets the content. - /// The content. - /// Type of the content. - /// specific node by content type of the whole document. - public static XmlNode GetContent(string content, string contentType) - { - var xmlDoc = new XmlDocument { XmlResolver = null }; - xmlDoc.LoadXml(content); - if (string.IsNullOrEmpty(contentType)) - { - return xmlDoc.DocumentElement; - } - else - { - return xmlDoc.SelectSingleNode(contentType); - } - } - - /// GenerateTabPath generates the TabPath used in Friendly URLS. - /// The Id of the Parent Tab. - /// The Name of the current Tab. - /// The TabPath. - public static string GenerateTabPath(int parentId, string tabName) - { - var strTabPath = Null.NullString; - - if (!Null.IsNull(parentId)) - { - var objTab = TabController.Instance.GetTab(parentId, Null.NullInteger, false); - while (objTab != null) - { - var strTabName = TabPathInvalidCharsRx.Replace(objTab.TabName, string.Empty); - strTabPath = "//" + strTabName + strTabPath; - objTab = Null.IsNull(objTab.ParentId) - ? null - : TabController.Instance.GetTab(objTab.ParentId, objTab.PortalID, false); - } - } - - strTabPath = strTabPath + "//" + TabPathInvalidCharsRx.Replace(tabName, string.Empty); - return strTabPath; - } - - /// Gets the help text. - /// The module control id. - /// help text. - public static string GetHelpText(int moduleControlId) - { - string helpText = Null.NullString; - ModuleControlInfo objModuleControl = ModuleControlController.GetModuleControl(moduleControlId); - if (objModuleControl != null) - { - string fileName = Path.GetFileName(objModuleControl.ControlSrc); - string localResourceFile = objModuleControl.ControlSrc.Replace(fileName, Localization.LocalResourceDirectory + "/" + fileName); - if (!string.IsNullOrEmpty(Localization.GetString(ModuleActionType.HelpText, localResourceFile))) - { - helpText = Localization.GetString(ModuleActionType.HelpText, localResourceFile); - } - } - - return helpText; - } - - /// Gets the online help url or the host configured help url if no url provided. - /// The help URL. - /// The module config. - /// The help url. - [DnnDeprecated(9, 8, 1, "ModuleInfo is unused, use the overload that does not take a ModuleInfo")] - public static partial string GetOnLineHelp(string helpUrl, ModuleInfo moduleConfig) - { - return GetOnLineHelp(helpUrl); - } - - /// Gets the online help url or the host configured help url if no url provided. - /// The help URL. - /// The help url. - [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] - public static partial string GetOnLineHelp(string helpUrl) - => GetOnLineHelp(GetCurrentServiceProvider().GetRequiredService(), helpUrl); - - /// Gets the online help url or the host configured help url if no url provided. - /// The host settings. - /// The help URL. - /// The help url. - public static string GetOnLineHelp(IHostSettings hostSettings, string helpUrl) - { - if (string.IsNullOrEmpty(helpUrl)) - { - helpUrl = hostSettings.HelpUrl; - } - - return helpUrl; - } - - /// Check whether the tab contains "Account Login" module. - /// The tab id. - /// if the tab contains "Account Login" module, otherwise, . - public static bool ValidateLoginTabID(int tabId) - { - return ValidateModuleInTab(tabId, "Account Login"); - } - - /// Check whether the tab contains specific module. - /// The tab id. - /// The module need to check. - /// if the tab contains the module, otherwise, . - public static bool ValidateModuleInTab(int tabId, string moduleName) - { - bool hasModule = Null.NullBoolean; - foreach (ModuleInfo objModule in ModuleController.Instance.GetTabModules(tabId).Values) - { - if (objModule.ModuleDefinition.FriendlyName == moduleName) - { - // We need to ensure that Anonymous Users or All Users have View permissions to the login page - TabInfo tab = TabController.Instance.GetTab(tabId, objModule.PortalID, false); - if (TabPermissionController.CanViewPage(tab)) - { - hasModule = true; - break; - } - } - } - - return hasModule; - } - - /// DeserializeHashTableBase64 deserializes a Hashtable using Binary Formatting. - /// - /// While this method of serializing is no longer supported (due to Medium Trust - /// issue, it is still required for upgrade purposes. - /// - /// The String Source to deserialize. - /// The deserialized Hashtable. - [DnnDeprecated(9, 8, 1, "No replacement")] - public static partial Hashtable DeserializeHashTableBase64(string source) - { - Hashtable objHashTable; - if (!string.IsNullOrEmpty(source)) - { - byte[] bits = Convert.FromBase64String(source); - using (var mem = new MemoryStream(bits)) - { - var bin = new BinaryFormatter(); - try - { - objHashTable = (Hashtable)bin.Deserialize(mem); - } - catch (Exception exc) - { - Logger.Error(exc); - - objHashTable = new Hashtable(); - } - - mem.Close(); - } - } - else - { - objHashTable = new Hashtable(); - } - - return objHashTable; - } - - /// DeserializeHashTableXml deserializes a Hashtable using Xml Serialization. - /// - /// This is the preferred method of serialization under Medium Trust. - /// - /// The String Source to deserialize. - /// The deserialized Hashtable. - [DnnDeprecated(9, 8, 1, "This API was not meant to be public and only deserializes xml with a root of 'profile'")] - public static partial Hashtable DeserializeHashTableXml(string source) - { - return XmlUtils.DeSerializeHashtable(source, "profile"); - } - - /// SerializeHashTableBase64 serializes a Hashtable using Binary Formatting. - /// - /// While this method of serializing is no longer supported (due to Medium Trust - /// issue, it is still required for upgrade purposes. - /// - /// The Hashtable to serialize. - /// The serialized String. - [DnnDeprecated(9, 8, 1, "No replacement")] - public static partial string SerializeHashTableBase64(Hashtable source) - { - string strString; - if (source.Count != 0) - { - var bin = new BinaryFormatter(); - var mem = new MemoryStream(); - try - { - bin.Serialize(mem, source); - strString = Convert.ToBase64String(mem.GetBuffer(), 0, Convert.ToInt32(mem.Length)); - } - catch (Exception exc) - { - Logger.Error(exc); - - strString = string.Empty; - } - finally - { - mem.Close(); - } - } - else - { - strString = string.Empty; - } - - return strString; - } - - /// SerializeHashTableXml serializes a Hashtable using Xml Serialization. - /// - /// This is the preferred method of serialization under Medium Trust. - /// - /// The Hashtable to serialize. - /// The serialized String. - [DnnDeprecated(9, 8, 1, "This method was never meant to be public and only works for 'profile' root namespace")] - public static partial string SerializeHashTableXml(Hashtable source) - { - return XmlUtils.SerializeDictionary(source, "profile"); - } - - /// Check whether the specific page is a host page. - /// The tab ID. - /// if the tab is a host page; otherwise, it is not a host page. - public static bool IsHostTab(int tabId) - { - bool isHostTab = false; - TabCollection hostTabs = TabController.Instance.GetTabsByPortal(Null.NullInteger); - - if (hostTabs != null) - { - isHostTab = hostTabs.Any(t => t.Value.TabID == tabId); - } - - return isHostTab; - } - - /// Return User Profile Picture Formatted Url. UserId, width and height can be passed to build a formatted Avatar Url. - /// Formatted url, e.g. http://www.mysite.com/DnnImageHandler.ashx?mode=profilepic&userid={0}&h={1}&w={2}. - /// - /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicFormattedUrl(), userInfo.UserID, 32, 32). - /// - [DnnDeprecated(7, 3, 0, "It causes issues in SSL-offloading scenarios - please use UserProfilePicRelativeUrl instead", RemovalVersion = 11)] - public static partial string UserProfilePicFormattedUrl() - { - var avatarUrl = PortalController.Instance.GetCurrentPortalSettings().DefaultPortalAlias; - if (string.IsNullOrEmpty(avatarUrl)) - { - avatarUrl = HttpContext.Current.Request.Url.Host; - } - - avatarUrl = string.Format( - "{0}://{1}{2}", - UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request) ? "https" : "http", - avatarUrl, - !HttpContext.Current.Request.Url.IsDefaultPort && !avatarUrl.Contains(":") ? ":" + HttpContext.Current.Request.Url.Port : string.Empty); - - avatarUrl += "/DnnImageHandler.ashx?mode=profilepic&userId={0}&h={1}&w={2}"; - - return avatarUrl; - } - - /// Return User Profile Picture relative Url. UserId, width and height can be passed to build a formatted relative Avatar Url. - /// Formatted url, e.g. /DnnImageHandler.ashx?userid={0}&h={1}&w={2} considering child portal. - /// - /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32). - /// - [DnnDeprecated(8, 0, 0, "Please use UserController.Instance.GetUserProfilePictureUrl", RemovalVersion = 11)] - public static partial string UserProfilePicRelativeUrl() - { - return UserProfilePicRelativeUrl(true); - } - - /// Return User Profile Picture relative Url. UserId, width and height can be passed to build a formatted relative Avatar Url. - /// Indicates if cdv (Cache Delayed Verification) has to be included in the returned URL. - /// Formatted url, e.g. /DnnImageHandler.ashx?userid={0}&h={1}&w={2} considering child portal. - /// - /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32). - /// - [DnnDeprecated(8, 0, 0, "Please use UserController.Instance.GetUserProfilePictureUrl", RemovalVersion = 11)] - public static partial string UserProfilePicRelativeUrl(bool includeCdv) - { - const string query = "/DnnImageHandler.ashx?mode=profilepic&userId={0}&h={1}&w={2}"; - var currentAlias = GetPortalSettings().PortalAlias.HTTPAlias; - var index = currentAlias.IndexOf('/'); - var childPortalAlias = index > 0 ? "/" + currentAlias.Substring(index + 1) : string.Empty; - - var cdv = string.Empty; - if (includeCdv) - { - cdv = "&cdv=" + DateTime.Now.Ticks; - } - - if (childPortalAlias.StartsWith(ApplicationPath)) - { - return childPortalAlias + query + cdv; - } - - return ApplicationPath + childPortalAlias + query + cdv; - } - - /// Formats an email address as a cloacked html link. - /// The formatted email address. - /// A cloacked html link. - [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatEmail", RemovalVersion = 11)] - public static partial string FormatEmail(string email) - { - return HtmlUtils.FormatEmail(email); - } - - /// Formats a domain name including link. - /// The domain name to format. - /// The formatted domain name. - [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatWebsite", RemovalVersion = 11)] - public static partial string FormatWebsite(object website) - { - return HtmlUtils.FormatWebsite(website); - } - - /// Xml encodes an html string. - /// The html to encode. - /// The encoded html for usage in xml. - [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.XmlUtils.XMLEncode", RemovalVersion = 11)] - public static partial string XMLEncode(string html) - { - return XmlUtils.XMLEncode(html); - } - - /// Gets the database connection string. - /// The database connection string. - [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.Config.GetConnectionString", RemovalVersion = 11)] - public static partial string GetDBConnectionString() - { - return Config.GetConnectionString(); - } - - /// Gets a file list. - /// The current directory. - /// The extensions to filter for. - /// If true, adds 'None Specified' to the list. - /// A list of file names. - [DnnDeprecated(7, 0, 0, "No replacement", RemovalVersion = 11)] - public static partial ArrayList GetFileList( - DirectoryInfo currentDirectory, - [Optional, DefaultParameterValue("")] // ERROR: Optional parameters aren't supported in C# - string strExtensions, - [Optional, DefaultParameterValue(true)] // ERROR: Optional parameters aren't supported in C# - bool noneSpecified) - { - var arrFileList = new ArrayList(); - string strExtension = string.Empty; - - if (noneSpecified) - { - arrFileList.Add(new FileItem(string.Empty, "<" + Localization.GetString("None_Specified") + ">")); - } - - string file = null; - string[] files = Directory.GetFiles(currentDirectory.FullName); - foreach (string fileLoopVariable in files) - { - file = fileLoopVariable; - if (file.IndexOf(".") > -1) - { - strExtension = file.Substring(file.LastIndexOf(".") + 1); - } - - string fileName = file.Substring(currentDirectory.FullName.Length); - if (strExtensions.IndexOf(strExtension, StringComparison.InvariantCultureIgnoreCase) != -1 || string.IsNullOrEmpty(strExtensions)) - { - arrFileList.Add(new FileItem(fileName, fileName)); - } - } - - return arrFileList; - } - - /// Gets the subfolder path for a give filename path. - /// The filename full path. - /// The subfolder name. - [DnnDeprecated(7, 0, 0, "Replaced by GetSubFolderPath(string strFileNamePath, int portalId)", RemovalVersion = 11)] - public static partial string GetSubFolderPath(string strFileNamePath) - { - // Obtain PortalSettings from Current Context - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - string parentFolderName = null; - if (IsHostTab(portalSettings.ActiveTab.TabID)) - { - parentFolderName = HostMapPath.Replace("/", "\\"); - } - else - { - parentFolderName = portalSettings.HomeDirectoryMapPath.Replace("/", "\\"); - } - - string strFolderpath = strFileNamePath.Substring(0, strFileNamePath.LastIndexOf("\\") + 1); - - return strFolderpath.Substring(parentFolderName.Length).Replace("\\", "/"); - } - - /// Gets a LinkClick url for tracking purposes. - /// The actual link the LinkClick handler should point to. - /// The formatted LinkClick url. - [DnnDeprecated(7, 0, 0, "Use Common.Globals.LinkClick() for proper handling of URLs", RemovalVersion = 11)] - public static partial string LinkClickURL(string link) - { - PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return LinkClick(link, portalSettings.ActiveTab.TabID, -1, false); - } - - /// Helps prevent sql injection in certain scenarios. - /// IMPORTANT: It is highly recommended to use other forms of sql injection protection such as using SqlParameters or ORMs. - /// The string to filter. - /// The filtered string. - [DnnDeprecated(7, 0, 0, "Use Security Filter functions in the PortalSecurity class", RemovalVersion = 11)] - public static partial string PreventSQLInjection(string strSQL) - { - return PortalSecurity.Instance.InputFilter(strSQL, PortalSecurity.FilterFlag.NoSQL); - } - - /// Looks at various file artifacts to determine if DotNetNuke has already been installed. - /// true if installed else false. - /// - /// If DotNetNuke has been installed, then we should treat database connection errors as real errors. - /// If DotNetNuke has not been installed, then we should expect to have database connection problems - /// since the connection string may not have been configured yet, which can occur during the installation - /// wizard. - /// - [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] - internal static partial bool IsInstalled() => applicationStatusInfo.IsInstalled(); - - /// Gets the culture code of the tab. - /// The tab ID. - /// if set to [is super tab]. - /// The settings. - /// return the tab's culture code, if ths tab doesn't exist, it will return current culture name. - internal static string GetCultureCode(int tabId, bool isSuperTab, IPortalSettings settings) - { - string cultureCode = Null.NullString; - if (settings != null) - { - TabInfo linkTab = TabController.Instance.GetTab(tabId, isSuperTab ? Null.NullInteger : settings.PortalId, false); - if (linkTab != null) - { - cultureCode = linkTab.CultureCode; - } - - if (string.IsNullOrEmpty(cultureCode)) - { - cultureCode = Thread.CurrentThread.CurrentCulture.Name; - } - } - - return cultureCode; - } - - /// Resets the application started timer. - internal static void ResetAppStartElapseTime() - { - AppStopwatch.Restart(); - } - - /// Gets an that should be disposed, trying to find the current request scope if possible. - /// An instance that should be disposed (but which can be disposed without prematurely disposing the current request scope). - internal static IServiceScope GetOrCreateServiceScope() - { - return new MaybeDisposableServiceScope( - HttpContextSource.Current?.GetScope(), - DependencyProvider.CreateScope); - } - - /// Gets an for the current request, or the global provider if not available. - /// An instance. - internal static IServiceProvider GetCurrentServiceProvider() - { - return HttpContextSource.Current?.GetScope()?.ServiceProvider ?? DependencyProvider; - } - - /// Check whether the Filename matches extensions. - /// The filename. - /// The valid extensions. - /// if the Filename matches extensions, otherwise, . - private static bool FilenameMatchesExtensions(string filename, string strExtensions) - { - bool result = string.IsNullOrEmpty(strExtensions); - if (!result) - { - foreach (string extension in strExtensions.Split(',')) - { - string ext = extension.Trim(); - if (!ext.StartsWith(".", StringComparison.Ordinal)) - { - ext = "." + extension; - } - - result = filename.EndsWith(ext, StringComparison.OrdinalIgnoreCase); - if (result) - { - break; - } - } - } - - return result; - } - - /// - /// Resolves dependencies after the - /// has been initialized. This should only be called once to resolve all - /// dependencies used by the object. - /// - private static void OnDependencyProviderChanged(object sender, PropertyChangedEventArgs eventArguments) - { - applicationStatusInfo = DependencyProvider?.GetRequiredService(); - navigationManager = DependencyProvider?.GetRequiredService(); - } - - private class MaybeDisposableServiceScope : IServiceScope - { - private readonly bool disposeServiceScope; - private readonly IServiceScope serviceScope; - - public MaybeDisposableServiceScope(IServiceScope doNotDisposeServiceScope, Func createDisposableServiceScope) - { - this.disposeServiceScope = doNotDisposeServiceScope is null; - this.serviceScope = doNotDisposeServiceScope ?? createDisposableServiceScope(); - } - - public IServiceProvider ServiceProvider => this.serviceScope.ServiceProvider; - - public void Dispose() - { - if (this.disposeServiceScope) - { - this.serviceScope.Dispose(); - } - } - } - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Common +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Net; + using System.Runtime.InteropServices; + using System.Runtime.Serialization.Formatters.Binary; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using System.Web; + using System.Web.Caching; + using System.Web.UI; + using System.Web.UI.HtmlControls; + using System.Xml; + + using DotNetNuke.Abstractions; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Collections.Internal; + using DotNetNuke.Common.Extensions; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Security; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Personalization; + using DotNetNuke.Services.Url.FriendlyUrl; + using DotNetNuke.UI.Utilities; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.VisualBasic.CompilerServices; + + using DataCache = DotNetNuke.UI.Utilities.DataCache; + + /// The global instance of DotNetNuke. all basic functions and properties are defined in this instance. + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "StyleCop.CSharp.NamingRules", + "SA1303:Const field names should begin with upper-case letter", + Justification = "Changing all these public constants to match the rule would be a massive breaking change just for a code style issue.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "StyleCop.CSharp.NamingRules", + "SA1310:Field names should not contain underscore", + Justification = "Changing all these public fields names would be a massive breaking change only for a code style issue.")] + [StandardModule] + public sealed partial class Globals + { + /// Global role id for all users. + /// -1. + public const string glbRoleAllUsers = "-1"; + + /// Global role id for super user. + /// -2. + public const string glbRoleSuperUser = "-2"; + + /// Global role id for unauthenticated users. + /// -3. + public const string glbRoleUnauthUser = "-3"; + + /// Global role id by default. + /// -4. + public const string glbRoleNothing = "-4"; + + /// Global role name for all users. + /// All Users. + public const string glbRoleAllUsersName = "All Users"; + + /// Global ro name for super user. + /// Superuser. + public const string glbRoleSuperUserName = "Superuser"; + + /// Global role name for unauthenticated users. + /// Unauthenticated Users. + public const string glbRoleUnauthUserName = "Unauthenticated Users"; + + /// Default page name. + /// Default.aspx. + public const string glbDefaultPage = "Default.aspx"; + + /// Default host skin folder. + /// _default. + public const string glbHostSkinFolder = "_default"; + + /// Default control panel. + /// Admin/ControlPanel/IconBar.ascx. + public const string glbDefaultControlPanel = "Admin/ControlPanel/IconBar.ascx"; + + /// Default setting to determine if selected control panel is loaded to evaluate visibility. + /// false. + public const bool glbAllowControlPanelToDetermineVisibility = false; + + /// Default pane name. + /// ContentPane. + public const string glbDefaultPane = "ContentPane"; + + /// Config files folder. + /// \Config\. + public const string glbConfigFolder = "\\Config\\"; + + /// About page name. + /// about.htm. + public const string glbAboutPage = "about.htm"; + + /// DotNetNuke config file. + /// DotNetNuke.config. + public const string glbDotNetNukeConfig = "DotNetNuke.config"; + + /// Default portal id for super user. + /// -1. + public const int glbSuperUserAppName = -1; + + /// extension of protected files. + /// .resources. + public const string glbProtectedExtension = ".resources"; + + /// Default container folder. + /// Portals/_default/Containers/. + public const string glbContainersPath = "Portals/_default/Containers/"; + + /// Default skin folder. + /// Portals/_default/Skins/. + public const string glbSkinsPath = "Portals/_default/Skins/"; + + /// + /// Email address regex pattern that covers most scenarios. + /// + /// A regex that covers most emails in a performant way. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public const string glbEmailRegEx = + @"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"; + + /// User Name regex pattern. + /// + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public const string glbUserNameRegEx = @""; + + /// User Name default minimum length. + /// + public const int glbUserNameMinLength = 5; + + /// Format of a script tag. + /// ]]> + public const string glbScriptFormat = ""; + + /// Validates for a valid email address. + public static readonly Regex EmailValidatorRegex = new Regex(glbEmailRegEx, RegexOptions.Compiled); + + /// Finds non-alphanumeric characters. + public static readonly Regex NonAlphanumericCharacters = new Regex("[^A-Za-z0-9]", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// Finds any character that is not a letter, a number, an underscore or a dash. + public static readonly Regex InvalidCharacters = new Regex("[^A-Za-z0-9_-]", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// Validates if the first character is a letter. + public static readonly Regex InvalidInitialCharacters = new Regex("^[^A-Za-z]", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// Validates if the string contains only numbers. + public static readonly Regex NumberMatchRegex = new Regex(@"^\d+$", RegexOptions.Compiled); + + /// Validates if a tag is an html 'base' tag. + public static readonly Regex BaseTagRegex = new Regex("]*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + + /// Finds common file escaping characters. + public static readonly Regex FileEscapingRegex = new Regex(@"[\\/]\.\.[\\/]", RegexOptions.Compiled); + + /// Checks if a string is a valid Windows file extension. + public static readonly Regex FileExtensionRegex = new Regex(@"\..+;", RegexOptions.Compiled); + + /// Checks if a string is a valid Windows filename. + public static readonly Regex FileValidNameRegex = new Regex(@"^(?!(?:PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d)(?:\..+)?$)[^\x00-\x1F\xA5\\?*:\"";|\/<>]+(?Checks if a url part is a valid services framework url. + public static readonly Regex ServicesFrameworkRegex = new Regex("/API/|DESKTOPMODULES/.+/API/", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// Checks for invalid usernames. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + public static readonly string USERNAME_UNALLOWED_ASCII = @"!""#$%&'()*+,/:;<=>?[\]^`{|}"; + + private const string tabPathInvalidCharsEx = @"[&\? \./'#:\*]"; // this value should keep same with the value used in sp BuildTabLevelAndPath to remove invalid chars. + + private static readonly Regex TabPathInvalidCharsRx = new Regex(tabPathInvalidCharsEx, RegexOptions.Compiled); + + private static readonly Stopwatch AppStopwatch = Stopwatch.StartNew(); + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Globals)); + private static readonly HashSet AdminControlKeys = new HashSet(StringComparer.OrdinalIgnoreCase) { "tab", "module", "importmodule", "exportmodule", "help", }; + private static string applicationPath; + private static string desktopModulePath; + private static string imagePath; + private static string hostMapPath; + private static string hostPath; + private static string installMapPath; + private static string installPath; + + private static IServiceProvider dependencyProvider; + private static IApplicationStatusInfo applicationStatusInfo; + private static INavigationManager navigationManager; + + // global constants for the life of the application ( set in Application_Start ) + + /// + public enum PerformanceSettings + { + /// + NoCaching = 0, + + /// + LightCaching = 1, + + /// + ModerateCaching = 3, + + /// + HeavyCaching = 6, + } + + /// Enumeration Of Registration Type for portal. + /// + /// NoRegistration: Disabled registration in portal. + /// PrivateRegistration: Once user's account information has been submitted, + /// the portal Administrator will be notified and user's application will be subjected to a screening procedure. + /// If user's application is authorized, the user will receive notification of access to the portal environment. + /// PublicRegistration: Once user's account information has been submitted, + /// user will be immediately granted access to the portal environment. + /// VerifiedRegistration: Once user's account information has been submitted, + /// user will receive an email containing unique Verification Code. + /// The Verification Code will be required the first time when user attempt to sign in to the portal environment. + /// + public enum PortalRegistrationType + { + /// Disabled Registration. + NoRegistration = 0, + + /// Account need be approved by portal's administrator. + PrivateRegistration = 1, + + /// Account will be available after post registration data successful. + PublicRegistration = 2, + + /// Account will be available by verify code. + VerifiedRegistration = 3, + } + + /// Enumeration Of Application upgrade status. + public enum UpgradeStatus + { + /// The application need update to a higher version. + Upgrade = 0, + + /// The application need to install itself. + Install = 1, + + /// The application is normal running. + None = 2, + + /// The application occur error when running. + Error = 3, + + /// The application status is unknown. + /// This status should never be returned. its is only used as a flag that Status hasn't been determined. + Unknown = 4, + } + + /// Gets the application path. + public static string ApplicationPath + { + get + { + if (applicationPath == null && (HttpContext.Current != null)) + { + if (HttpContext.Current.Request.ApplicationPath == "/") + { + applicationPath = string.IsNullOrEmpty(Config.GetSetting("InstallationSubfolder")) ? string.Empty : (Config.GetSetting("InstallationSubfolder") + "/").ToLowerInvariant(); + } + else + { + applicationPath = HttpContext.Current.Request.ApplicationPath.ToLowerInvariant(); + } + } + + return applicationPath; + } + } + + /// Gets the application map path. + /// + /// The application map path. + /// + [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] + public static string ApplicationMapPath => applicationStatusInfo.ApplicationMapPath; + + /// Gets the desktop module path. + /// ApplicationPath + "/DesktopModules/". + public static string DesktopModulePath + { + get + { + if (desktopModulePath == null) + { + desktopModulePath = ApplicationPath + "/DesktopModules/"; + } + + return desktopModulePath; + } + } + + /// Gets the image path. + /// ApplicationPath + "/Images/". + public static string ImagePath + { + get + { + if (imagePath == null) + { + imagePath = ApplicationPath + "/Images/"; + } + + return imagePath; + } + } + + /// Gets the database version. + [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] + public static Version DataBaseVersion { get => applicationStatusInfo.DatabaseVersion; } + + /// Gets the host map path. + /// ApplicationMapPath + "Portals\_default\". + public static string HostMapPath + { + get + { + if (hostMapPath == null) + { + hostMapPath = Path.Combine(applicationStatusInfo.ApplicationMapPath, @"Portals\_default\"); + } + + return hostMapPath; + } + } + + /// Gets the host path. + /// ApplicationPath + "/Portals/_default/". + public static string HostPath + { + get + { + if (hostPath == null) + { + hostPath = ApplicationPath + "/Portals/_default/"; + } + + return hostPath; + } + } + + /// Gets the install map path. + /// server map path of InstallPath. + public static string InstallMapPath + { + get + { + if (installMapPath == null) + { + installMapPath = applicationStatusInfo.ApplicationMapPath + "\\Install\\"; + } + + return installMapPath; + } + } + + /// Gets the install path. + /// ApplicationPath + "/Install/". + public static string InstallPath + { + get + { + if (installPath == null) + { + installPath = ApplicationPath + "/Install/"; + } + + return installPath; + } + } + + /// Gets the status of application. + /// + [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] + public static UpgradeStatus Status { get => (UpgradeStatus)applicationStatusInfo.Status; } + + /// Gets image file types. + /// Values read from ImageTypes List. If there is not a List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico. + [Obsolete("Deprecated in DotNetNuke 9.8.1. Use ImageFileTypes instead. Scheduled removal in v11.0.0.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "StyleCop.CSharp.NamingRules", + "SA1300:Element should begin with upper-case letter", + Justification = "Kept to prevent a breaking change, new overload created.")] + public static string glbImageFileTypes => ImageFileTypes; + + /// Gets image file types. + /// Values read from ImageTypes List. If there is not a List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico. + public static string ImageFileTypes + { + get + { + var listController = new ListController(); + var listEntries = listController.GetListEntryInfoItems("ImageTypes"); + if (listEntries == null || !listEntries.Any()) + { + return "jpg,jpeg,jpe,gif,bmp,png,svg,ico"; + } + + return string.Join(",", listEntries.Select(l => l.Value)); + } + } + + /// Gets a value indicating for how long the application has been running. + public static TimeSpan ElapsedSinceAppStart => AppStopwatch.Elapsed; + + /// Gets or sets the name of the IIS app. + /// + /// request.ServerVariables["APPL_MD_PATH"]. + /// + public static string IISAppName { get; set; } + + /// Gets or sets the name of the server. + /// + /// server name in config file or the server's machine name. + /// + public static string ServerName { get; set; } + + /// Gets or sets the operating system version. + /// + /// The operating system version. + /// + public static Version OperatingSystemVersion { get; set; } + + /// Gets or sets the NET framework version. + /// + /// The NET framework version. + /// + public static Version NETFrameworkVersion { get; set; } + + /// Gets the .Net framework version text. + /// The .Net framework version text. + public static string FormattedNetFrameworkVersion => FormatVersion(NETFrameworkVersion, "0", 3, "."); + + /// Gets or sets the database engine version. + /// + /// The database engine version. + /// + public static Version DatabaseEngineVersion { get; set; } + + /// Gets or sets the Dependency Service. + /// The Dependency Service. + internal static IServiceProvider DependencyProvider + { + get => dependencyProvider; + set + { + dependencyProvider = value; + if (dependencyProvider is INotifyPropertyChanged hasPropertyChanged) + { + hasPropertyChanged.PropertyChanged += OnDependencyProviderChanged; + } + else + { + OnDependencyProviderChanged(null, null); + } + } + } + + /// Redirects the specified URL. + /// The URL. + /// if set to [end response]. + public static void Redirect(string url, bool endResponse) + { + try + { + HttpContext.Current.Response.Redirect(url, endResponse); + } + catch (ThreadAbortException) + { + // we are ignoreing this error simply because there is no graceful way to redirect the user, wihtout the threadabort exception. + // RobC + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + + /// Checks if incremental sqlDataProvider files exist. + /// If a 09.08.01.01.sqlDataProvider file exists for a provided version 09.08.01 this method will return true. + /// The version. + /// A value indicating whether any incremental sql script file exists. + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial bool IncrementalVersionExists(Version version) => applicationStatusInfo.IncrementalVersionExists(version); + + /// Builds the cross tab dataset. + /// Name of the data set. + /// The result. + /// The fixed columns. + /// The variable columns. + /// The key column. + /// The field column. + /// The field type column. + /// The string value column. + /// The numeric value column. + /// the dataset instance. + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial DataSet BuildCrossTabDataSet( + string dataSetName, + IDataReader result, + string fixedColumns, + string variableColumns, + string keyColumn, + string fieldColumn, + string fieldTypeColumn, + string stringValueColumn, + string numericValueColumn) + { + return BuildCrossTabDataSet(dataSetName, result, fixedColumns, variableColumns, keyColumn, fieldColumn, fieldTypeColumn, stringValueColumn, numericValueColumn, CultureInfo.CurrentCulture); + } + + /// converts a data reader with serialized fields into a typed data set. + /// Name of the dataset to be created. + /// Data reader that contains all field values serialized. + /// List of fixed columns, delimited by commas. Columns must be contained in DataReader. + /// List of variable columns, delimited by commas. Columns must be contained in DataReader. + /// Name of the column, that contains the row ID. Column must be contained in DataReader. + /// Name of the column, that contains the field name. Column must be contained in DataReader. + /// Name of the column, that contains the field type name. Column must be contained in DataReader. + /// Name of the column, that contains the field value, if stored as string. Column must be contained in DataReader. + /// Name of the column, that contains the field value, if stored as number. Column must be contained in DataReader. + /// culture of the field values in data reader's string value column. + /// The generated DataSet. + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial DataSet BuildCrossTabDataSet( + string dataSetName, + IDataReader result, + string fixedColumns, + string variableColumns, + string keyColumn, + string fieldColumn, + string fieldTypeColumn, + string stringValueColumn, + string numericValueColumn, + CultureInfo culture) + { + string[] arrFixedColumns = null; + string[] arrVariableColumns = null; + string[] arrField; + string fieldType; + int intColumn; + int intKeyColumn; + + // create dataset + var crosstab = new DataSet(dataSetName); + crosstab.Namespace = "NetFrameWork"; + + // create table + var tab = new DataTable(dataSetName); + + // split fixed columns + arrFixedColumns = fixedColumns.Split(','); + + // add fixed columns to table + for (intColumn = 0; intColumn < arrFixedColumns.Length; intColumn++) + { + arrField = arrFixedColumns[intColumn].Split('|'); + var col = new DataColumn(arrField[0], Type.GetType("System." + arrField[1])); + tab.Columns.Add(col); + } + + // split variable columns + if (!string.IsNullOrEmpty(variableColumns)) + { + arrVariableColumns = variableColumns.Split(','); + + // add varible columns to table + for (intColumn = 0; intColumn < arrVariableColumns.Length; intColumn++) + { + arrField = arrVariableColumns[intColumn].Split('|'); + var col = new DataColumn(arrField[0], Type.GetType("System." + arrField[1])); + col.AllowDBNull = true; + tab.Columns.Add(col); + } + } + + // add table to dataset + crosstab.Tables.Add(tab); + + // add rows to table + intKeyColumn = -1; + DataRow row = null; + while (result.Read()) + { + // loop using KeyColumn as control break + if (Convert.ToInt32(result[keyColumn], CultureInfo.InvariantCulture) != intKeyColumn) + { + // add row + if (intKeyColumn != -1) + { + tab.Rows.Add(row); + } + + // create new row + row = tab.NewRow(); + + // assign fixed column values + for (intColumn = 0; intColumn < arrFixedColumns.Length; intColumn++) + { + arrField = arrFixedColumns[intColumn].Split('|'); + row[arrField[0]] = result[arrField[0]]; + } + + // initialize variable column values + if (!string.IsNullOrEmpty(variableColumns)) + { + for (intColumn = 0; intColumn < arrVariableColumns.Length; intColumn++) + { + arrField = arrVariableColumns[intColumn].Split('|'); + switch (arrField[1]) + { + case "Decimal": + row[arrField[0]] = 0; + break; + case "String": + row[arrField[0]] = string.Empty; + break; + } + } + } + + intKeyColumn = Convert.ToInt32(result[keyColumn], CultureInfo.InvariantCulture); + } + + // assign pivot column value + if (!string.IsNullOrEmpty(fieldTypeColumn)) + { + fieldType = result[fieldTypeColumn].ToString(); + } + else + { + fieldType = "String"; + } + + switch (fieldType) + { + case "Decimal": + row[Convert.ToInt32(result[fieldColumn], CultureInfo.InvariantCulture)] = result[numericValueColumn]; + break; + case "String": + if (ReferenceEquals(culture, CultureInfo.CurrentCulture)) + { + row[result[fieldColumn].ToString()] = result[stringValueColumn]; + } + else + { + switch (tab.Columns[result[fieldColumn].ToString()].DataType.ToString()) + { + case "System.Decimal": + case "System.Currency": + row[result[fieldColumn].ToString()] = decimal.Parse(result[stringValueColumn].ToString(), culture); + break; + case "System.Int32": + row[result[fieldColumn].ToString()] = int.Parse(result[stringValueColumn].ToString(), culture); + break; + default: + row[result[fieldColumn].ToString()] = result[stringValueColumn]; + break; + } + } + + break; + } + } + + result.Close(); + + // add row + if (intKeyColumn != -1) + { + tab.Rows.Add(row); + } + + // finalize dataset + crosstab.AcceptChanges(); + + // return the dataset + return crosstab; + } + + /// Converts the datareader to dataset. + /// The reader. + /// the dataset instance. + public static DataSet ConvertDataReaderToDataSet(IDataReader reader) + { + // add datatable to dataset + var objDataSet = new DataSet(); + + try + { + do + { + objDataSet.Tables.Add(ConvertDataReaderToDataTable(reader, false)); + } + while (reader.NextResult()); + } + finally + { + reader.Close(); + } + + return objDataSet; + } + + /// Converts the datareader to datatable. + /// The reader. + /// the datatable instance. + public static DataTable ConvertDataReaderToDataTable(IDataReader reader) + { + return ConvertDataReaderToDataTable(reader, true); + } + + /// Converts the datareader to datatable. + /// The reader. + /// Whether close reader. + /// the datatable instance. + public static DataTable ConvertDataReaderToDataTable(IDataReader reader, bool closeReader) + { + try + { + // create datatable from datareader + var objDataTable = new DataTable(); + int intFieldCount = reader.FieldCount; + int intCounter; + for (intCounter = 0; intCounter <= intFieldCount - 1; intCounter++) + { + objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter)); + } + + // populate datatable + objDataTable.BeginLoadData(); + var objValues = new object[intFieldCount]; + while (reader.Read()) + { + reader.GetValues(objValues); + objDataTable.LoadDataRow(objValues, true); + } + + objDataTable.EndLoadData(); + return objDataTable; + } + finally + { + if (closeReader) + { + reader.Close(); + } + } + } + + /// Gets the absolute server path. + /// The request. + /// absolute server path. + public static string GetAbsoluteServerPath(HttpRequest request) + { + var strServerPath = request.MapPath(request.ApplicationPath); + if (!strServerPath.EndsWith(@"\", StringComparison.Ordinal)) + { + strServerPath += @"\"; + } + + return strServerPath; + } + + /// Gets the ApplicationName for the MemberRole API. + /// + /// This overload is used to get the current ApplicationName. The Application + /// Name is in the form Prefix_Id, where Prefix is the object qualifier + /// for this instance of DotNetNuke, and ID is the current PortalId for normal + /// users or glbSuperUserAppName for SuperUsers. + /// + /// A string representing the application name. + public static string GetApplicationName() + { + string appName; + if (HttpContext.Current.Items["ApplicationName"] == null || string.IsNullOrEmpty(HttpContext.Current.Items["ApplicationName"].ToString())) + { + var portalSettings = PortalController.Instance.GetCurrentSettings(); + if (portalSettings == null) + { + appName = "/"; + } + else + { + appName = GetApplicationName(portalSettings.PortalId); + } + } + else + { + appName = Convert.ToString(HttpContext.Current.Items["ApplicationName"], CultureInfo.InvariantCulture); + } + + return appName; + } + + /// Gets the ApplicationName for the MemberRole API. + /// + /// This overload is used to build the Application Name from the Portal ID. + /// + /// The id of the portal (site). + /// A string representing the application name. + public static string GetApplicationName(int portalID) + { + // Get the Data Provider Configuration + ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration("data"); + + // Read the configuration specific information for the current Provider + var objProvider = (Provider)providerConfiguration.Providers[providerConfiguration.DefaultProvider]; + + // Get the Object Qualifier from the Provider Configuration + string objectQualifier = objProvider.Attributes["objectQualifier"]; + if (!string.IsNullOrEmpty(objectQualifier) && !objectQualifier.EndsWith("_", StringComparison.Ordinal)) + { + objectQualifier += "_"; + } + + return objectQualifier + Convert.ToString(portalID, CultureInfo.InvariantCulture); + } + + /// Finds the database version. + /// The major. + /// The minor. + /// The build. + /// return if can find the specific version, otherwise will return . + public static bool FindDatabaseVersion(int major, int minor, int build) + { + bool version = false; + IDataReader dr = null; + try + { + dr = DataProvider.Instance().FindDatabaseVersion(major, minor, build); + if (dr.Read()) + { + version = true; + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + finally + { + CBO.CloseDataReader(dr, true); + } + + return version; + } + + /// Updates the database version. + /// The version. + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial void UpdateDataBaseVersion(Version version) => applicationStatusInfo.UpdateDatabaseVersion(version); + + /// Updates the database version. + /// The version. + /// The increment (revision) number. + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial void UpdateDataBaseVersionIncrement(Version version, int increment) => + applicationStatusInfo.UpdateDatabaseVersionIncrement(version, increment); + + /// Gets the last applied iteration (revision). + /// The version for which to check the last revision. + /// The last applied iteration (revision) for the requested version. + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial int GetLastAppliedIteration(Version version) => + applicationStatusInfo.GetLastAppliedIteration(version); + + /// Adds the port. + /// The HTTP alias. + /// The original URL. + /// url with port if the post number is not 80. + public static string AddPort(string httpAlias, string originalUrl) + { + var uri = new Uri(originalUrl); + var aliasUri = new Uri(httpAlias); + + if (!uri.IsDefaultPort) + { + httpAlias = AddHTTP(aliasUri.Host + ":" + uri.Port + aliasUri.LocalPath); + } + + return httpAlias; + } + + /// Gets the name of the domain. + /// The request. + /// domain name. + public static string GetDomainName(HttpRequest request) + { + return GetDomainName(new HttpRequestWrapper(request), false); + } + + /// Gets the name of the domain. + /// The request. + /// domain name. + public static string GetDomainName(HttpRequestBase request) + { + return GetDomainName(request, false); + } + + /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ). + /// The request. + /// if set to [parse port number]. + /// domain name. + public static string GetDomainName(HttpRequest request, bool parsePortNumber) + { + return GetDomainName(new HttpRequestWrapper(request), parsePortNumber); + } + + /// returns the domain name of the current request ( ie. www.domain.com or 207.132.12.123 or www.domain.com/directory if subhost ). + /// The request. + /// if set to [parse port number]. + /// domain name. + public static string GetDomainName(HttpRequestBase request, bool parsePortNumber) + { + return TestableGlobals.Instance.GetDomainName(request.Url, parsePortNumber); + } + + /// Determin whether use port number by the value in config file. + /// + /// if use port number, otherwise, return . + /// + public static bool UsePortNumber() + { + bool usePort = true; + if (Config.GetSetting("UsePortNumber") != null) + { + usePort = bool.Parse(Config.GetSetting("UsePortNumber")); + } + + return usePort; + } + + /// Gets the file list. + /// file list. + public static ArrayList GetFileList() + { + return GetFileList(-1, string.Empty, true, string.Empty, false); + } + + /// Gets the file list. + /// The portal id. + /// file list. + public static ArrayList GetFileList(int portalId) + { + return GetFileList(portalId, string.Empty, true, string.Empty, false); + } + + /// Gets the file list. + /// The portal id. + /// The STR extensions. + /// file list. + public static ArrayList GetFileList(int portalId, string strExtensions) + { + return GetFileList(portalId, strExtensions, true, string.Empty, false); + } + + /// Gets the file list. + /// The portal id. + /// The STR extensions. + /// if set to [none specified]. + /// file list. + public static ArrayList GetFileList(int portalId, string strExtensions, bool noneSpecified) + { + return GetFileList(portalId, strExtensions, noneSpecified, string.Empty, false); + } + + /// Gets the file list. + /// The portal id. + /// The STR extensions. + /// if set to [none specified]. + /// The folder. + /// file list. + public static ArrayList GetFileList(int portalId, string strExtensions, bool noneSpecified, string folder) + { + return GetFileList(portalId, strExtensions, noneSpecified, folder, false); + } + + /// Gets the file list. + /// The portal id. + /// The STR extensions. + /// if set to [none specified]. + /// The folder. + /// if set to [include hidden]. + /// file list. + public static ArrayList GetFileList(int portalId, string strExtensions, bool noneSpecified, string folder, bool includeHidden) + { + var arrFileList = new ArrayList(); + if (noneSpecified) + { + arrFileList.Add(new FileItem(string.Empty, "<" + Localization.GetString("None_Specified") + ">")); + } + + var objFolder = FolderManager.Instance.GetFolder(portalId, folder); + + if (objFolder != null) + { + try + { + var files = FolderManager.Instance.GetFiles(objFolder); + var fileManager = FileManager.Instance; + + foreach (var file in files) + { + if (FilenameMatchesExtensions(file.FileName, strExtensions)) + { + if (file.SupportsFileAttributes) + { + if (fileManager.FileExists(objFolder, file.FileName)) + { + if (includeHidden) + { + arrFileList.Add(new FileItem(file.FileId.ToString(CultureInfo.InvariantCulture), file.FileName)); + } + else + { + var attributes = file.FileAttributes; + + if ((attributes & FileAttributes.Hidden) != FileAttributes.Hidden) + { + arrFileList.Add(new FileItem(file.FileId.ToString(CultureInfo.InvariantCulture), file.FileName)); + } + } + } + } + else + { + // File is stored in DB - Just add to arraylist + arrFileList.Add(new FileItem(file.FileId.ToString(CultureInfo.InvariantCulture), file.FileName)); + } + } + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + } + + return arrFileList; + } + + /// Gets the host portal settings. + /// Host portal settings. + [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] + public static partial PortalSettings GetHostPortalSettings() + => GetHostPortalSettings(GetCurrentServiceProvider().GetRequiredService()); + + /// Gets the host portal settings. + /// The host settings. + /// Host portal settings. + public static PortalSettings GetHostPortalSettings(IHostSettings hostSettings) + { + int tabId = -1; + int portalId = -1; + IPortalAliasInfo objPortalAliasInfo = null; + + // if the portal alias exists + if (hostSettings.HostPortalId > Null.NullInteger) + { + portalId = hostSettings.HostPortalId; + + // use the host portal + objPortalAliasInfo = new PortalAliasInfo(); + objPortalAliasInfo.PortalId = portalId; + } + + // load the PortalSettings into current context + return new PortalSettings(tabId, objPortalAliasInfo as PortalAliasInfo); + } + + /// Gets the portal domain name. + /// The portal alias. + /// The request or null. + /// if set to calls on the result. + /// domain name. + public static string GetPortalDomainName(string strPortalAlias, HttpRequest request, bool blnAddHTTP) + { + string strDomainName = string.Empty; + string strURL = string.Empty; + int intAlias; + if (request != null) + { + strURL = GetDomainName(request); + } + + string[] arrPortalAlias = strPortalAlias.Split(','); + for (intAlias = 0; intAlias <= arrPortalAlias.Length - 1; intAlias++) + { + if (arrPortalAlias[intAlias] == strURL) + { + strDomainName = arrPortalAlias[intAlias]; + } + } + + if (string.IsNullOrEmpty(strDomainName)) + { + strDomainName = arrPortalAlias[0]; + } + + if (blnAddHTTP) + { + strDomainName = AddHTTP(strDomainName); + } + + return strDomainName; + } + + /// Gets the portal settings. + /// Portal settings. + public static PortalSettings GetPortalSettings() + { + PortalSettings portalSettings = null; + + // Try getting the settings from the Context + if (HttpContext.Current != null) + { + portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; + } + + // If nothing then try getting the Host Settings + if (portalSettings == null) + { + portalSettings = GetHostPortalSettings(); + } + + return portalSettings; + } + + /// Returns the folder path under the root for the portal. + /// The folder the absolute path. + /// Portal Id. + /// A string containing the subfolder path. + public static string GetSubFolderPath(string strFileNamePath, int portalId) + { + string parentFolderName; + if (portalId == Null.NullInteger) + { + parentFolderName = HostMapPath.Replace("/", @"\"); + } + else + { + PortalInfo objPortal = PortalController.Instance.GetPortal(portalId); + parentFolderName = objPortal.HomeDirectoryMapPath.Replace("/", @"\"); + } + + string strFolderpath = strFileNamePath.Substring(0, strFileNamePath.LastIndexOf(@"\", StringComparison.Ordinal) + 1); + return strFolderpath.Substring(parentFolderName.Length).Replace(@"\", "/"); + } + + /// The GetTotalRecords method gets the number of Records returned. + /// An containing the Total number of records. + /// The total number of records in the data reader. + public static int GetTotalRecords(ref IDataReader dr) + { + int total = 0; + if (dr.Read()) + { + try + { + total = Convert.ToInt32(dr["TotalRecords"], CultureInfo.InvariantCulture); + } + catch (Exception exc) + { + Logger.Error(exc); + total = -1; + } + } + + return total; + } + + /// Sets the status. + /// The status. + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial void SetStatus(UpgradeStatus status) => + applicationStatusInfo.SetStatus((DotNetNuke.Abstractions.Application.UpgradeStatus)status); + + /// + /// ImportFile - converts a file url (/Portals/0/somefile.gif) to the appropriate + /// FileID=xx identification for use in importing portals, tabs and modules. + /// + /// The id of the portal (site) on which the file is imported. + /// The url to the file. + /// The file handler url for the file (FileID=xxxx). + public static string ImportFile(int portalId, string url) + { + string strUrl = url; + if (GetURLType(url) == TabType.File) + { + var fileName = Path.GetFileName(url); + + var folderPath = url.Substring(0, url.LastIndexOf(fileName, StringComparison.OrdinalIgnoreCase)); + var folder = FolderManager.Instance.GetFolder(portalId, folderPath); + + if (folder != null) + { + var file = FileManager.Instance.GetFile(folder, fileName); + if (file != null) + { + strUrl = "FileID=" + file.FileId; + } + } + } + + return strUrl; + } + + /// Encode the post url. + /// The post url. + /// encoded value. + public static string HTTPPOSTEncode(string strPost) + { + strPost = strPost.Replace(@"\", string.Empty); + strPost = HttpUtility.UrlEncode(strPost); + strPost = strPost.Replace("%2f", "/"); + return strPost; + } + + /// Sets the ApplicationName for the MemberRole API. + /// + /// This overload takes a the PortalId. + /// + /// The Portal ID. + public static void SetApplicationName(int portalId) + { + HttpContext.Current.Items["ApplicationName"] = GetApplicationName(portalId); + } + + /// Sets the ApplicationName for the MemberRole API. + /// + /// This overload takes a the PortalId. + /// + /// The Application Name to set. + public static void SetApplicationName(string applicationName) + { + HttpContext.Current.Items["ApplicationName"] = applicationName; + } + + /// Formats the address on a single line ( ie. Unit, Street, City, Region, Country, PostalCode ). + /// The unit. + /// The street. + /// The city. + /// The region. + /// The country. + /// The postal code. + /// A string containing the whole address on a single line. + public static string FormatAddress(object unit, object street, object city, object region, object country, object postalCode) + { + string strAddress = string.Empty; + if (unit != null) + { + if (!string.IsNullOrEmpty(unit.ToString().Trim())) + { + strAddress += ", " + unit; + } + } + + if (street != null) + { + if (!string.IsNullOrEmpty(street.ToString().Trim())) + { + strAddress += ", " + street; + } + } + + if (city != null) + { + if (!string.IsNullOrEmpty(city.ToString().Trim())) + { + strAddress += ", " + city; + } + } + + if (region != null) + { + if (!string.IsNullOrEmpty(region.ToString().Trim())) + { + strAddress += ", " + region; + } + } + + if (country != null) + { + if (!string.IsNullOrEmpty(country.ToString().Trim())) + { + strAddress += ", " + country; + } + } + + if (postalCode != null) + { + if (!string.IsNullOrEmpty(postalCode.ToString().Trim())) + { + strAddress += ", " + postalCode; + } + } + + if (!string.IsNullOrEmpty(strAddress.Trim())) + { + strAddress = strAddress.Substring(2); + } + + return strAddress; + } + + /// Formats the system.version into the standard format nn.nn.nn. + /// The version. + /// Formatted version as string. + public static string FormatVersion(Version version) + { + return FormatVersion(version, false); + } + + /// Formats the version. + /// The version. + /// if set to [include build]. + /// Formatted version as string. + /// + /// + /// var version = new Version(6, 0, 0, 147); + /// string formattedVersion = FormatVersion(version, true); // formattedVersion's value will be: 06.00.00(147) + /// + /// + public static string FormatVersion(Version version, bool includeBuild) + { + string strVersion = FormattableString.Invariant($"{version.Major:00}.{version.Minor:00}.{version.Build:00}"); + if (includeBuild) + { + strVersion += $" ({version.Revision})"; + } + + return strVersion; + } + + /// Formats a version into the standard format nn.nn.nn. + /// The version to be formatted. + /// The field format. + /// The field count. + /// The delimiter character. + /// Formatted version as a string. + public static string FormatVersion(Version version, string fieldFormat, int fieldCount, string delimiterCharacter) + { + string strVersion = string.Empty; + const int intZero = 0; + if (version != null) + { + if (fieldCount > 0) + { + if (version.Major >= 0) + { + strVersion += version.Major.ToString(fieldFormat, CultureInfo.InvariantCulture); + } + else + { + strVersion += intZero.ToString(fieldFormat, CultureInfo.InvariantCulture); + } + } + + if (fieldCount > 1) + { + strVersion += delimiterCharacter; + if (version.Minor >= 0) + { + strVersion += version.Minor.ToString(fieldFormat, CultureInfo.InvariantCulture); + } + else + { + strVersion += intZero.ToString(fieldFormat, CultureInfo.InvariantCulture); + } + } + + if (fieldCount > 2) + { + strVersion += delimiterCharacter; + if (version.Build >= 0) + { + strVersion += version.Build.ToString(fieldFormat, CultureInfo.InvariantCulture); + } + else + { + strVersion += intZero.ToString(fieldFormat, CultureInfo.InvariantCulture); + } + } + + if (fieldCount > 3) + { + strVersion += delimiterCharacter; + if (version.Revision >= 0) + { + strVersion += version.Revision.ToString(fieldFormat, CultureInfo.InvariantCulture); + } + else + { + strVersion += intZero.ToString(fieldFormat, CultureInfo.InvariantCulture); + } + } + } + + return strVersion; + } + + /// Cloaks the text, obfuscate sensitive data to prevent collection by robots and spiders and crawlers. + /// The personal info. + /// obfuscated sensitive data by hustling ASCII characters. + public static string CloakText(string personalInfo) + { + if (personalInfo == null) + { + return Null.NullString; + } + + var characterCodes = personalInfo.Select(ch => ((int)ch).ToString(CultureInfo.InvariantCulture)); + return $""" + + """; + } + + /// Gets the medium date by current culture. + /// The date. + /// return formatted content of the date if parameter isn't empty, else return the parameter. + /// + /// + /// var mediumDate = GetMediumDate("6/1/2011"); + /// + /// + public static string GetMediumDate(string strDate) + { + if (!string.IsNullOrEmpty(strDate)) + { + DateTime datDate = Convert.ToDateTime(strDate, CultureInfo.CurrentCulture); + string strMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(datDate.Month); + strDate = $"{datDate.Day}-{strMonth}-{datDate.Year}"; + } + + return strDate; + } + + /// Gets the short date. + /// The date. + /// short date content of the input. + public static string GetShortDate(string strDate) + { + if (!string.IsNullOrEmpty(strDate)) + { + var datDate = Convert.ToDateTime(strDate, CultureInfo.CurrentCulture); + strDate = $"{datDate.Month}/{datDate.Day}/{datDate.Year}"; + } + + return strDate; + } + + /// Determines whether current request contains admin control information. + /// + /// if current request contains admin control information; otherwise, . + /// + public static bool IsAdminControl() + { + // This is needed to avoid an exception if there is no Context. This will occur if code is called from the Scheduler + if (HttpContext.Current == null) + { + return false; + } + + return (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) || (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"])); + } + + /// Determines whether current request use admin skin. + /// + /// if current request use admin skin; otherwise, . + /// + public static bool IsAdminSkin() + { + bool isAdminSkin = Null.NullBoolean; + if (HttpContext.Current != null) + { + string controlKey = string.Empty; + if (HttpContext.Current.Request.QueryString["ctl"] != null) + { + controlKey = HttpContext.Current.Request.QueryString["ctl"].ToLowerInvariant(); + } + + int moduleID = -1; + if (HttpContext.Current.Request.QueryString["mid"] != null) + { + if (!int.TryParse(HttpContext.Current.Request.QueryString["mid"], out moduleID)) + { + moduleID = -1; + } + } + + isAdminSkin = (!string.IsNullOrEmpty(controlKey) && !string.Equals(controlKey, "view", StringComparison.OrdinalIgnoreCase) && moduleID != -1) || + (!string.IsNullOrEmpty(controlKey) && AdminControlKeys.Contains(controlKey) && moduleID == -1); + } + + return isAdminSkin; + } + + /// Returns whether the current tab is in EditMode. + /// if the tab is in Edit mode; otherwise . + public static bool IsEditMode() + { + return Personalization.GetUserMode() == PortalSettings.Mode.Edit && TabPermissionController.CanAddContentToPage(); + } + + /// Returns whether the current tab is in LayoutMode. + /// if the current tab is in layout mode; otherwise . + public static bool IsLayoutMode() + { + return TabPermissionController.CanAddContentToPage() && Personalization.GetUserMode() == PortalSettings.Mode.Layout; + } + + /// Creates the RSS. + /// The dr. + /// The title field. + /// The URL field. + /// The created date field. + /// The syndicate field. + /// Name of the domain. + /// Name of the file. + public static void CreateRSS( + IDataReader dr, + string titleField, + string urlField, + string createdDateField, + string syndicateField, + string domainName, + string fileName) + { + // Obtain PortalSettings from Current Context + var portalSettings = PortalController.Instance.GetCurrentSettings(); + var strRSS = new StringBuilder(); + var strRelativePath = domainName + fileName.Substring(fileName.IndexOf("\\Portals", StringComparison.InvariantCultureIgnoreCase)).Replace(@"\", "/"); + strRelativePath = strRelativePath.Substring(0, strRelativePath.LastIndexOf("/", StringComparison.InvariantCulture)); + try + { + while (dr.Read()) + { + if (!int.TryParse((dr[syndicateField] ?? string.Empty).ToString(), out var field) || field <= 0) + { + continue; + } + + strRSS.AppendLine(" "); + strRSS.AppendLine(" " + dr[titleField] + ""); + var drUrl = (dr["URL"] ?? string.Empty).ToString(); + if (drUrl.IndexOf("://", StringComparison.InvariantCulture) == -1) + { + strRSS.Append(" "); + if (NumberMatchRegex.IsMatch(drUrl)) + { + strRSS.Append(domainName + "/" + glbDefaultPage + "?tabid=" + dr[urlField]); + } + else + { + strRSS.Append(strRelativePath + dr[urlField]); + } + + strRSS.AppendLine(""); + } + else + { + strRSS.AppendLine(" " + dr[urlField] + ""); + } + + strRSS.AppendLine(" " + portalSettings.PortalName + " " + GetMediumDate(dr[createdDateField].ToString()) + ""); + strRSS.AppendLine(" "); + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + finally + { + CBO.CloseDataReader(dr, true); + } + + if (strRSS.Length == 0) + { + strRSS.Append( + "" + + Environment.NewLine + + "" + + Environment.NewLine + + " " + + Environment.NewLine + + " " + + portalSettings.PortalName + + "" + + Environment.NewLine + + " " + + domainName + + "" + + Environment.NewLine + + " " + + portalSettings.PortalName + + "" + + Environment.NewLine + + " en-us" + + Environment.NewLine + + " " + + (!string.IsNullOrEmpty(portalSettings.FooterText) + ? portalSettings.FooterText.Replace( + "[year]", + DateTime.Now.Year.ToString(CultureInfo.InvariantCulture)) + : string.Empty) + + "" + + Environment.NewLine + + " " + + portalSettings.Email + + "" + + Environment.NewLine + + strRSS + + " " + + Environment.NewLine + + ""); + File.WriteAllText(fileName, strRSS.ToString()); + } + else + { + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + } + } + + /// injects the upload directory into raw HTML for src and background tags. + /// raw HTML text. + /// path of portal image directory. + /// HTML with paths for images and background corrected. + public static string ManageUploadDirectory(string strHTML, string strUploadDirectory) + { + strHTML = ManageTokenUploadDirectory(strHTML, strUploadDirectory, "src"); + return ManageTokenUploadDirectory(strHTML, strUploadDirectory, "background"); + } + + /// Injects the upload directory into raw HTML for a single token. + /// The raw HTML text. + /// The path of portal image directory. + /// The token to be replaced. + /// HTML with paths for images and background corrected. + /// + /// Called by ManageUploadDirectory for each token. + /// + public static string ManageTokenUploadDirectory(string strHTML, string strUploadDirectory, string strToken) + { + int urlStartPosition = 0; + var sbBuff = new StringBuilder(string.Empty); + if (!string.IsNullOrEmpty(strHTML)) + { + var tokenLength = strToken.Length + 2; + string uploadDirectory = strUploadDirectory.ToLowerInvariant(); + + var tokenStartPosition = strHTML.IndexOf(strToken + "=\"", StringComparison.OrdinalIgnoreCase); + while (tokenStartPosition != -1) + { + sbBuff.Append(strHTML.Substring(urlStartPosition, tokenStartPosition - urlStartPosition + tokenLength)); // keep characters left of URL + urlStartPosition = tokenStartPosition + tokenLength; + var endOfUrl = strHTML.IndexOf("\"", urlStartPosition, StringComparison.Ordinal); + string strUrl; + if (endOfUrl >= 0) + { + strUrl = strHTML.Substring(urlStartPosition, endOfUrl - urlStartPosition).ToLowerInvariant(); + } + else + { + strUrl = strHTML.Substring(urlStartPosition).ToLowerInvariant(); + } + + // add upload directory if we are linking internally and the upload directory is not already included + if (!strUrl.Contains("://", StringComparison.Ordinal) && !strUrl.StartsWith("/", StringComparison.Ordinal) && !strUrl.StartsWith(uploadDirectory, StringComparison.OrdinalIgnoreCase)) + { + sbBuff.Append(strUploadDirectory); + } + + // find position of next occurrence: + tokenStartPosition = strHTML.IndexOf(strToken + "=\"", urlStartPosition + strUrl.Length + 2, StringComparison.OrdinalIgnoreCase); + } + + if (urlStartPosition > -1) + { + sbBuff.Append(strHTML.Substring(urlStartPosition)); + } + } + + return sbBuff.ToString(); + } + + /// Finds the control recursive from child to parent. + /// current control. + /// the control name which want to find out. + /// control which'name is strControlName, or else return null if didn't match any control. + public static Control FindControlRecursive(Control objControl, string strControlName) + { + if (objControl.Parent == null) + { + return null; + } + else + { + if (objControl.Parent.FindControl(strControlName) != null) + { + return objControl.Parent.FindControl(strControlName); + } + else + { + return FindControlRecursive(objControl.Parent, strControlName); + } + } + } + + /// Searches control hierarchy from top down to find a control matching the passed in name. + /// Root control to begin searching. + /// Name of control to look for. + /// The found control or null. + /// + /// This differs from FindControlRecursive in that it looks down the control hierarchy, whereas, the + /// FindControlRecursive starts at the passed in control and walks the tree up. Therefore, this function is + /// more a expensive task. + /// + public static Control FindControlRecursiveDown(Control objParent, string strControlName) + { + Control objCtl; + objCtl = objParent.FindControl(strControlName); + if (objCtl == null) + { + foreach (Control objChild in objParent.Controls) + { + objCtl = FindControlRecursiveDown(objChild, strControlName); + if (objCtl != null) + { + break; + } + } + } + + return objCtl; + } + + /// Sets the form focus. + /// The control. + public static void SetFormFocus(Control control) + { + if (control.Page != null && control.Visible) + { + if (control.Page.Request.Browser.EcmaScriptVersion.Major >= 1) + { + // JH dnn.js mod + if (ClientAPI.ClientAPIDisabled() == false) + { + JavaScript.RegisterClientReference(control.Page, ClientAPI.ClientNamespaceReferences.dnn); + DNNClientAPI.SetInitialFocus(control.Page, control); + } + else + { + // Create JavaScript + var sb = new StringBuilder(); + sb.Append(""); + + // Register Client Script + ClientAPI.RegisterClientScriptBlock(control.Page, "InitialFocus", sb.ToString()); + } + } + } + } + + /// Gets the external request. + /// The address. + /// Web request. + [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] + public static partial HttpWebRequest GetExternalRequest(string address) + => GetExternalRequest(GetCurrentServiceProvider().GetRequiredService(), address); + + /// Gets the external request. + /// The host settings. + /// The address. + /// Web request. + public static HttpWebRequest GetExternalRequest(IHostSettings hostSettings, string address) + { + // Create the request object + var objRequest = (HttpWebRequest)WebRequest.Create(address); + + // Set a time-out to the request ... 10 seconds + objRequest.Timeout = (int)hostSettings.WebRequestTimeout.TotalMilliseconds; + + // Attach a User Agent to the request + objRequest.UserAgent = "DotNetNuke"; + + // If there is Proxy info, apply it to the request + if (!string.IsNullOrEmpty(hostSettings.ProxyServer)) + { + // Create a new Proxy + WebProxy proxy; + + // Create a new Network Credentials item + NetworkCredential proxyCredentials; + + // Fill Proxy info from host settings + proxy = new WebProxy(hostSettings.ProxyServer, hostSettings.ProxyPort); + if (!string.IsNullOrEmpty(hostSettings.ProxyUsername)) + { + // Fill the credential info from host settings + proxyCredentials = new NetworkCredential(hostSettings.ProxyUsername, hostSettings.ProxyPassword); + + // Apply credentials to proxy + proxy.Credentials = proxyCredentials; + } + + // Apply Proxy to request + objRequest.Proxy = proxy; + } + + return objRequest; + } + + /// Gets the external request. + /// The address. + /// The credentials. + /// Web request. + [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] + public static partial HttpWebRequest GetExternalRequest(string address, NetworkCredential credentials) + => GetExternalRequest(GetCurrentServiceProvider().GetRequiredService(), address, credentials); + + /// Gets the external request. + /// The host settings. + /// The address. + /// The credentials. + /// Web request. + public static HttpWebRequest GetExternalRequest(IHostSettings hostSettings, string address, NetworkCredential credentials) + { + // Create the request object + var objRequest = (HttpWebRequest)WebRequest.Create(address); + + // Set a time-out to the request ... 10 seconds + objRequest.Timeout = (int)hostSettings.WebRequestTimeout.TotalMilliseconds; + + // Attach a User Agent to the request + objRequest.UserAgent = "DotNetNuke"; + + // Attach supplied credentials + if (credentials.UserName != null) + { + objRequest.Credentials = credentials; + } + + // If there is Proxy info, apply it to the request + if (!string.IsNullOrEmpty(hostSettings.ProxyServer)) + { + // Create a new Proxy + WebProxy proxy; + + // Create a new Network Credentials item + NetworkCredential proxyCredentials; + + // Fill Proxy info from host settings + proxy = new WebProxy(hostSettings.ProxyServer, hostSettings.ProxyPort); + if (!string.IsNullOrEmpty(hostSettings.ProxyUsername)) + { + // Fill the credential info from host settings + proxyCredentials = new NetworkCredential(hostSettings.ProxyUsername, hostSettings.ProxyPassword); + + // Apply credentials to proxy + proxy.Credentials = proxyCredentials; + } + + objRequest.Proxy = proxy; + } + + return objRequest; + } + + /// Deletes the folder recursive, include the folder itself will be deleted. + /// The root. + public static void DeleteFolderRecursive(string strRoot) + => FileSystemUtils.DeleteFolderRecursive(strRoot); + + /// Deletes the folder recursive, include the folder itself will be deleted. + /// The root. + /// The cancellation token. + /// A indicating completion. + public static async Task DeleteFolderRecursiveAsync(string strRoot, CancellationToken cancellationToken = default) + => await FileSystemUtils.DeleteFolderRecursiveAsync(strRoot, cancellationToken); + + /// Deletes the files recursive which match the filter, will not delete folders and will ignore folder which is hidden or system. + /// The root. + /// The filter. + public static void DeleteFilesRecursive(string strRoot, string filter) + => FileSystemUtils.DeleteFilesRecursive(strRoot, filter); + + /// Deletes the files recursive which match the filter, will not delete folders and will ignore folder which is hidden or system. + /// The root. + /// The filter. + /// The cancellation token. + /// A indicating completion. + public static async Task DeleteFilesRecursiveAsync(string strRoot, string filter, CancellationToken cancellationToken = default) + => await FileSystemUtils.DeleteFilesRecursiveAsync(strRoot, filter, cancellationToken); + + /// Cleans the name of the file. + /// Name of the file. + /// clean name. + public static string CleanFileName(string fileName) + { + return CleanFileName(fileName, string.Empty, string.Empty); + } + + /// Cleans the name of the file. + /// Name of the file. + /// The bad chars. + /// clean name. + public static string CleanFileName(string fileName, string badChars) + { + return CleanFileName(fileName, badChars, string.Empty); + } + + /// Cleans the name of the file. + /// Name of the file. + /// The bad chars. + /// The replace char. + /// clean name. + public static string CleanFileName(string fileName, string badChars, string replaceChar) + { + string strFileName = fileName; + if (string.IsNullOrEmpty(badChars)) + { + badChars = ":/\\?*|" + ((char)34) + ((char)39) + ((char)9); + } + + if (string.IsNullOrEmpty(replaceChar)) + { + replaceChar = "_"; + } + + int intCounter; + for (intCounter = 0; intCounter <= badChars.Length - 1; intCounter++) + { + strFileName = strFileName.Replace(badChars.Substring(intCounter, 1), replaceChar); + } + + return strFileName; + } + + /// + /// CleanName - removes characters from Module/Tab names that are being used for file names + /// in Module/Tab Import/Export. + /// + /// The name to clean. + /// A cleaned string. + public static string CleanName(string name) + { + string strName = name; + string strBadChars = ". ~`!@#$%^&*()-_+={[}]|\\:;<,>?/" + ((char)34) + ((char)39); + int intCounter; + for (intCounter = 0; intCounter <= strBadChars.Length - 1; intCounter++) + { + strName = strName.Replace(strBadChars.Substring(intCounter, 1), string.Empty); + } + + return strName; + } + + /// + /// CreateValidClass - removes characters from Module/Tab names which are invalid + /// for use as an XHTML class attribute / CSS class selector value and optionally + /// prepends the letter 'A' if the first character is not alphabetic. This differs + /// from CreateValidID which replaces invalid characters with an underscore + /// and replaces the first letter with an 'A' if it is not alphabetic. + /// + /// String to use to create the class value. + /// If set true, validate whether the first character + /// is alphabetic and, if not, prepend the letter 'A' to the returned value. + /// A string suitable for use as a class value. + public static string CreateValidClass(string inputValue, bool validateFirstChar) + { + string returnValue = Null.NullString; + + // Regex is expensive so we will cache the results in a lookup table + var validClassLookupDictionary = CBO.GetCachedObject>( + new CacheItemArgs("ValidClassLookup", 200, CacheItemPriority.NotRemovable), + (CacheItemArgs cacheItemArgs) => new SharedDictionary()); + + bool idFound = Null.NullBoolean; + using (ISharedCollectionLock readLock = validClassLookupDictionary.GetReadLock()) + { + if (validClassLookupDictionary.TryGetValue(inputValue, out var className)) + { + // Return value + returnValue = className; + idFound = true; + } + } + + if (!idFound) + { + using (ISharedCollectionLock writeLock = validClassLookupDictionary.GetWriteLock()) + { + if (!validClassLookupDictionary.ContainsKey(inputValue)) + { + // Create Valid Class + // letters ([a-zA-Z]), digits ([0-9]), hyphens ("-") and underscores ("_") are valid in class values + // Remove all characters that aren't in the list + returnValue = InvalidCharacters.Replace(inputValue, string.Empty); + + // If we're asked to validate the first character... + if (validateFirstChar) + { + // classes should begin with a letter ([A-Za-z])' + // prepend a starting non-letter character with an A + if (InvalidCharacters.IsMatch(returnValue)) + { + returnValue = "A" + returnValue; + } + } + + // put in Dictionary + validClassLookupDictionary[inputValue] = returnValue; + } + } + } + + // Return Value + return returnValue; + } + + /// Creates the valid ID. + /// The input value. + /// String with a valid ID. + public static string CreateValidID(string inputValue) + { + string returnValue = Null.NullString; + + // Regex is expensive so we will cache the results in a lookup table + var validIDLookupDictionary = CBO.GetCachedObject>( + new CacheItemArgs("ValidIDLookup", 200, CacheItemPriority.NotRemovable), + (CacheItemArgs cacheItemArgs) => new SharedDictionary()); + + bool idFound = Null.NullBoolean; + using (ISharedCollectionLock readLock = validIDLookupDictionary.GetReadLock()) + { + if (validIDLookupDictionary.TryGetValue(inputValue, out var id)) + { + // Return value + returnValue = id; + idFound = true; + } + } + + if (!idFound) + { + using (ISharedCollectionLock writeLock = validIDLookupDictionary.GetWriteLock()) + { + if (!validIDLookupDictionary.ContainsKey(inputValue)) + { + // Create Valid ID + // '... letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".")' are valid identifiers + // We aren't allowing hyphens or periods, even though they're valid, since the previous version of this function didn't + // Replace all characters that aren't in the list with an underscore + returnValue = InvalidCharacters.Replace(inputValue, "_"); + + // identifiers '... must begin with a letter ([A-Za-z])' + // replace a starting non-letter character with an A + returnValue = InvalidInitialCharacters.Replace(returnValue, "A"); + + // put in Dictionary + validIDLookupDictionary[inputValue] = returnValue; + } + } + } + + return returnValue; + } + + /// Get the URL to show the "access denied" message. + /// URL to access denied view. + public static string AccessDeniedURL() + { + return AccessDeniedURL(string.Empty); + } + + /// Get the URL to show the "access denied" message. + /// The message to display. + /// URL to access denied view. + public static string AccessDeniedURL(string message) + { + string strURL = string.Empty; + + var currentTabId = TabController.CurrentPage.TabID; + var currentUserId = UserController.Instance.GetCurrentUserInfo().UserID; + if (HttpContext.Current.Request.IsAuthenticated) + { + if (string.IsNullOrEmpty(message)) + { + // redirect to access denied page + strURL = navigationManager.NavigateURL(currentTabId, "Access Denied"); + } + else + { + // redirect to access denied page with custom message + var messageGuid = DataProvider.Instance().AddRedirectMessage( + currentUserId, currentTabId, message).ToString("N"); + strURL = navigationManager.NavigateURL(currentTabId, "Access Denied", "message=" + messageGuid); + } + } + else + { + strURL = LoginURL(HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl), false); + } + + return strURL; + } + + /// Adds the current request's protocol ("http://" or "https://") to the given URL, if it does not already have a protocol specified. + /// The URL. + /// The formatted URL. + public static string AddHTTP(string strURL) + { + if (!string.IsNullOrEmpty(strURL)) + { + if (!strURL.Contains("mailto:", StringComparison.OrdinalIgnoreCase) + && !strURL.Contains("://", StringComparison.Ordinal) + && !strURL.Contains("~", StringComparison.Ordinal) + && !strURL.Contains(@"\\", StringComparison.Ordinal)) + { + var secure = HttpContext.Current != null && UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request); + strURL = (secure ? "https://" : "http://") + strURL; + } + } + + return strURL; + } + + /// Generates the Application root url (including the tab/page). + /// + /// This overload assumes the current page. + /// + /// The formatted root url. + public static string ApplicationURL() + { + var currentPage = TabController.CurrentPage; + if (currentPage != null && currentPage.HasAVisibleVersion) + { + return ApplicationURL(currentPage.TabID); + } + + return ApplicationURL(-1); + } + + /// Generates the Application root url (including the tab/page). + /// + /// This overload takes the tabid (page id) as a parameter. + /// + /// The id of the tab/page. + /// The formatted root url. + public static string ApplicationURL(int tabID) + { + string strURL = "~/" + glbDefaultPage; + if (tabID != -1) + { + strURL += "?tabid=" + tabID; + } + + return strURL; + } + + /// Formats the help URL, adding query-string parameters and a protocol (if missing). + /// The help URL. + /// The portal settings. + /// The name of the module. + /// Formatted URL. + public static string FormatHelpUrl(string helpUrl, PortalSettings objPortalSettings, string name) + { + return FormatHelpUrl(helpUrl, objPortalSettings, name, string.Empty); + } + + /// Formats the help URL, adding query-string parameters and a protocol (if missing). + /// The help URL. + /// The portal settings. + /// The name of the module. + /// The version of the module. + /// Formatted URL. + public static string FormatHelpUrl(string helpUrl, PortalSettings objPortalSettings, string name, string version) + { + string strURL = helpUrl; + if (strURL.Contains("?", StringComparison.Ordinal)) + { + strURL += "&helpculture="; + } + else + { + strURL += "?helpculture="; + } + + if (!string.IsNullOrEmpty(Thread.CurrentThread.CurrentUICulture.ToString())) + { + strURL += Thread.CurrentThread.CurrentUICulture.ToString().ToLowerInvariant(); + } + else + { + strURL += objPortalSettings.DefaultLanguage.ToLowerInvariant(); + } + + if (!string.IsNullOrEmpty(name)) + { + strURL += "&helpmodule=" + HttpUtility.UrlEncode(name); + } + + if (!string.IsNullOrEmpty(version)) + { + strURL += "&helpversion=" + HttpUtility.UrlEncode(version); + } + + return AddHTTP(strURL); + } + + /// Generates the correctly formatted friendly URL. + /// + /// Assumes Default.aspx, and that portalsettings are saved to Context. + /// + /// The current tab. + /// The path to format. + /// The formatted (friendly) URL. + public static string FriendlyUrl(TabInfo tab, string path) + { + return FriendlyUrl(tab, path, glbDefaultPage); + } + + /// Generates the correctly formatted friendly URL. + /// + /// This overload includes an optional page to include in the url. + /// + /// The current tab. + /// The path to format. + /// The page to include in the url. + /// The formatted (friendly) URL. + public static string FriendlyUrl(TabInfo tab, string path, string pageName) + { + var portalSettings = PortalController.Instance.GetCurrentSettings(); + return FriendlyUrl(tab, path, pageName, portalSettings); + } + + /// Generates the correctly formatted friendly URL. + /// + /// This overload includes the portal settings for the site. + /// + /// The current tab. + /// The path to format. + /// The portal settings. + /// The formatted (friendly) URL. + [DnnDeprecated(9, 4, 3, "Use the IPortalSettings overload")] + public static partial string FriendlyUrl(TabInfo tab, string path, PortalSettings settings) + { + return FriendlyUrl(tab, path, (IPortalSettings)settings); + } + + /// Generates the correctly formatted friendly URL. + /// + /// This overload includes the portal settings for the site. + /// + /// The current tab. + /// The path to format. + /// The portal settings. + /// The formatted (friendly) URL. + public static string FriendlyUrl(TabInfo tab, string path, IPortalSettings settings) + { + return FriendlyUrl(tab, path, glbDefaultPage, settings); + } + + /// Generates the correctly formatted friendly URL. + /// + /// This overload includes an optional page to include in the URL, and the portal + /// settings for the site. + /// + /// The current tab. + /// The path to format. + /// The page to include in the URL. + /// The portal settings. + /// The formatted (friendly) url. + [DnnDeprecated(9, 4, 3, "Use the IPortalSettings overload")] + public static partial string FriendlyUrl(TabInfo tab, string path, string pageName, PortalSettings settings) + { + return FriendlyUrl(tab, path, pageName, (IPortalSettings)settings); + } + + /// Generates the correctly formatted friendly URL. + /// + /// This overload includes an optional page to include in the URL, and the portal + /// settings for the site. + /// + /// The current tab. + /// The path to format. + /// The page to include in the URL. + /// The portal settings. + /// The formatted (friendly) url. + public static string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings) + { + return FriendlyUrlProvider.Instance().FriendlyUrl(tab, path, pageName, settings); + } + + /// Generates the correctly formatted friendly url. + /// + /// This overload includes an optional page to include in the url, and the portal + /// alias for the site. + /// + /// The current tab. + /// The path to format. + /// The page to include in the URL. + /// The portal alias for the site. + /// The formatted (friendly) URL. + public static string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) + { + return FriendlyUrlProvider.Instance().FriendlyUrl(tab, path, pageName, portalAlias); + } + + /// Returns the type of URl (T=other tab, F=file, U=URL, N=normal). + /// The url. + /// The url type. + public static TabType GetURLType(string url) + { + if (string.IsNullOrEmpty(url)) + { + return TabType.Normal; + } + + if (!url.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase) + && !url.Contains("://", StringComparison.Ordinal) + && !url.StartsWith("~", StringComparison.Ordinal) + && !url.StartsWith(@"\\", StringComparison.Ordinal) + && !url.StartsWith("/", StringComparison.Ordinal)) + { + if (NumberMatchRegex.IsMatch(url)) + { + return TabType.Tab; + } + + if (url.StartsWith("userid=", StringComparison.InvariantCultureIgnoreCase)) + { + return TabType.Member; + } + + return TabType.File; + } + + return TabType.Url; + } + + /// + /// Url's as internal links to Files, Tabs and Users should only be imported if + /// those files, tabs and users exist. This function parses the url, and checks + /// whether the internal links exist. + /// If the link does not exist, the function will return an empty string. + /// + /// The id of the module (unused). + /// the url to import. + /// If an internal link does not exist, an empty string is returned, otherwise the passed in url is returned as is. + [DnnDeprecated(9, 8, 1, "moduleId is not used in the method, use the overload that takes only the url")] + public static partial string ImportUrl(int moduleId, string url) + { + return ImportUrl(url); + } + + /// + /// Url's as internal links to Files, Tabs and Users should only be imported if + /// those files, tabs and users exist. This function parses the url, and checks + /// whether the internal links exist. + /// If the link does not exist, the function will return an empty string. + /// + /// The url to import. + /// If an internal link does not exist, an empty string is returned, otherwise the passed in url is returned as is. + public static string ImportUrl(string url) + { + string strUrl = url; + TabType urlType = GetURLType(url); + int intId = -1; + PortalSettings portalSettings = GetPortalSettings(); + switch (urlType) + { + case TabType.File: + if (int.TryParse(url.Replace("FileID=", string.Empty), out intId)) + { + var objFile = FileManager.Instance.GetFile(intId); + if (objFile == null) + { + // fileId does not exist in the portal + strUrl = string.Empty; + } + } + else + { + // failed to get fileId + strUrl = string.Empty; + } + + break; + case TabType.Member: + if (int.TryParse(url.Replace("UserID=", string.Empty), out intId)) + { + if (UserController.GetUserById(portalSettings.PortalId, intId) == null) + { + // UserId does not exist for this portal + strUrl = string.Empty; + } + } + else + { + // failed to get UserId + strUrl = string.Empty; + } + + break; + case TabType.Tab: + if (int.TryParse(url, out intId)) + { + if (TabController.Instance.GetTab(intId, portalSettings.PortalId, false) == null) + { + // the tab does not exist + strUrl = string.Empty; + } + } + else + { + // failed to get TabId + strUrl = string.Empty; + } + + break; + } + + return strUrl; + } + + /// Gets the login URL. + /// The URL to redirect to after logging in. + /// if set to , show the login control on the current page, even if there is a login page defined for the site. + /// Formatted URL. + public static string LoginURL(string returnUrl, bool overrideSetting) + { + return LoginURL(returnUrl, overrideSetting, PortalController.Instance.GetCurrentSettings()); + } + + /// Gets the login URL. + /// The URL to redirect to after logging in. + /// if set to , show the login control on the current page, even if there is a login page defined for the site. + /// The Portal Settings. + /// Formatted URL. + [DnnDeprecated(9, 8, 1, "Use the overload that takes IPortalSettings instead")] + public static partial string LoginURL(string returnUrl, bool overrideSetting, PortalSettings portalSettings) + { + return LoginURL(returnUrl, overrideSetting, (IPortalSettings)portalSettings); + } + + /// Gets the login URL. + /// The URL to redirect to after logging in. + /// if set to , show the login control on the current page, even if there is a login page defined for the site. + /// The Portal Settings. + /// Formatted URL. + public static string LoginURL(string returnUrl, bool overrideSetting, IPortalSettings portalSettings) + { + string loginUrl; + var currentTabId = TabController.CurrentPage.TabID; + + if (!string.IsNullOrEmpty(returnUrl)) + { + returnUrl = $"returnurl={returnUrl}"; + } + + var popUpParameter = string.Empty; + if (HttpUtility.UrlDecode(returnUrl).IndexOf("popUp=true", StringComparison.OrdinalIgnoreCase) >= 0) + { + popUpParameter = "popUp=true"; + } + + if (portalSettings.LoginTabId != -1 && !overrideSetting) + { + if (ValidateLoginTabID(portalSettings.LoginTabId)) + { + loginUrl = string.IsNullOrEmpty(returnUrl) + ? navigationManager.NavigateURL(portalSettings.LoginTabId, string.Empty, popUpParameter) + : navigationManager.NavigateURL(portalSettings.LoginTabId, string.Empty, returnUrl, popUpParameter); + } + else + { + string strMessage = + $"error={Localization.GetString("NoLoginControl", Localization.GlobalResourceFile)}"; + + // No account module so use portal tab + loginUrl = string.IsNullOrEmpty(returnUrl) + ? navigationManager.NavigateURL(currentTabId, "Login", strMessage, popUpParameter) + : navigationManager.NavigateURL(currentTabId, "Login", returnUrl, strMessage, popUpParameter); + } + } + else + { + // portal tab + loginUrl = string.IsNullOrEmpty(returnUrl) + ? navigationManager.NavigateURL(currentTabId, "Login", popUpParameter) + : navigationManager.NavigateURL(currentTabId, "Login", returnUrl, popUpParameter); + } + + return loginUrl; + } + + /// Gets User profile URL. + /// The user id. + /// Formatted url. + public static string UserProfileURL(int userId) + { + string strURL = string.Empty; + var portalSettings = PortalController.Instance.GetCurrentSettings(); + + strURL = navigationManager.NavigateURL(portalSettings.UserTabId, string.Empty, $"userId={userId}"); + + return strURL; + } + + /// Gets the URL to the current page. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL() + { + return navigationManager.NavigateURL(); + } + + /// Gets the URL to the given page. + /// The tab ID. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID) + { + return navigationManager.NavigateURL(tabID); + } + + /// Gets the URL to the given page. + /// The tab ID. + /// if set to the page is a "super-tab," i.e. a host-level page. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, bool isSuperTab) + { + return navigationManager.NavigateURL(tabID, isSuperTab); + } + + /// Gets the URL to show the control associated with the given control key. + /// The control key, or or null. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(string controlKey) + { + return navigationManager.NavigateURL(controlKey); + } + + /// Gets the URL to show the control associated with the given control key. + /// The control key, or or null. + /// Any additional parameters, in "key=value" format. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(string controlKey, params string[] additionalParameters) + { + return navigationManager.NavigateURL(controlKey, additionalParameters); + } + + /// Gets the URL to show the control associated with the given control key on the given page. + /// The tab ID. + /// The control key, or or null. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, string controlKey) + { + return navigationManager.NavigateURL(tabID, controlKey); + } + + /// Gets the URL to show the given page. + /// The tab ID. + /// The control key, or or null. + /// Any additional parameters. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, string controlKey, params string[] additionalParameters) + { + return navigationManager.NavigateURL(tabID, controlKey, additionalParameters); + } + + /// Gets the URL to show the given page. + /// The tab ID. + /// The portal settings. + /// The control key, or or null. + /// Any additional parameters. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, PortalSettings settings, string controlKey, params string[] additionalParameters) + { + return navigationManager.NavigateURL(tabID, settings, controlKey, additionalParameters); + } + + /// Gets the URL to show the given page. + /// The tab ID. + /// if set to the page is a "super-tab," i.e. a host-level page. + /// The portal settings. + /// The control key, or or null. + /// Any additional parameters. + /// Formatted URL. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, params string[] additionalParameters) + { + return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, additionalParameters); + } + + /// Gets the URL to show the given page. + /// The tab ID. + /// if set to the page is a "super-tab," i.e. a host-level page. + /// The portal settings. + /// The control key, or or null. + /// The language code. + /// Any additional parameters. + /// Formatted URL. + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, params string[] additionalParameters) + { + return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, additionalParameters); + } + + /// Gets the URL to show the given page. + /// The tab ID. + /// if set to the page is a "super-tab," i.e. a host-level page. + /// The portal settings. + /// The control key, or or null. + /// The language code. + /// The page name to pass to . + /// Any additional parameters. + /// Formatted url. + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, string pageName, params string[] additionalParameters) + { + return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, pageName, additionalParameters); + } + + /// UrlEncode query string. + /// The query string. + /// Encoded content. + public static string QueryStringEncode(string queryString) + { + queryString = HttpUtility.UrlEncode(queryString); + return queryString; + } + + /// UrlDecode query string. + /// The query string. + /// Decoded content. + public static string QueryStringDecode(string queryString) + { + queryString = HttpUtility.UrlDecode(queryString); + string fullPath; + try + { + fullPath = HttpContext.Current.Request.MapPath(queryString, HttpContext.Current.Request.ApplicationPath, false); + } + catch (HttpException exc) + { + Exceptions.ProcessHttpException(exc); + } + + string strDoubleDecodeUrl = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Server.UrlDecode(queryString)); + if (queryString.Contains("..", StringComparison.Ordinal) || strDoubleDecodeUrl.Contains("..", StringComparison.Ordinal)) + { + Exceptions.ProcessHttpException(); + } + + return queryString; + } + + /// Gets Register URL. + /// The return URL. + /// The original URL. + /// Formatted url. + public static string RegisterURL(string returnURL, string originalURL) + { + string strURL; + + var portalSettings = PortalController.Instance.GetCurrentSettings(); + string extraParams = string.Empty; + if (!string.IsNullOrEmpty(returnURL)) + { + extraParams = string.Concat("returnurl=", returnURL); + } + + if (!string.IsNullOrEmpty(originalURL)) + { + extraParams += string.Concat("&orignalurl=", originalURL); + } + + if (portalSettings.RegisterTabId != -1) + { + // user defined tab + strURL = navigationManager.NavigateURL(portalSettings.RegisterTabId, string.Empty, extraParams); + } + else + { + strURL = navigationManager.NavigateURL(TabController.CurrentPage.TabID, "Register", extraParams); + } + + return strURL; + } + + /// Generates the correctly formatted url. + /// The url to format. + /// The formatted (resolved) url. + public static string ResolveUrl(string url) + { + // String is Empty, just return Url + if (string.IsNullOrEmpty(url)) + { + return url; + } + + // String does not contain a ~, so just return Url + if (!url.StartsWith("~", StringComparison.Ordinal)) + { + return url; + } + + // There is just the ~ in the Url, return the appPath + if (url.Length == 1) + { + return ApplicationPath; + } + + if (url.ToCharArray()[1] == '/' || url.ToCharArray()[1] == '\\') + { + // Url looks like ~/ or ~\ + if (!string.IsNullOrEmpty(ApplicationPath) && ApplicationPath.Length > 1) + { + return ApplicationPath + "/" + url.Substring(2); + } + else + { + return "/" + url.Substring(2); + } + } + else + { + // Url look like ~something + if (!string.IsNullOrEmpty(ApplicationPath) && ApplicationPath.Length > 1) + { + return ApplicationPath + "/" + url.Substring(1); + } + else + { + return ApplicationPath + url.Substring(1); + } + } + } + + /// Encodes the reserved characters. + /// The query string. + /// Encoded content. + [DnnDeprecated(9, 8, 1, "Use System.Net.WebUtility.UrlEncode instead")] + public static partial string EncodeReservedCharacters(string queryString) + { + queryString = queryString.Replace("$", "%24"); + queryString = queryString.Replace("&", "%26"); + queryString = queryString.Replace("+", "%2B"); + queryString = queryString.Replace(",", "%2C"); + queryString = queryString.Replace("/", "%2F"); + queryString = queryString.Replace(":", "%3A"); + queryString = queryString.Replace(";", "%3B"); + queryString = queryString.Replace("=", "%3D"); + queryString = queryString.Replace("?", "%3F"); + queryString = queryString.Replace("@", "%40"); + return queryString; + } + + /// Dates to string. + /// The date value. + /// return value of input with SortableDateTimePattern. + [DnnDeprecated(9, 8, 1, @"Use DateTime.ToString(""s"") instead")] + public static partial string DateToString(DateTime dateValue) + { + try + { + if (!Null.IsNull(dateValue)) + { + return dateValue.ToString("s"); + } + else + { + return Null.NullString; + } + } + catch (Exception exc) + { + Logger.Error(exc); + + return Null.NullString; + } + } + + /// Gets the hash value. + /// The hash object. + /// The default value. + /// 's value or if is . + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial string GetHashValue(object hashObject, string defaultValue) + { + if (hashObject != null) + { + if (!string.IsNullOrEmpty(hashObject.ToString())) + { + return Convert.ToString(hashObject, CultureInfo.InvariantCulture); + } + else + { + return defaultValue; + } + } + else + { + return defaultValue; + } + } + + /// Gets Link click url. + /// The link. + /// The tab ID. + /// The module ID. + /// Formatted url. + public static string LinkClick(string link, int tabId, int moduleId) + { + return LinkClick(link, tabId, moduleId, true, string.Empty); + } + + /// Gets Link click url. + /// The link. + /// The tab ID. + /// The module ID. + /// if set to [track clicks]. + /// Formatted url. + public static string LinkClick(string link, int tabId, int moduleId, bool trackClicks) + { + return LinkClick(link, tabId, moduleId, trackClicks, string.Empty); + } + + /// Gets Link click url. + /// The link. + /// The tab ID. + /// The module ID. + /// if set to [track clicks]. + /// Type of the content. + /// Formatted url. + public static string LinkClick(string link, int tabId, int moduleId, bool trackClicks, string contentType) + { + return LinkClick(link, tabId, moduleId, trackClicks, !string.IsNullOrEmpty(contentType)); + } + + /// Gets Link click url. + /// The link. + /// The tab ID. + /// The module ID. + /// if set to [track clicks]. + /// if set to [force download]. + /// Formatted url. + public static string LinkClick(string link, int tabId, int moduleId, bool trackClicks, bool forceDownload) + { + var portalSettings = PortalController.Instance.GetCurrentSettings(); + return LinkClick(link, tabId, moduleId, trackClicks, forceDownload, portalSettings.PortalId, portalSettings.EnableUrlLanguage, portalSettings.GUID.ToString()); + } + + /// Gets Link click url. + /// The link. + /// The tab ID. + /// The module ID. + /// if set to [track clicks]. + /// if set to [force download]. + /// The portal id. + /// if set to [enable URL language]. + /// The portal GUID. + /// Formatted url. + public static string LinkClick( + string link, + int tabId, + int moduleId, + bool trackClicks, + bool forceDownload, + int portalId, + bool enableUrlLanguage, + string portalGuid) + { + string strLink = string.Empty; + TabType urlType = GetURLType(link); + if (urlType == TabType.Member) + { + strLink = UserProfileURL(Convert.ToInt32(UrlUtils.GetParameterValue(link), CultureInfo.InvariantCulture)); + } + else if (trackClicks || forceDownload || urlType == TabType.File) + { + // format LinkClick wrapper + if (link.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) + { + strLink = $"{ApplicationPath}/LinkClick.aspx?fileticket={UrlUtils.EncryptParameter(UrlUtils.GetParameterValue(link), portalGuid)}"; + if (portalId == Null.NullInteger) + { + // To track Host files + strLink += "&hf=1"; + } + } + + if (string.IsNullOrEmpty(strLink)) + { + strLink = $"{ApplicationPath}/LinkClick.aspx?link={HttpUtility.UrlEncode(link)}"; + } + + // tabid is required to identify the portal where the click originated + if (tabId != Null.NullInteger) + { + strLink += $"&tabid={tabId}"; + } + + // append portal id to query string to identity portal the click originated. + if (portalId != Null.NullInteger) + { + strLink += $"&portalid={portalId}"; + } + + // moduleid is used to identify the module where the url is stored + if (moduleId != -1) + { + strLink += $"&mid={moduleId}"; + } + + // only add language to url if more than one locale is enabled, and if admin did not turn it off + if (LocaleController.Instance.GetLocales(portalId).Count > 1 && enableUrlLanguage) + { + strLink += $"&language={Thread.CurrentThread.CurrentCulture.Name}"; + } + + // force a download dialog + if (forceDownload) + { + strLink += "&forcedownload=true"; + } + } + else + { + switch (urlType) + { + case TabType.Tab: + strLink = navigationManager.NavigateURL(int.Parse(link, CultureInfo.InvariantCulture)); + break; + default: + strLink = link; + break; + } + } + + return strLink; + } + + /// Gets the name of the role. + /// The role ID. + /// Role Name. + [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] + public static partial string GetRoleName(int roleId) + => GetRoleName(GetCurrentServiceProvider().GetRequiredService(), roleId); + + /// Gets the name of the role. + /// The host settings. + /// The role ID. + /// Role Name. + public static string GetRoleName(IHostSettings hostSettings, int roleId) + { + switch (Convert.ToString(roleId, CultureInfo.InvariantCulture)) + { + case glbRoleAllUsers: + return glbRoleAllUsersName; + case glbRoleUnauthUser: + return glbRoleUnauthUserName; + } + + Hashtable htRoles = null; + if (hostSettings.PerformanceSetting != DotNetNuke.Abstractions.Application.PerformanceSettings.NoCaching) + { + htRoles = (Hashtable)DataCache.GetCache("GetRoles"); + } + + if (htRoles == null) + { + var roles = RoleController.Instance.GetRoles(Null.NullInteger, r => r.SecurityMode != SecurityMode.SocialGroup); + htRoles = new Hashtable(); + int i; + for (i = 0; i <= roles.Count - 1; i++) + { + RoleInfo role = roles[i]; + htRoles.Add(role.RoleID, role.RoleName); + } + + if (hostSettings.PerformanceSetting != DotNetNuke.Abstractions.Application.PerformanceSettings.NoCaching) + { + DataCache.SetCache("GetRoles", htRoles); + } + } + + return Convert.ToString(htRoles[roleId], CultureInfo.InvariantCulture); + } + + /// Gets the content. + /// The content. + /// Type of the content. + /// specific node by content type of the whole document. + public static XmlNode GetContent(string content, string contentType) + { + var xmlDoc = new XmlDocument { XmlResolver = null }; + xmlDoc.LoadXml(content); + if (string.IsNullOrEmpty(contentType)) + { + return xmlDoc.DocumentElement; + } + else + { + return xmlDoc.SelectSingleNode(contentType); + } + } + + /// GenerateTabPath generates the TabPath used in Friendly URLS. + /// The Id of the Parent Tab. + /// The Name of the current Tab. + /// The TabPath. + public static string GenerateTabPath(int parentId, string tabName) + { + var strTabPath = Null.NullString; + + if (!Null.IsNull(parentId)) + { + var objTab = TabController.Instance.GetTab(parentId, Null.NullInteger, false); + while (objTab != null) + { + var strTabName = TabPathInvalidCharsRx.Replace(objTab.TabName, string.Empty); + strTabPath = "//" + strTabName + strTabPath; + objTab = Null.IsNull(objTab.ParentId) + ? null + : TabController.Instance.GetTab(objTab.ParentId, objTab.PortalID, false); + } + } + + strTabPath = strTabPath + "//" + TabPathInvalidCharsRx.Replace(tabName, string.Empty); + return strTabPath; + } + + /// Gets the help text. + /// The module control id. + /// help text. + public static string GetHelpText(int moduleControlId) + { + string helpText = Null.NullString; + ModuleControlInfo objModuleControl = ModuleControlController.GetModuleControl(moduleControlId); + if (objModuleControl != null) + { + string fileName = Path.GetFileName(objModuleControl.ControlSrc); + string localResourceFile = objModuleControl.ControlSrc.Replace(fileName, Localization.LocalResourceDirectory + "/" + fileName); + if (!string.IsNullOrEmpty(Localization.GetString(ModuleActionType.HelpText, localResourceFile))) + { + helpText = Localization.GetString(ModuleActionType.HelpText, localResourceFile); + } + } + + return helpText; + } + + /// Gets the online help url or the host configured help url if no url provided. + /// The help URL. + /// The module config. + /// The help url. + [DnnDeprecated(9, 8, 1, "ModuleInfo is unused, use the overload that does not take a ModuleInfo")] + public static partial string GetOnLineHelp(string helpUrl, ModuleInfo moduleConfig) + { + return GetOnLineHelp(helpUrl); + } + + /// Gets the online help url or the host configured help url if no url provided. + /// The help URL. + /// The help url. + [DnnDeprecated(10, 0, 2, "Use overload taking IHostSettings")] + public static partial string GetOnLineHelp(string helpUrl) + => GetOnLineHelp(GetCurrentServiceProvider().GetRequiredService(), helpUrl); + + /// Gets the online help url or the host configured help url if no url provided. + /// The host settings. + /// The help URL. + /// The help url. + public static string GetOnLineHelp(IHostSettings hostSettings, string helpUrl) + { + if (string.IsNullOrEmpty(helpUrl)) + { + helpUrl = hostSettings.HelpUrl; + } + + return helpUrl; + } + + /// Check whether the tab contains "Account Login" module. + /// The tab id. + /// if the tab contains "Account Login" module, otherwise, . + public static bool ValidateLoginTabID(int tabId) + { + return ValidateModuleInTab(tabId, "Account Login"); + } + + /// Check whether the tab contains specific module. + /// The tab id. + /// The module need to check. + /// if the tab contains the module, otherwise, . + public static bool ValidateModuleInTab(int tabId, string moduleName) + { + bool hasModule = Null.NullBoolean; + foreach (ModuleInfo objModule in ModuleController.Instance.GetTabModules(tabId).Values) + { + if (objModule.ModuleDefinition.FriendlyName == moduleName) + { + // We need to ensure that Anonymous Users or All Users have View permissions to the login page + TabInfo tab = TabController.Instance.GetTab(tabId, objModule.PortalID, false); + if (TabPermissionController.CanViewPage(tab)) + { + hasModule = true; + break; + } + } + } + + return hasModule; + } + + /// DeserializeHashTableBase64 deserializes a Hashtable using Binary Formatting. + /// + /// While this method of serializing is no longer supported (due to Medium Trust + /// issue, it is still required for upgrade purposes. + /// + /// The String Source to deserialize. + /// The deserialized Hashtable. + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial Hashtable DeserializeHashTableBase64(string source) + { + Hashtable objHashTable; + if (!string.IsNullOrEmpty(source)) + { + byte[] bits = Convert.FromBase64String(source); + using (var mem = new MemoryStream(bits)) + { + var bin = new BinaryFormatter(); + try + { + objHashTable = (Hashtable)bin.Deserialize(mem); + } + catch (Exception exc) + { + Logger.Error(exc); + + objHashTable = new Hashtable(); + } + + mem.Close(); + } + } + else + { + objHashTable = new Hashtable(); + } + + return objHashTable; + } + + /// DeserializeHashTableXml deserializes a Hashtable using Xml Serialization. + /// + /// This is the preferred method of serialization under Medium Trust. + /// + /// The String Source to deserialize. + /// The deserialized Hashtable. + [DnnDeprecated(9, 8, 1, "This API was not meant to be public and only deserializes xml with a root of 'profile'")] + public static partial Hashtable DeserializeHashTableXml(string source) + { + return XmlUtils.DeSerializeHashtable(source, "profile"); + } + + /// SerializeHashTableBase64 serializes a Hashtable using Binary Formatting. + /// + /// While this method of serializing is no longer supported (due to Medium Trust + /// issue, it is still required for upgrade purposes. + /// + /// The Hashtable to serialize. + /// The serialized String. + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial string SerializeHashTableBase64(Hashtable source) + { + string strString; + if (source.Count != 0) + { + var bin = new BinaryFormatter(); + var mem = new MemoryStream(); + try + { + bin.Serialize(mem, source); + strString = Convert.ToBase64String(mem.GetBuffer(), 0, Convert.ToInt32(mem.Length)); + } + catch (Exception exc) + { + Logger.Error(exc); + + strString = string.Empty; + } + finally + { + mem.Close(); + } + } + else + { + strString = string.Empty; + } + + return strString; + } + + /// SerializeHashTableXml serializes a Hashtable using Xml Serialization. + /// + /// This is the preferred method of serialization under Medium Trust. + /// + /// The Hashtable to serialize. + /// The serialized String. + [DnnDeprecated(9, 8, 1, "This method was never meant to be public and only works for 'profile' root namespace")] + public static partial string SerializeHashTableXml(Hashtable source) + { + return XmlUtils.SerializeDictionary(source, "profile"); + } + + /// Check whether the specific page is a host page. + /// The tab ID. + /// if the tab is a host page; otherwise, it is not a host page. + public static bool IsHostTab(int tabId) + { + bool isHostTab = false; + TabCollection hostTabs = TabController.Instance.GetTabsByPortal(Null.NullInteger); + + if (hostTabs != null) + { + isHostTab = hostTabs.Any(t => t.Value.TabID == tabId); + } + + return isHostTab; + } + + /// Return User Profile Picture Formatted Url. UserId, width and height can be passed to build a formatted Avatar Url. + /// Formatted url, e.g. http://www.mysite.com/DnnImageHandler.ashx?mode=profilepic&userid={0}&h={1}&w={2}. + /// + /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> + /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicFormattedUrl(), userInfo.UserID, 32, 32). + /// + [DnnDeprecated(7, 3, 0, "It causes issues in SSL-offloading scenarios - please use UserProfilePicRelativeUrl instead", RemovalVersion = 11)] + public static partial string UserProfilePicFormattedUrl() + { + var avatarUrl = PortalController.Instance.GetCurrentPortalSettings().DefaultPortalAlias; + if (string.IsNullOrEmpty(avatarUrl)) + { + avatarUrl = HttpContext.Current.Request.Url.Host; + } + + var protocol = UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request) ? "https" : "http"; + var port = !HttpContext.Current.Request.Url.IsDefaultPort && !avatarUrl.Contains(":") ? ":" + HttpContext.Current.Request.Url.Port : string.Empty; + avatarUrl = $"{protocol}://{avatarUrl}{port}"; + + avatarUrl += "/DnnImageHandler.ashx?mode=profilepic&userId={0}&h={1}&w={2}"; + + return avatarUrl; + } + + /// Return User Profile Picture relative Url. UserId, width and height can be passed to build a formatted relative Avatar Url. + /// Formatted url, e.g. /DnnImageHandler.ashx?userid={0}&h={1}&w={2} considering child portal. + /// + /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> + /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32). + /// + [DnnDeprecated(8, 0, 0, "Please use UserController.Instance.GetUserProfilePictureUrl", RemovalVersion = 11)] + public static partial string UserProfilePicRelativeUrl() + { + return UserProfilePicRelativeUrl(true); + } + + /// Return User Profile Picture relative Url. UserId, width and height can be passed to build a formatted relative Avatar Url. + /// Indicates if cdv (Cache Delayed Verification) has to be included in the returned URL. + /// Formatted url, e.g. /DnnImageHandler.ashx?userid={0}&h={1}&w={2} considering child portal. + /// + /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> + /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32). + /// + [DnnDeprecated(8, 0, 0, "Please use UserController.Instance.GetUserProfilePictureUrl", RemovalVersion = 11)] + public static partial string UserProfilePicRelativeUrl(bool includeCdv) + { + const string query = "/DnnImageHandler.ashx?mode=profilepic&userId={0}&h={1}&w={2}"; + var currentAlias = GetPortalSettings().PortalAlias.HTTPAlias; + var index = currentAlias.IndexOf('/'); + var childPortalAlias = index > 0 ? "/" + currentAlias.Substring(index + 1) : string.Empty; + + var cdv = string.Empty; + if (includeCdv) + { + cdv = "&cdv=" + DateTime.Now.Ticks; + } + + if (childPortalAlias.StartsWith(ApplicationPath, StringComparison.OrdinalIgnoreCase)) + { + return childPortalAlias + query + cdv; + } + + return ApplicationPath + childPortalAlias + query + cdv; + } + + /// Formats an email address as a cloaked html link. + /// The formatted email address. + /// A cloaked html link. + [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatEmail", RemovalVersion = 11)] + public static partial string FormatEmail(string email) + { + return HtmlUtils.FormatEmail(email); + } + + /// Formats a domain name including link. + /// The domain name to format. + /// The formatted domain name. + [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatWebsite", RemovalVersion = 11)] + public static partial string FormatWebsite(object website) + { + return HtmlUtils.FormatWebsite(website); + } + + /// Xml encodes an html string. + /// The html to encode. + /// The encoded html for usage in xml. + [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.XmlUtils.XMLEncode", RemovalVersion = 11)] + public static partial string XMLEncode(string html) + { + return XmlUtils.XMLEncode(html); + } + + /// Gets the database connection string. + /// The database connection string. + [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.Config.GetConnectionString", RemovalVersion = 11)] + public static partial string GetDBConnectionString() + { + return Config.GetConnectionString(); + } + + /// Gets a file list. + /// The current directory. + /// The extensions to filter for. + /// If true, adds 'None Specified' to the list. + /// A list of file names. + [DnnDeprecated(7, 0, 0, "No replacement", RemovalVersion = 11)] + public static partial ArrayList GetFileList( + DirectoryInfo currentDirectory, + [Optional, DefaultParameterValue("")] // ERROR: Optional parameters aren't supported in C# + string strExtensions, + [Optional, DefaultParameterValue(true)] // ERROR: Optional parameters aren't supported in C# + bool noneSpecified) + { + var arrFileList = new ArrayList(); + string strExtension = string.Empty; + + if (noneSpecified) + { + arrFileList.Add(new FileItem(string.Empty, "<" + Localization.GetString("None_Specified") + ">")); + } + + string file = null; + string[] files = Directory.GetFiles(currentDirectory.FullName); + foreach (string fileLoopVariable in files) + { + file = fileLoopVariable; + if (file.Contains(".", StringComparison.Ordinal)) + { + strExtension = file.Substring(file.LastIndexOf(".", StringComparison.Ordinal) + 1); + } + + string fileName = file.Substring(currentDirectory.FullName.Length); + if (strExtensions.Contains(strExtension, StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(strExtensions)) + { + arrFileList.Add(new FileItem(fileName, fileName)); + } + } + + return arrFileList; + } + + /// Gets the subfolder path for a give filename path. + /// The filename full path. + /// The subfolder name. + [DnnDeprecated(7, 0, 0, "Replaced by GetSubFolderPath(string strFileNamePath, int portalId)", RemovalVersion = 11)] + public static partial string GetSubFolderPath(string strFileNamePath) + { + // Obtain PortalSettings from Current Context + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + string parentFolderName = null; + if (IsHostTab(portalSettings.ActiveTab.TabID)) + { + parentFolderName = HostMapPath.Replace("/", @"\"); + } + else + { + parentFolderName = portalSettings.HomeDirectoryMapPath.Replace("/", @"\"); + } + + string strFolderpath = strFileNamePath.Substring(0, strFileNamePath.LastIndexOf(@"\", StringComparison.Ordinal) + 1); + + return strFolderpath.Substring(parentFolderName.Length).Replace(@"\", "/"); + } + + /// Gets a LinkClick url for tracking purposes. + /// The actual link the LinkClick handler should point to. + /// The formatted LinkClick url. + [DnnDeprecated(7, 0, 0, "Use Common.Globals.LinkClick() for proper handling of URLs", RemovalVersion = 11)] + public static partial string LinkClickURL(string link) + { + PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return LinkClick(link, portalSettings.ActiveTab.TabID, -1, false); + } + + /// Helps prevent sql injection in certain scenarios. + /// IMPORTANT: It is highly recommended to use other forms of sql injection protection such as using SqlParameters or ORMs. + /// The string to filter. + /// The filtered string. + [DnnDeprecated(7, 0, 0, "Use Security Filter functions in the PortalSecurity class", RemovalVersion = 11)] + public static partial string PreventSQLInjection(string strSQL) + { + return PortalSecurity.Instance.InputFilter(strSQL, PortalSecurity.FilterFlag.NoSQL); + } + + /// Looks at various file artifacts to determine if DotNetNuke has already been installed. + /// true if installed else false. + /// + /// If DotNetNuke has been installed, then we should treat database connection errors as real errors. + /// If DotNetNuke has not been installed, then we should expect to have database connection problems + /// since the connection string may not have been configured yet, which can occur during the installation + /// wizard. + /// + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + internal static partial bool IsInstalled() => applicationStatusInfo.IsInstalled(); + + /// Gets the culture code of the tab. + /// The tab ID. + /// if set to [is super tab]. + /// The settings. + /// return the tab's culture code, if ths tab doesn't exist, it will return current culture name. + internal static string GetCultureCode(int tabId, bool isSuperTab, IPortalSettings settings) + { + string cultureCode = Null.NullString; + if (settings != null) + { + TabInfo linkTab = TabController.Instance.GetTab(tabId, isSuperTab ? Null.NullInteger : settings.PortalId, false); + if (linkTab != null) + { + cultureCode = linkTab.CultureCode; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + cultureCode = Thread.CurrentThread.CurrentCulture.Name; + } + } + + return cultureCode; + } + + /// Resets the application started timer. + internal static void ResetAppStartElapseTime() + { + AppStopwatch.Restart(); + } + + /// Gets an that should be disposed, trying to find the current request scope if possible. + /// An instance that should be disposed (but which can be disposed without prematurely disposing the current request scope). + internal static IServiceScope GetOrCreateServiceScope() + { + return new MaybeDisposableServiceScope( + HttpContextSource.Current?.GetScope(), + DependencyProvider.CreateScope); + } + + /// Gets an for the current request, or the global provider if not available. + /// An instance. + internal static IServiceProvider GetCurrentServiceProvider() + { + return HttpContextSource.Current?.GetScope()?.ServiceProvider ?? DependencyProvider; + } + + /// Check whether the Filename matches extensions. + /// The filename. + /// The valid extensions. + /// if the Filename matches extensions, otherwise, . + private static bool FilenameMatchesExtensions(string filename, string strExtensions) + { + bool result = string.IsNullOrEmpty(strExtensions); + if (!result) + { + foreach (string extension in strExtensions.Split(',')) + { + string ext = extension.Trim(); + if (!ext.StartsWith(".", StringComparison.Ordinal)) + { + ext = "." + extension; + } + + result = filename.EndsWith(ext, StringComparison.OrdinalIgnoreCase); + if (result) + { + break; + } + } + } + + return result; + } + + /// + /// Resolves dependencies after the + /// has been initialized. This should only be called once to resolve all + /// dependencies used by the object. + /// + private static void OnDependencyProviderChanged(object sender, PropertyChangedEventArgs eventArguments) + { + applicationStatusInfo = DependencyProvider?.GetRequiredService(); + navigationManager = DependencyProvider?.GetRequiredService(); + } + + private class MaybeDisposableServiceScope : IServiceScope + { + private readonly bool disposeServiceScope; + private readonly IServiceScope serviceScope; + + public MaybeDisposableServiceScope(IServiceScope doNotDisposeServiceScope, Func createDisposableServiceScope) + { + this.disposeServiceScope = doNotDisposeServiceScope is null; + this.serviceScope = doNotDisposeServiceScope ?? createDisposableServiceScope(); + } + + public IServiceProvider ServiceProvider => this.serviceScope.ServiceProvider; + + public void Dispose() + { + if (this.disposeServiceScope) + { + this.serviceScope.Dispose(); + } + } + } + } +} diff --git a/DNN Platform/Library/Common/Guard.cs b/DNN Platform/Library/Common/Guard.cs index fd6b54bf7c5..b3a038a86e2 100644 --- a/DNN Platform/Library/Common/Guard.cs +++ b/DNN Platform/Library/Common/Guard.cs @@ -22,7 +22,7 @@ public static class Guard /// When is . public static void Against(bool condition, string message, params object[] args) { - Against(condition, string.Format(CultureInfo.CurrentUICulture, message, args)); + Against(condition, string.Format(CultureInfo.CurrentCulture, message, args)); } /// diff --git a/DNN Platform/Library/Common/Initialize.cs b/DNN Platform/Library/Common/Initialize.cs index 832dd7e0483..56d8714f3c7 100644 --- a/DNN Platform/Library/Common/Initialize.cs +++ b/DNN Platform/Library/Common/Initialize.cs @@ -152,7 +152,7 @@ public static void LogEnd() null, CultureInfo.InvariantCulture) is not HttpRuntime runtime) { - Logger.InfoFormat("Application shutting down. Reason: {0}", shutdownDetail); + Logger.InfoFormat(CultureInfo.InvariantCulture, "Application shutting down. Reason: {0}", shutdownDetail); } else { @@ -197,23 +197,22 @@ public static void LogEnd() /// A value indicating whether the request should be processed in an HttpModule. public static bool ProcessHttpModule(HttpRequest request, bool allowUnknownExtensions, bool checkOmitFromRewriteProcessing) { - var toLowerLocalPath = request.Url.LocalPath.ToLowerInvariant(); - - if (toLowerLocalPath.EndsWith("webresource.axd") - || toLowerLocalPath.EndsWith("scriptresource.axd") - || toLowerLocalPath.EndsWith("captcha.aspx") - || toLowerLocalPath.Contains("upgradewizard.aspx") - || toLowerLocalPath.Contains("installwizard.aspx") - || toLowerLocalPath.EndsWith("install.aspx")) + var localPath = request.Url.LocalPath; + if (localPath.EndsWith("webresource.axd", StringComparison.OrdinalIgnoreCase) + || localPath.EndsWith("scriptresource.axd", StringComparison.OrdinalIgnoreCase) + || localPath.EndsWith("captcha.aspx", StringComparison.OrdinalIgnoreCase) + || localPath.Contains("upgradewizard.aspx", StringComparison.OrdinalIgnoreCase) + || localPath.Contains("installwizard.aspx", StringComparison.OrdinalIgnoreCase) + || localPath.EndsWith("install.aspx", StringComparison.OrdinalIgnoreCase)) { return false; } - if (allowUnknownExtensions == false - && toLowerLocalPath.EndsWith(".aspx") == false - && toLowerLocalPath.EndsWith(".asmx") == false - && toLowerLocalPath.EndsWith(".ashx") == false - && toLowerLocalPath.EndsWith(".svc") == false) + if (!allowUnknownExtensions + && !localPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase) + && !localPath.EndsWith(".asmx", StringComparison.OrdinalIgnoreCase) + && !localPath.EndsWith(".ashx", StringComparison.OrdinalIgnoreCase) + && !localPath.EndsWith(".svc", StringComparison.OrdinalIgnoreCase)) { return false; } @@ -493,11 +492,11 @@ private static string InitializeApp(HttpApplication app, ref bool initialized) private static bool IsUpgradeOrInstallRequest(HttpRequest request) { - var url = request.Url.LocalPath.ToLowerInvariant(); + var url = request.Url.LocalPath; - return url.EndsWith("/install.aspx") - || url.Contains("/upgradewizard.aspx") - || url.Contains("/installwizard.aspx"); + return url.EndsWith("/install.aspx", StringComparison.OrdinalIgnoreCase) + || url.Contains("/upgradewizard.aspx", StringComparison.OrdinalIgnoreCase) + || url.Contains("/installwizard.aspx", StringComparison.OrdinalIgnoreCase); } } } diff --git a/DNN Platform/Library/Common/Internal/GlobalsImpl.cs b/DNN Platform/Library/Common/Internal/GlobalsImpl.cs index b622d889885..9a410ac6174 100644 --- a/DNN Platform/Library/Common/Internal/GlobalsImpl.cs +++ b/DNN Platform/Library/Common/Internal/GlobalsImpl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Common.Internal { using System; + using System.Diagnostics.CodeAnalysis; using System.Text; using System.Web; @@ -16,6 +17,7 @@ namespace DotNetNuke.Common.Internal using Microsoft.Extensions.DependencyInjection; /// A collection of Dnn global methods and properties. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public class GlobalsImpl : IGlobals { /// Initializes a new instance of the class. @@ -40,6 +42,7 @@ public string HostMapPath protected INavigationManager NavigationManager { get; } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string GetSubFolderPath(string strFileNamePath, int portalId) { return Globals.GetSubFolderPath(strFileNamePath, portalId); @@ -52,6 +55,7 @@ public string LinkClick(string link, int tabId, int moduleId) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string LinkClick(string link, int tabID, int moduleID, bool trackClicks, bool forceDownload, int portalId, bool enableUrlLanguage, string portalGuid) { return Globals.LinkClick(link, tabID, moduleID, trackClicks, forceDownload, portalId, enableUrlLanguage, portalGuid); diff --git a/DNN Platform/Library/Common/Internal/IGlobals.cs b/DNN Platform/Library/Common/Internal/IGlobals.cs index 0e527337563..9d6c039a634 100644 --- a/DNN Platform/Library/Common/Internal/IGlobals.cs +++ b/DNN Platform/Library/Common/Internal/IGlobals.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Common.Internal { using System; + using System.Diagnostics.CodeAnalysis; using System.Web; using DotNetNuke.Entities.Portals; @@ -114,6 +115,7 @@ string LinkClick( /// The URL to redirect to after logging in. /// if set to , show the login control on the current page, even if there is a login page defined for the site. /// Formatted URL. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] string LoginURL(string returnURL, bool @override); /// Gets the URL to the current page. diff --git a/DNN Platform/Library/Common/Lists/CachedCountryList.cs b/DNN Platform/Library/Common/Lists/CachedCountryList.cs index b9b18dcaf3e..d0c7b5581a1 100644 --- a/DNN Platform/Library/Common/Lists/CachedCountryList.cs +++ b/DNN Platform/Library/Common/Lists/CachedCountryList.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Common.Lists { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Common.Utilities; @@ -26,7 +27,7 @@ public CachedCountryList(string locale) { Id = li.EntryID, Code = li.Value, - FullName = string.Format("{0} ({1})", text, li.Value), + FullName = $"{text} ({li.Value})", Name = text, }; c.NormalizedFullName = c.FullName.NormalizeString(); @@ -63,7 +64,7 @@ public static CachedCountryList GetCountryList(string locale) /// The cache key string. public static string CacheKey(string locale) { - return string.Format("CountryList:{0}", locale); + return $"CountryList:{locale}"; } /// Represents a country. @@ -71,21 +72,26 @@ public static string CacheKey(string locale) public struct Country { /// The country id. + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public int Id; /// The country name. /// United States. + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string Name; /// The country code. /// US. + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string Code; /// The country name and code. /// United States (US). + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string FullName; /// The country name and code with diacritics (accents) removed. + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string NormalizedFullName; } } diff --git a/DNN Platform/Library/Common/Lists/ListController.cs b/DNN Platform/Library/Common/Lists/ListController.cs index 9d9ced1e2d6..1fc970ce61c 100644 --- a/DNN Platform/Library/Common/Lists/ListController.cs +++ b/DNN Platform/Library/Common/Lists/ListController.cs @@ -9,6 +9,7 @@ namespace DotNetNuke.Common.Lists using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Threading; @@ -28,13 +29,11 @@ public partial class ListController { /// The list of list types that are not localized. [Obsolete("Deprecated in DotNetNuke 9.8.1. Use UnLocalizedLists instead. Scheduled removal in v11.0.0.")] - [System.Diagnostics.CodeAnalysis.SuppressMessage( - "StyleCop.CSharp.MaintainabilityRules", - "SA1401:Fields should be private", - Justification = "Make private in v11.")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Make private in v11.")] public readonly string[] NonLocalizedLists = UnLocalizableLists; - private static readonly string[] UnLocalizableLists = { "ContentTypes", "Processor", "DataType", "ProfanityFilter", "BannedPasswords" }; + private static readonly string[] UnLocalizableLists = ["ContentTypes", "Processor", "DataType", "ProfanityFilter", "BannedPasswords",]; private readonly IEventLogger eventLogger; /// Initializes a new instance of the class. @@ -152,7 +151,7 @@ public void DeleteList(string listName, string parentKey, int portalId) /// Deletes a list. /// The reference for the list to delete. - /// A value indicating wheter to also delete the children items for this list. + /// A value indicating whether to also delete the children items for this list. public void DeleteList(ListInfo list, bool includeChildren) { if (list == null) @@ -160,15 +159,14 @@ public void DeleteList(ListInfo list, bool includeChildren) return; } - var lists = new SortedList(); - lists.Add(list.Key, list); + var lists = new SortedList { { list.Key, list }, }; // add Children if (includeChildren) { foreach (KeyValuePair listPair in GetListInfoDictionary(list.PortalID)) { - if (listPair.Value.ParentList.StartsWith(list.Key)) + if (listPair.Value.ParentList.StartsWith(list.Key, StringComparison.OrdinalIgnoreCase)) { lists.Add(listPair.Value.Key.Replace(":", "."), listPair.Value); } @@ -456,7 +454,7 @@ private static void ClearListCache(int portalId) private static void ClearEntriesCache(string listName, int portalId) { - string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.ListEntriesCacheKey, portalId, listName); DataCache.RemoveCache(cacheKey); } @@ -477,18 +475,18 @@ private static ListInfo FillListInfo(IDataReader dr, bool checkForOpenDataReader if (canContinue) { - list = new ListInfo(Convert.ToString(dr["ListName"])); + list = new ListInfo(Convert.ToString(dr["ListName"], CultureInfo.InvariantCulture)); { - list.Level = Convert.ToInt32(dr["Level"]); - list.PortalID = Convert.ToInt32(dr["PortalID"]); - list.DefinitionID = Convert.ToInt32(dr["DefinitionID"]); - list.EntryCount = Convert.ToInt32(dr["EntryCount"]); - list.ParentID = Convert.ToInt32(dr["ParentID"]); - list.ParentKey = Convert.ToString(dr["ParentKey"]); - list.Parent = Convert.ToString(dr["Parent"]); - list.ParentList = Convert.ToString(dr["ParentList"]); - list.EnableSortOrder = Convert.ToInt32(dr["MaxSortOrder"]) > 0; - list.SystemList = Convert.ToInt32(dr["SystemList"]) > 0; + list.Level = Convert.ToInt32(dr["Level"], CultureInfo.InvariantCulture); + list.PortalID = Convert.ToInt32(dr["PortalID"], CultureInfo.InvariantCulture); + list.DefinitionID = Convert.ToInt32(dr["DefinitionID"], CultureInfo.InvariantCulture); + list.EntryCount = Convert.ToInt32(dr["EntryCount"], CultureInfo.InvariantCulture); + list.ParentID = Convert.ToInt32(dr["ParentID"], CultureInfo.InvariantCulture); + list.ParentKey = Convert.ToString(dr["ParentKey"], CultureInfo.InvariantCulture); + list.Parent = Convert.ToString(dr["Parent"], CultureInfo.InvariantCulture); + list.ParentList = Convert.ToString(dr["ParentList"], CultureInfo.InvariantCulture); + list.EnableSortOrder = Convert.ToInt32(dr["MaxSortOrder"], CultureInfo.InvariantCulture) > 0; + list.SystemList = Convert.ToInt32(dr["SystemList"], CultureInfo.InvariantCulture) > 0; } } @@ -525,7 +523,7 @@ private static Dictionary FillListInfoDictionary(IDataReader d private static Dictionary GetListInfoDictionary(int portalId) { - string cacheKey = string.Format(DataCache.ListsCacheKey, portalId); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.ListsCacheKey, portalId); return CBO.GetCachedObject>( new CacheItemArgs( cacheKey, @@ -536,7 +534,7 @@ private static Dictionary GetListInfoDictionary(int portalId) private static IEnumerable GetListEntries(string listName, int portalId) { - string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.ListEntriesCacheKey, portalId, listName); return CBO.GetCachedObject>( new CacheItemArgs( cacheKey, diff --git a/DNN Platform/Library/Common/Lists/ListInfoCollection.cs b/DNN Platform/Library/Common/Lists/ListInfoCollection.cs index 79e53dd104f..1a9ecb30a08 100644 --- a/DNN Platform/Library/Common/Lists/ListInfoCollection.cs +++ b/DNN Platform/Library/Common/Lists/ListInfoCollection.cs @@ -5,15 +5,17 @@ namespace DotNetNuke.Common.Lists { using System; using System.Collections; + using System.Collections.Generic; + using DotNetNuke.Collections; using DotNetNuke.Instrumentation; /// Represents a collection of . [Serializable] - public class ListInfoCollection : CollectionBase + public class ListInfoCollection : GenericCollectionBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ListInfoCollection)); - private readonly Hashtable mKeyIndexLookup = new Hashtable(); + private readonly Dictionary mKeyIndexLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); /// Gets the children from a parent name. /// The name of the parent. @@ -28,13 +30,10 @@ public ListInfo GetChildren(string parentName) /// The value of the object. public void Add(string key, object value) { - int index; - - // try { - index = this.List.Add(value); - this.mKeyIndexLookup.Add(key.ToLowerInvariant(), index); + var index = this.List.Add(value); + this.mKeyIndexLookup.Add(key, index); } catch (Exception exc) { @@ -49,9 +48,7 @@ public object Item(int index) { try { - object obj; - obj = this.List[index]; - return obj; + return this.List[index]; } catch (Exception exc) { @@ -60,31 +57,26 @@ public object Item(int index) } } - /// Gets a list from a spedific key. + /// Gets a list from a specific key. /// The key to fetch the list. /// A single list. public object Item(string key) { - int index; - object obj; - // Do validation first try { - if (this.mKeyIndexLookup[key.ToLowerInvariant()] == null) + if (!this.mKeyIndexLookup.TryGetValue(key, out var index)) { return null; } + + return this.List[index]; } catch (Exception exc) { Logger.Error(exc); return null; } - - index = Convert.ToInt32(this.mKeyIndexLookup[key.ToLowerInvariant()]); - obj = this.List[index]; - return obj; } /// Gets a single list. @@ -93,14 +85,14 @@ public object Item(string key) /// A list object. public object Item(string key, bool cache) { - int index; + int index = 0; object obj = null; bool itemExists = false; // Do validation first try { - if (this.mKeyIndexLookup[key.ToLowerInvariant()] != null) + if (this.mKeyIndexLookup.TryGetValue(key, out index)) { itemExists = true; } @@ -114,9 +106,9 @@ public object Item(string key, bool cache) if (!itemExists) { var ctlLists = new ListController(); - string listName = key.Substring(key.IndexOf(":") + 1); - string parentKey = key.Replace(listName, string.Empty).TrimEnd(':'); - ListInfo listInfo = ctlLists.GetListInfo(listName, parentKey); + var listName = key.Substring(key.IndexOf(":", StringComparison.Ordinal) + 1); + var parentKey = key.Replace(listName, string.Empty).TrimEnd(':'); + var listInfo = ctlLists.GetListInfo(listName, parentKey); // the collection has been cache, so add this entry list into it if specified if (cache) @@ -127,7 +119,6 @@ public object Item(string key, bool cache) } else { - index = Convert.ToInt32(this.mKeyIndexLookup[key.ToLowerInvariant()]); obj = this.List[index]; } diff --git a/DNN Platform/Library/Common/Utilities/CBO.cs b/DNN Platform/Library/Common/Utilities/CBO.cs index ee22a4a98e3..063dcc930d7 100644 --- a/DNN Platform/Library/Common/Utilities/CBO.cs +++ b/DNN Platform/Library/Common/Utilities/CBO.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Common.Utilities using System.Collections; using System.Collections.Generic; using System.Data; + using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -680,26 +681,26 @@ private static IDictionary FillDictionaryFromReader( { // Create the Object objObject = (TValue)CreateObjectFromReader(typeof(TValue), dr, false); - if (keyField == "KeyID" && objObject is IHydratable) + if (keyField == "KeyID" && objObject is IHydratable hydratable) { // Get the value of the key field from the KeyID - keyValue = (TKey)Null.SetNull(((IHydratable)objObject).KeyID, keyValue); + keyValue = (TKey)Null.SetNull(hydratable.KeyID, keyValue); } else { // Get the value of the key field from the DataReader if (typeof(TKey).Name == "Int32" && dr[keyField].GetType().Name == "Decimal") { - keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], keyValue), typeof(TKey)); + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], keyValue), typeof(TKey), CultureInfo.InvariantCulture); } else if (typeof(TKey).Name.Equals("string", StringComparison.OrdinalIgnoreCase) && dr[keyField].GetType().Name.Equals("dbnull", StringComparison.OrdinalIgnoreCase)) { - keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey)); + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey), CultureInfo.InvariantCulture); } else { - keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey)); + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey), CultureInfo.InvariantCulture); } } @@ -829,16 +830,16 @@ private static void HydrateObject(object hydratedObject, IDataReader dr) { PropertyInfo objPropertyInfo = null; Type propType = null; - object coloumnValue; + object columnValue; Type objDataType; int intIndex; // get cached object mapping for type ObjectMappingInfo objMappingInfo = GetObjectMapping(hydratedObject.GetType()); - if (hydratedObject is BaseEntityInfo && !(hydratedObject is ScheduleItem)) + if (hydratedObject is BaseEntityInfo info and not ScheduleItem) { // Call the base classes fill method to populate base class properties - ((BaseEntityInfo)hydratedObject).FillBaseProperties(dr); + info.FillBaseProperties(dr); } // fill object with values from datareader @@ -854,19 +855,19 @@ private static void HydrateObject(object hydratedObject, IDataReader dr) if (objPropertyInfo.CanWrite) { // Get the Data Value from the data reader - coloumnValue = dr.GetValue(intIndex); + columnValue = dr.GetValue(intIndex); // Get the Data Value's type - objDataType = coloumnValue.GetType(); - if (coloumnValue == null || coloumnValue == DBNull.Value) + objDataType = columnValue.GetType(); + if (columnValue == DBNull.Value) { // set property value to Null objPropertyInfo.SetValue(hydratedObject, Null.SetNull(objPropertyInfo), null); } - else if (propType.Equals(objDataType)) + else if (propType == objDataType) { // Property and data objects are the same type - objPropertyInfo.SetValue(hydratedObject, coloumnValue, null); + objPropertyInfo.SetValue(hydratedObject, columnValue, null); } else { @@ -875,38 +876,38 @@ private static void HydrateObject(object hydratedObject, IDataReader dr) if (propType.BaseType.Equals(typeof(Enum))) { // check if value is numeric and if not convert to integer ( supports databases like Oracle ) - if (Globals.NumberMatchRegex.IsMatch(coloumnValue.ToString())) + if (Globals.NumberMatchRegex.IsMatch(columnValue.ToString())) { objPropertyInfo.SetValue( hydratedObject, - Enum.ToObject(propType, Convert.ToInt32(coloumnValue)), + Enum.ToObject(propType, Convert.ToInt32(columnValue, CultureInfo.InvariantCulture)), null); } else { - objPropertyInfo.SetValue(hydratedObject, Enum.ToObject(propType, coloumnValue), null); + objPropertyInfo.SetValue(hydratedObject, Enum.ToObject(propType, columnValue), null); } } else if (propType == typeof(Guid)) { - // guid is not a datatype common across all databases ( ie. Oracle ) + // guid is not a datatype common across all databases (e.g. Oracle) objPropertyInfo.SetValue( hydratedObject, - Convert.ChangeType(new Guid(coloumnValue.ToString()), propType), + Convert.ChangeType(new Guid(columnValue.ToString()), propType, CultureInfo.InvariantCulture), null); } else if (propType == typeof(Version)) { - objPropertyInfo.SetValue(hydratedObject, new Version(coloumnValue.ToString()), null); + objPropertyInfo.SetValue(hydratedObject, new Version(columnValue.ToString()), null); } - else if (coloumnValue is IConvertible) + else if (columnValue is IConvertible) { - objPropertyInfo.SetValue(hydratedObject, ChangeType(coloumnValue, propType), null); + objPropertyInfo.SetValue(hydratedObject, ChangeType(columnValue, propType, CultureInfo.InvariantCulture), null); } else { // try explicit conversion - objPropertyInfo.SetValue(hydratedObject, coloumnValue, null); + objPropertyInfo.SetValue(hydratedObject, columnValue, null); } } } @@ -914,7 +915,7 @@ private static void HydrateObject(object hydratedObject, IDataReader dr) } } - private static object ChangeType(object obj, Type type) + private static object ChangeType(object obj, Type type, IFormatProvider formatProvider) { Type u = Nullable.GetUnderlyingType(type); @@ -925,10 +926,10 @@ private static object ChangeType(object obj, Type type) return GetDefault(type); } - return Convert.ChangeType(obj, u); + return Convert.ChangeType(obj, u, formatProvider); } - return Convert.ChangeType(obj, type); + return Convert.ChangeType(obj, type, formatProvider); } private static object GetDefault(Type type) @@ -978,8 +979,7 @@ private static ObjectMappingInfo GetObjectMapping(Type objType) private static string GetPrimaryKey(Type objType) { - string primaryKey = DefaultPrimaryKey; - return primaryKey; + return DefaultPrimaryKey; } private static string GetTableName(Type objType) @@ -990,7 +990,7 @@ private static string GetTableName(Type objType) if (string.IsNullOrEmpty(tableName)) { tableName = objType.Name; - if (tableName.EndsWith("Info")) + if (tableName.EndsWith("Info", StringComparison.Ordinal)) { // Remove Info ending tableName = tableName.Replace("Info", string.Empty); diff --git a/DNN Platform/Library/Common/Utilities/Calendar.cs b/DNN Platform/Library/Common/Utilities/Calendar.cs index 2d7f95bc7e0..5eb89dc3ea8 100644 --- a/DNN Platform/Library/Common/Utilities/Calendar.cs +++ b/DNN Platform/Library/Common/Utilities/Calendar.cs @@ -27,7 +27,7 @@ public static string InvokePopupCal(TextBox field) var monthBuilder = new StringBuilder(); foreach (string month in DateTimeFormatInfo.CurrentInfo.MonthNames) { - monthBuilder.AppendFormat("{0},", month); + monthBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0},", month); } var monthNameString = monthBuilder.ToString().TrimEnd(trimChars); @@ -37,7 +37,7 @@ public static string InvokePopupCal(TextBox field) var dayBuilder = new StringBuilder(); foreach (string day in DateTimeFormatInfo.CurrentInfo.AbbreviatedDayNames) { - dayBuilder.AppendFormat("{0},", day); + dayBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0},", day); } var dayNameString = dayBuilder.ToString().TrimEnd(trimChars); @@ -54,6 +54,7 @@ public static string InvokePopupCal(TextBox field) string strCalendar = ClientAPI.GetSafeJSString(Localization.GetString("Calendar")); return string.Format( + CultureInfo.InvariantCulture, "javascript:popupCal('Cal','{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7});", HttpUtility.JavaScriptStringEncode(field.ClientID), HttpUtility.JavaScriptStringEncode(formatString), diff --git a/DNN Platform/Library/Common/Utilities/Config.cs b/DNN Platform/Library/Common/Utilities/Config.cs index c3f207edefe..c8eb579e246 100644 --- a/DNN Platform/Library/Common/Utilities/Config.cs +++ b/DNN Platform/Library/Common/Utilities/Config.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Common.Utilities { using System; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Threading; @@ -60,6 +61,7 @@ public enum FcnMode NotSet = 2, /// The application creates one object to monitor the main directory and uses this object to monitor each subdirectory. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] Single, } @@ -351,8 +353,8 @@ public static void SetMaxUploadSize(IApplicationStatusInfo appStatus, long newSi configNav.SelectSingleNode("configuration//location//system.web//httpRuntime"); if (httpNode != null) { - httpNode.Attributes["maxRequestLength"].InnerText = (newSize / 1024).ToString("#"); - httpNode.Attributes["requestLengthDiskThreshold"].InnerText = (newSize / 1024).ToString("#"); + httpNode.Attributes["maxRequestLength"].InnerText = (newSize / 1024).ToString("#", CultureInfo.InvariantCulture); + httpNode.Attributes["requestLengthDiskThreshold"].InnerText = (newSize / 1024).ToString("#", CultureInfo.InvariantCulture); } httpNode = configNav.SelectSingleNode("configuration//system.webServer//security//requestFiltering//requestLimits") ?? @@ -364,7 +366,7 @@ public static void SetMaxUploadSize(IApplicationStatusInfo appStatus, long newSi httpNode.Attributes.Append(configNav.CreateAttribute("maxAllowedContentLength")); } - httpNode.Attributes["maxAllowedContentLength"].InnerText = newSize.ToString("#"); + httpNode.Attributes["maxAllowedContentLength"].InnerText = newSize.ToString("#", CultureInfo.InvariantCulture); } Save(appStatus, configNav); @@ -382,7 +384,7 @@ public static string GetUpgradeConnectionString() public static string GetDataBaseOwner() { var databaseOwner = GetDefaultProvider("data").Attributes["databaseOwner"]; - if (!string.IsNullOrEmpty(databaseOwner) && databaseOwner.EndsWith(".") == false) + if (!string.IsNullOrEmpty(databaseOwner) && !databaseOwner.EndsWith(".", StringComparison.Ordinal)) { databaseOwner += "."; } @@ -444,7 +446,7 @@ public static string GetObjectQualifer() { var provider = GetDefaultProvider("data"); var objectQualifier = provider.Attributes["objectQualifier"]; - if (!string.IsNullOrEmpty(objectQualifier) && objectQualifier.EndsWith("_") == false) + if (!string.IsNullOrEmpty(objectQualifier) && !objectQualifier.EndsWith("_", StringComparison.Ordinal)) { objectQualifier += "_"; } @@ -499,7 +501,7 @@ public static int GetPersistentCookieTimeout(IApplicationStatusInfo appStatus) var persistentCookieTimeout = 0; if (!string.IsNullOrEmpty(GetSetting("PersistentCookieTimeout"))) { - persistentCookieTimeout = int.Parse(GetSetting("PersistentCookieTimeout")); + persistentCookieTimeout = int.Parse(GetSetting("PersistentCookieTimeout"), CultureInfo.InvariantCulture); } return persistentCookieTimeout == 0 ? GetAuthCookieTimeout(appStatus) : persistentCookieTimeout; diff --git a/DNN Platform/Library/Common/Utilities/CryptographyUtils.cs b/DNN Platform/Library/Common/Utilities/CryptographyUtils.cs index 4e16068ac52..71ec83b5e86 100644 --- a/DNN Platform/Library/Common/Utilities/CryptographyUtils.cs +++ b/DNN Platform/Library/Common/Utilities/CryptographyUtils.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Common.Utilities { using System; + using System.Globalization; using System.Security.Cryptography; using System.Text; @@ -95,11 +96,11 @@ public static string GenerateHash(this string str, HashAlgorithm hasher) // create a StringBuilder object var stringBuilder = new StringBuilder(); - // loop to each each byte + // loop to each byte foreach (var b in hashedByteArray) { // append it to our StringBuilder - stringBuilder.Append(b.ToString("x2").ToLowerInvariant()); + stringBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture).ToLowerInvariant()); } // return the hashed value diff --git a/DNN Platform/Library/Common/Utilities/DataCache.cs b/DNN Platform/Library/Common/Utilities/DataCache.cs index 8f46a7e8cdd..08552bd8c23 100644 --- a/DNN Platform/Library/Common/Utilities/DataCache.cs +++ b/DNN Platform/Library/Common/Utilities/DataCache.cs @@ -6,10 +6,12 @@ namespace DotNetNuke.Common.Utilities using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.Threading; using System.Web.Caching; using DotNetNuke.Abstractions.Application; + using DotNetNuke.Abstractions.Logging; using DotNetNuke.Collections.Internal; using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Portals; @@ -347,7 +349,7 @@ public static void ClearCache() } // log the cache clear event - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.CACHE_REFRESH.ToString() }; + var log = new LogInfo { LogTypeKey = nameof(EventLogType.CACHE_REFRESH), }; log.LogProperties.Add(new LogDetailInfo("*", "Refresh")); LogController.Instance.AddLog(log); } @@ -359,7 +361,7 @@ public static void ClearCache(string cachePrefix) public static void ClearFolderCache(int portalId) { - CachingProvider.Instance().Clear("Folder", portalId.ToString()); + CachingProvider.Instance().Clear("Folder", portalId.ToString(CultureInfo.InvariantCulture)); } public static void ClearHostCache(bool cascade) @@ -376,7 +378,7 @@ public static void ClearHostCache(bool cascade) public static void ClearModuleCache(int tabId) { - CachingProvider.Instance().Clear("Module", tabId.ToString()); + CachingProvider.Instance().Clear("Module", tabId.ToString(CultureInfo.InvariantCulture)); var portals = PortalController.GetPortalDictionary(); if (portals.TryGetValue(tabId, out var portalId)) { @@ -387,29 +389,29 @@ public static void ClearModuleCache(int tabId) outputProvider?.Remove(tabId); } - RemoveCache(string.Format(SharedModulesByPortalCacheKey, portalId)); - RemoveCache(string.Format(SharedModulesWithPortalCacheKey, portalId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, SharedModulesByPortalCacheKey, portalId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, SharedModulesWithPortalCacheKey, portalId)); } } public static void ClearModulePermissionsCachesByPortal(int portalId) { - CachingProvider.Instance().Clear("ModulePermissionsByPortal", portalId.ToString()); + CachingProvider.Instance().Clear("ModulePermissionsByPortal", portalId.ToString(CultureInfo.InvariantCulture)); } public static void ClearPortalCache(int portalId, bool cascade) { - CachingProvider.Instance().Clear(cascade ? "PortalCascade" : "Portal", portalId.ToString()); + CachingProvider.Instance().Clear(cascade ? "PortalCascade" : "Portal", portalId.ToString(CultureInfo.InvariantCulture)); } public static void ClearTabsCache(int portalId) { - CachingProvider.Instance().Clear("Tab", portalId.ToString()); + CachingProvider.Instance().Clear("Tab", portalId.ToString(CultureInfo.InvariantCulture)); } public static void ClearDefinitionsCache(int portalId) { - RemoveCache(string.Format(ProfileDefinitionsCacheKey, portalId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, ProfileDefinitionsCacheKey, portalId)); } public static void ClearDesktopModulePermissionsCache() @@ -421,48 +423,48 @@ public static void ClearFolderPermissionsCache(int portalId) { PermissionProvider.ResetCacheDependency( portalId, - () => RemoveCache(string.Format(FolderPermissionCacheKey, portalId))); + () => RemoveCache(string.Format(CultureInfo.InvariantCulture, FolderPermissionCacheKey, portalId))); } public static void ClearListsCache(int portalId) { - RemoveCache(string.Format(ListsCacheKey, portalId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, ListsCacheKey, portalId)); } public static void ClearModulePermissionsCache(int tabId) { - RemoveCache(string.Format(ModulePermissionCacheKey, tabId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, ModulePermissionCacheKey, tabId)); } public static void ClearTabPermissionsCache(int portalId) { - RemoveCache(string.Format(TabPermissionCacheKey, portalId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, TabPermissionCacheKey, portalId)); } public static void ClearPortalPermissionsCache(int portalId) { - RemoveCache(string.Format(PortalPermissionCacheKey, portalId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, PortalPermissionCacheKey, portalId)); } public static void ClearUserCache(int portalId, string username) { - RemoveCache(string.Format(UserCacheKey, portalId, username)); - RemoveCache(string.Format(UserProfileCacheKey, portalId, username)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, UserCacheKey, portalId, username)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, UserProfileCacheKey, portalId, username)); } public static void ClearPortalUserCountCache(int portalID) { - CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalID)); + CachingProvider.Instance().Remove(string.Format(CultureInfo.InvariantCulture, PortalUserCountCacheKey, portalID)); } public static void ClearUserPersonalizationCache(int portalId, int userId) { - RemoveCache(string.Format(UserPersonalizationCacheKey, portalId, userId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, UserPersonalizationCacheKey, portalId, userId)); } public static void ClearPackagesCache(int portalId) { - RemoveCache(string.Format(PackagesCacheKey, portalId)); + RemoveCache(string.Format(CultureInfo.InvariantCulture, PackagesCacheKey, portalId)); } /// Get cached data. @@ -639,7 +641,7 @@ private static object GetCachedDataFromRuntimeCache(PerformanceSettings performa } // set cache timeout - int timeOut = cacheItemArgs.CacheTimeOut * Convert.ToInt32(performance); + int timeOut = cacheItemArgs.CacheTimeOut * (int)performance; // if we retrieved a valid object and we are using caching if (objObject != null && timeOut > 0) diff --git a/DNN Platform/Library/Common/Utilities/DateUtils.cs b/DNN Platform/Library/Common/Utilities/DateUtils.cs index 9ac423b8508..c429c4e5c3f 100644 --- a/DNN Platform/Library/Common/Utilities/DateUtils.cs +++ b/DNN Platform/Library/Common/Utilities/DateUtils.cs @@ -1,150 +1,151 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Common.Utilities -{ - using System; - - using DotNetNuke.Data; - using DotNetNuke.Internal.SourceGenerators; +namespace DotNetNuke.Common.Utilities +{ + using System; + using System.Globalization; + + using DotNetNuke.Data; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Localization; - /// Provides utility methods to work with Dates. - public partial class DateUtils - { - private static DateTime lastUpdateUtc = DateTime.MinValue; - private static DateTime lastUpdateLocal = DateTime.MinValue; - - private static TimeSpan driftUtc = TimeSpan.MinValue; - - private static TimeSpan driftLocal = TimeSpan.MinValue; - - /// Gets the database time. - /// Date/time of the database in UTC. - [DnnDeprecated(9, 1, 0, "Replaced by GetDatabaseUtcTime")] - public static partial DateTime GetDatabaseTime() - { - return GetDatabaseUtcTime(); - } - - /// Gets DateTime Offset of current DB. - /// DateTimeOffset object. - public static TimeZoneInfo GetDatabaseDateTimeOffset() - { - var dateTimeOffset = DataProvider.Instance().GetDatabaseTimeOffset(); - var offset = dateTimeOffset.Offset; - var id = string.Format("UTC {0}", offset.ToString()); - return TimeZoneInfo.CreateCustomTimeZone(id, offset, id, id); - } - - /// Gets the database server's time in UTC. - /// Date/time of the database in UTC. - public static DateTime GetDatabaseUtcTime() - { - try - { - // Also We check that drift is not the initial value and it is not out of the maximum UTC offset - if (DateTime.UtcNow >= lastUpdateUtc + TimeSpan.FromMinutes(15) || !(TimeSpan.FromHours(-26) <= driftUtc && driftUtc <= TimeSpan.FromHours(26)) || driftUtc == TimeSpan.MinValue) - { - lastUpdateUtc = DateTime.UtcNow; - driftUtc = DateTime.UtcNow - DataProvider.Instance().GetDatabaseTimeUtc(); - } - } - catch (ArgumentOutOfRangeException) - { - lastUpdateUtc = DateTime.UtcNow; - driftUtc = DateTime.UtcNow - DataProvider.Instance().GetDatabaseTimeUtc(); - } - - return DateTime.UtcNow + driftUtc; - } - - /// Gets the database server's local time of the DB server and not the web server's local time. - /// Date/time of the database in UTC. - public static DateTime GetDatabaseLocalTime() - { - try - { - // Also We check that drift is not the initial value and it is not out of the maximum UTC offset - if (DateTime.UtcNow >= lastUpdateLocal + TimeSpan.FromMinutes(15) || !(TimeSpan.FromHours(-26) <= driftLocal && driftLocal <= TimeSpan.FromHours(26)) || driftLocal == TimeSpan.MinValue) - { - lastUpdateLocal = DateTime.Now; - driftLocal = DateTime.Now - DataProvider.Instance().GetDatabaseTime(); - } - } - catch (ArgumentOutOfRangeException) - { - lastUpdateLocal = DateTime.Now; - driftLocal = DateTime.Now - DataProvider.Instance().GetDatabaseTime(); - } - - return DateTime.Now + driftLocal; + /// Provides utility methods to work with Dates. + public partial class DateUtils + { + private static DateTime lastUpdateUtc = DateTime.MinValue; + private static DateTime lastUpdateLocal = DateTime.MinValue; + + private static TimeSpan driftUtc = TimeSpan.MinValue; + + private static TimeSpan driftLocal = TimeSpan.MinValue; + + /// Gets the database time. + /// Date/time of the database in UTC. + [DnnDeprecated(9, 1, 0, "Replaced by GetDatabaseUtcTime")] + public static partial DateTime GetDatabaseTime() + { + return GetDatabaseUtcTime(); } - /// Returns a string with the pretty printed amount of time since the specified date. - /// DateTime in UTC. - /// String representing the required date for display. - public static string CalculateDateForDisplay(DateTime date) - { - var utcTimeDifference = GetDatabaseUtcTime() - date; - - if (utcTimeDifference.TotalSeconds < 60) - { - return string.Format(Localization.GetString("SecondsAgo"), (int)utcTimeDifference.TotalSeconds); - } - - if (utcTimeDifference.TotalMinutes < 60) - { - if (utcTimeDifference.TotalMinutes < 2) - { - return string.Format(Localization.GetString("MinuteAgo"), (int)utcTimeDifference.TotalMinutes); - } - - return string.Format(Localization.GetString("MinutesAgo"), (int)utcTimeDifference.TotalMinutes); - } - - if (utcTimeDifference.TotalHours < 24) - { - if (utcTimeDifference.TotalHours < 2) - { - return string.Format(Localization.GetString("HourAgo"), (int)utcTimeDifference.TotalHours); - } - - return string.Format(Localization.GetString("HoursAgo"), (int)utcTimeDifference.TotalHours); - } - - if (utcTimeDifference.TotalDays < 7) - { - if (utcTimeDifference.TotalDays < 2) - { - return string.Format(Localization.GetString("DayAgo"), (int)utcTimeDifference.TotalDays); - } - - return string.Format(Localization.GetString("DaysAgo"), (int)utcTimeDifference.TotalDays); - } - - if (utcTimeDifference.TotalDays < 30) - { - if (utcTimeDifference.TotalDays < 14) - { - return string.Format(Localization.GetString("WeekAgo"), (int)utcTimeDifference.TotalDays / 7); - } - - return string.Format(Localization.GetString("WeeksAgo"), (int)utcTimeDifference.TotalDays / 7); - } - - if (utcTimeDifference.TotalDays < 180) - { - if (utcTimeDifference.TotalDays < 60) - { - return string.Format(Localization.GetString("MonthAgo"), (int)utcTimeDifference.TotalDays / 30); - } - - return string.Format(Localization.GetString("MonthsAgo"), (int)utcTimeDifference.TotalDays / 30); - } - - // anything else (this is the only time we have to personalize it to the user) - return date.ToShortDateString(); - } - } -} + /// Gets DateTime Offset of current DB. + /// DateTimeOffset object. + public static TimeZoneInfo GetDatabaseDateTimeOffset() + { + var dateTimeOffset = DataProvider.Instance().GetDatabaseTimeOffset(); + var offset = dateTimeOffset.Offset; + var id = $"UTC {offset}"; + return TimeZoneInfo.CreateCustomTimeZone(id, offset, id, id); + } + + /// Gets the database server's time in UTC. + /// Date/time of the database in UTC. + public static DateTime GetDatabaseUtcTime() + { + try + { + // Also We check that drift is not the initial value, and it is not out of the maximum UTC offset + if (DateTime.UtcNow >= lastUpdateUtc + TimeSpan.FromMinutes(15) || !(TimeSpan.FromHours(-26) <= driftUtc && driftUtc <= TimeSpan.FromHours(26)) || driftUtc == TimeSpan.MinValue) + { + lastUpdateUtc = DateTime.UtcNow; + driftUtc = DateTime.UtcNow - DataProvider.Instance().GetDatabaseTimeUtc(); + } + } + catch (ArgumentOutOfRangeException) + { + lastUpdateUtc = DateTime.UtcNow; + driftUtc = DateTime.UtcNow - DataProvider.Instance().GetDatabaseTimeUtc(); + } + + return DateTime.UtcNow + driftUtc; + } + + /// Gets the database server's local time of the DB server and not the web server's local time. + /// Date/time of the database in UTC. + public static DateTime GetDatabaseLocalTime() + { + try + { + // Also We check that drift is not the initial value and it is not out of the maximum UTC offset + if (DateTime.UtcNow >= lastUpdateLocal + TimeSpan.FromMinutes(15) || !(TimeSpan.FromHours(-26) <= driftLocal && driftLocal <= TimeSpan.FromHours(26)) || driftLocal == TimeSpan.MinValue) + { + lastUpdateLocal = DateTime.Now; + driftLocal = DateTime.Now - DataProvider.Instance().GetDatabaseTime(); + } + } + catch (ArgumentOutOfRangeException) + { + lastUpdateLocal = DateTime.Now; + driftLocal = DateTime.Now - DataProvider.Instance().GetDatabaseTime(); + } + + return DateTime.Now + driftLocal; + } + + /// Returns a string with the pretty printed amount of time since the specified date. + /// DateTime in UTC. + /// String representing the required date for display. + public static string CalculateDateForDisplay(DateTime date) + { + var utcTimeDifference = GetDatabaseUtcTime() - date; + + if (utcTimeDifference.TotalSeconds < 60) + { + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("SecondsAgo"), (int)utcTimeDifference.TotalSeconds); + } + + if (utcTimeDifference.TotalMinutes < 60) + { + if (utcTimeDifference.TotalMinutes < 2) + { + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("MinuteAgo"), (int)utcTimeDifference.TotalMinutes); + } + + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("MinutesAgo"), (int)utcTimeDifference.TotalMinutes); + } + + if (utcTimeDifference.TotalHours < 24) + { + if (utcTimeDifference.TotalHours < 2) + { + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("HourAgo"), (int)utcTimeDifference.TotalHours); + } + + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("HoursAgo"), (int)utcTimeDifference.TotalHours); + } + + if (utcTimeDifference.TotalDays < 7) + { + if (utcTimeDifference.TotalDays < 2) + { + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("DayAgo"), (int)utcTimeDifference.TotalDays); + } + + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("DaysAgo"), (int)utcTimeDifference.TotalDays); + } + + if (utcTimeDifference.TotalDays < 30) + { + if (utcTimeDifference.TotalDays < 14) + { + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("WeekAgo"), (int)utcTimeDifference.TotalDays / 7); + } + + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("WeeksAgo"), (int)utcTimeDifference.TotalDays / 7); + } + + if (utcTimeDifference.TotalDays < 180) + { + if (utcTimeDifference.TotalDays < 60) + { + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("MonthAgo"), (int)utcTimeDifference.TotalDays / 30); + } + + return string.Format(CultureInfo.CurrentCulture, Localization.GetString("MonthsAgo"), (int)utcTimeDifference.TotalDays / 30); + } + + // anything else (this is the only time we have to personalize it to the user) + return date.ToShortDateString(); + } + } +} diff --git a/DNN Platform/Library/Common/Utilities/EscapedString.cs b/DNN Platform/Library/Common/Utilities/EscapedString.cs index 67dc9fcf1e7..b3f5d7653dd 100644 --- a/DNN Platform/Library/Common/Utilities/EscapedString.cs +++ b/DNN Platform/Library/Common/Utilities/EscapedString.cs @@ -2,134 +2,135 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Common.Utilities -{ - using System.Collections; - using System.Collections.Generic; - - public static class EscapedString - { - private const char EscapeSequence = '\\'; - private const string DoubleEscapseSequence = @"\\"; - private const char DefaultSeperator = ','; - - /// Combine the string values of the enumerable into an escaped string. - /// An IEnumerable of values to combine. - /// An escaped string that is seperated using the specified characeter. The escape character is '\'. - /// The string returned by .ToString() is used as the value of each item in the IEnumerable. - /// The seperator char is ','. - public static string Combine(IEnumerable enumerable) - { - return Combine(enumerable, DefaultSeperator); - } - - /// Combine the string values of the enumerable into an escaped string. - /// An IEnumerable of values to combine. - /// The character to use as a seperator. - /// An escaped string that is seperated using the specified characeter. The escape character is '\'. - /// The string returned by .ToString() is used as the value of each item in the IEnumerable. - public static string Combine(IEnumerable enumerable, char seperator) - { - string result = string.Empty; - - foreach (var item in enumerable) - { - var s = item.ToString(); - s = s.Replace(EscapeSequence.ToString(), EscapeSequence.ToString() + EscapeSequence); - s = s.Replace(seperator.ToString(), EscapeSequence.ToString() + seperator); - result += s + seperator; - } - - return string.IsNullOrEmpty(result) ? string.Empty : result.Substring(0, result.Length - 1); - } - - /// Takes an escaped string and splits it into an IEnumerable of seperate strings. - /// The string to seperate. - /// IEnumerable of all the seperated strings. - /// The escape character is '\', the seperator char is ','. - public static IEnumerable Seperate(string combinedString) - { - return Seperate(combinedString, DefaultSeperator); +namespace DotNetNuke.Common.Utilities +{ + using System; + using System.Collections; + using System.Collections.Generic; + + public static class EscapedString + { + private const char EscapeSequence = '\\'; + private const string DoubleEscapeSequence = @"\\"; + private const char DefaultSeparator = ','; + + /// Combine the string values of the enumerable into an escaped string. + /// An IEnumerable of values to combine. + /// An escaped string that is separated using the specified character. The escape character is '\'. + /// The string returned by is used as the value of each item in the . + /// The separator char is ','. + public static string Combine(IEnumerable enumerable) + { + return Combine(enumerable, DefaultSeparator); + } + + /// Combine the string values of the enumerable into an escaped string. + /// An IEnumerable of values to combine. + /// The character to use as a separator. + /// An escaped string that is separated using the specified character. The escape character is '\'. + /// The string returned by is used as the value of each item in the . + public static string Combine(IEnumerable enumerable, char seperator) + { + string result = string.Empty; + + foreach (var item in enumerable) + { + var s = item.ToString(); + s = s.Replace(EscapeSequence.ToString(), EscapeSequence.ToString() + EscapeSequence); + s = s.Replace(seperator.ToString(), EscapeSequence.ToString() + seperator); + result += s + seperator; + } + + return string.IsNullOrEmpty(result) ? string.Empty : result.Substring(0, result.Length - 1); } - /// Takes an escaped string and splits it into an IEnumerable of seperate strings. - /// The string to seperate. - /// Trims whitespaces. - /// IEnumerable of all the seperated strings. - /// The escape character is '\', the seperator char is ','. - public static IEnumerable Seperate(string combinedString, bool trimWhitespaces) - { - return Seperate(combinedString, DefaultSeperator, trimWhitespaces); + /// Takes an escaped string and splits it into an IEnumerable of separate strings. + /// The string to separate. + /// IEnumerable of all the separated strings. + /// The escape character is '\', the separator char is ','. + public static IEnumerable Seperate(string combinedString) + { + return Seperate(combinedString, DefaultSeparator); } - /// Takes an escaped string and splits it into an IEnumerable of seperate strings. - /// The string to seperate. - /// The character on which to split. - /// IEnumerable of all the seperated strings. - /// The escape character is '\', the seperator char is ','. - public static IEnumerable Seperate(string combinedString, char separator) - { - return Seperate(combinedString, separator, false); - } - - /// Takes an escaped string and splits it into an IEnumerable of seperate strings. - /// The string to seperate. + /// Takes an escaped string and splits it into an IEnumerable of separate strings. + /// The string to separate. + /// Trims whitespaces. + /// IEnumerable of all the separated strings. + /// The escape character is '\', the separator char is ','. + public static IEnumerable Seperate(string combinedString, bool trimWhitespaces) + { + return Seperate(combinedString, DefaultSeparator, trimWhitespaces); + } + + /// Takes an escaped string and splits it into an IEnumerable of separate strings. + /// The string to separate. + /// The character on which to split. + /// IEnumerable of all the separated strings. + /// The escape character is '\', the separator char is ','. + public static IEnumerable Seperate(string combinedString, char separator) + { + return Seperate(combinedString, separator, false); + } + + /// Takes an escaped string and splits it into an IEnumerable of separate strings. + /// The string to separate. /// The character on which to split. - /// Trims whitespaces. - /// IEnumerable of all the seperated strings. - /// The escape character is '\'. - public static IEnumerable Seperate(string combinedString, char seperator, bool trimWhitespaces) - { - var result = new List(); - - if (string.IsNullOrEmpty(combinedString)) - { - return result; - } - - var segments = combinedString.Split(new[] { seperator }); - - for (int i = 0; i < segments.Length; i++) - { - var current = trimWhitespaces ? segments[i].Trim() : segments[i]; - - while (current.EndsWith(EscapeSequence.ToString())) - { - if (EndsInEscapeMode(current)) - { - i++; - current = current.Substring(0, current.Length - 1) + seperator + segments[i]; - } - else - { - break; - } - } - - result.Add(current.Replace(DoubleEscapseSequence, EscapeSequence.ToString())); - } - - return result; - } - - private static bool EndsInEscapeMode(string s) - { - int escapeCount = 0; - - // count the number of escape chars on end of string - for (int i = s.Length - 1; i > -1; i--) - { - if (s.Substring(i, 1) == EscapeSequence.ToString()) - { - escapeCount++; - } - else - { - break; - } - } - - return escapeCount % 2 == 1; // odd count means escape mode is active - } - } -} + /// Trims whitespaces. + /// IEnumerable of all the separated strings. + /// The escape character is '\'. + public static IEnumerable Seperate(string combinedString, char seperator, bool trimWhitespaces) + { + var result = new List(); + + if (string.IsNullOrEmpty(combinedString)) + { + return result; + } + + var segments = combinedString.Split(new[] { seperator }); + + for (int i = 0; i < segments.Length; i++) + { + var current = trimWhitespaces ? segments[i].Trim() : segments[i]; + + while (current.EndsWith(EscapeSequence.ToString(), StringComparison.Ordinal)) + { + if (EndsInEscapeMode(current)) + { + i++; + current = current.Substring(0, current.Length - 1) + seperator + segments[i]; + } + else + { + break; + } + } + + result.Add(current.Replace(DoubleEscapeSequence, EscapeSequence.ToString())); + } + + return result; + } + + private static bool EndsInEscapeMode(string s) + { + int escapeCount = 0; + + // count the number of escape chars on end of string + for (int i = s.Length - 1; i > -1; i--) + { + if (s.Substring(i, 1) == EscapeSequence.ToString()) + { + escapeCount++; + } + else + { + break; + } + } + + return escapeCount % 2 == 1; // odd count means escape mode is active + } + } +} diff --git a/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs b/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs index d8e28332dd8..ce8cee6a8de 100644 --- a/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs +++ b/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Common.Utilities { + using System; using System.Collections.Generic; using System.Linq; @@ -48,19 +49,15 @@ public bool IsAllowedExtension(string extension) /// public bool IsAllowedExtension(string extension, IEnumerable additionalExtensions) { - var allExtensions = this.CombineLists(additionalExtensions).ToList(); + var allExtensions = this.CombineLists(additionalExtensions).ToHashSet(StringComparer.OrdinalIgnoreCase); if (allExtensions.Count == 0) { return true; } - if (!extension.StartsWith(".")) + if (!extension.StartsWith(".", StringComparison.Ordinal)) { - extension = "." + extension.ToLowerInvariant(); - } - else - { - extension = extension.ToLowerInvariant(); + extension = "." + extension; } return allExtensions.Contains(extension); @@ -102,7 +99,7 @@ public IFileExtensionAllowList RestrictBy(IFileExtensionAllowList parentList) private static IEnumerable NormalizeExtensions(IEnumerable additionalExtensions) { - return additionalExtensions.Select(ext => (ext.StartsWith(".") ? ext : "." + ext).ToLowerInvariant()); + return additionalExtensions.Select(ext => (ext.StartsWith(".", StringComparison.Ordinal) ? ext : "." + ext).ToLowerInvariant()); } private IEnumerable CombineLists(IEnumerable additionalExtensions) diff --git a/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs b/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs index 7f2a38a1ada..6d9d29cfbfc 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs @@ -19,7 +19,7 @@ public static partial class FileSystemExtensions public static void CheckZipEntry(this ZipArchiveEntry input) { var fullName = input.FullName.Replace('\\', '/'); - if (fullName.StartsWith("..") || fullName.Contains("/../")) + if (fullName.StartsWith("..", StringComparison.Ordinal) || fullName.Contains("/../", StringComparison.Ordinal)) { throw new IllegalZipFileException("Illegal Zip File"); } @@ -28,10 +28,8 @@ public static void CheckZipEntry(this ZipArchiveEntry input) public static string ReadTextFile(this ZipArchiveEntry input) { var text = string.Empty; - using (var reader = new StreamReader(input.Open())) - { - text = reader.ReadToEnd(); - } + using var reader = new StreamReader(input.Open()); + text = reader.ReadToEnd(); return text; } @@ -65,7 +63,7 @@ public static IEnumerable FileEntries(this ZipArchive zip) public static partial void CheckZipEntry(this ZipEntry input) { var fullName = input.Name.Replace('\\', '/'); - if (fullName.StartsWith("..") || fullName.Contains("/../")) + if (fullName.StartsWith("..", StringComparison.Ordinal) || fullName.Contains("/../", StringComparison.Ordinal)) { throw new IllegalZipFileException("Illegal Zip File"); } diff --git a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs index a0b94f0a1b7..7bcea4cc737 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs @@ -1,885 +1,887 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Common.Utilities -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.IO.Compression; - using System.Linq; - using System.Threading; - using System.Threading.Tasks; - - using DotNetNuke.Abstractions.Application; - using DotNetNuke.Instrumentation; - using DotNetNuke.Internal.SourceGenerators; - using ICSharpCode.SharpZipLib.Zip; - using Microsoft.Extensions.DependencyInjection; - - using Directory = SchwabenCode.QuickIO.QuickIODirectory; - using DirectoryInfo = SchwabenCode.QuickIO.QuickIODirectoryInfo; - using File = SchwabenCode.QuickIO.QuickIOFile; - - /// File System utilities. - public partial class FileSystemUtils - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSystemUtils)); - - /// Adds a File to a Zip File. - /// The Zip File to add to. - /// The path to the file to add. - /// The name of the file to add. - /// The name of the folder to use for the zip entry. - public static void AddToZip(ref ZipArchive zipFile, string filePath, string fileName, string folder) - { - using var fs = File.OpenRead(FixPath(filePath)); - - var buffer = new byte[fs.Length]; - - var len = fs.Read(buffer, 0, buffer.Length); - if (len != fs.Length) - { - Logger.ErrorFormat( - "Reading from {0} didn't read all data in buffer. Requested to read {1} bytes, but was read {2} bytes", - filePath, - fs.Length, - len); - } - - // Create Zip Entry - zipFile.CreateEntryFromFile(FixPath(filePath), Path.Combine(folder, fileName)); - } - - /// Adds a File to a Zip File. - /// The Zip File to add to. - /// The path to the file to add. - /// The name of the file to add. - /// The name of the folder to use for the zip entry. - /// The cancellation token. - /// A indicating completion. - public static async Task AddToZipAsync(ZipArchive zipFile, string filePath, string fileName, string folder, CancellationToken cancellationToken = default) - { - using var fs = File.OpenRead(FixPath(filePath)); - - // Read file into byte array buffer - var buffer = new byte[fs.Length]; - - var len = await fs.ReadAsync(buffer, 0, buffer.Length, cancellationToken); - if (len != fs.Length) - { - Logger.ErrorFormat( - "Reading from {0} didn't read all data in buffer. Requested to read {1} bytes, but was read {2} bytes", - filePath, - fs.Length, - len); - } - - // Create Zip Entry - zipFile.CreateEntryFromFile(FixPath(filePath), Path.Combine(folder, fileName)); - } - - /// Tries to copy a file in the file system. - /// The name of the source file. - /// The name of the destination file. - public static void CopyFile(string sourceFileName, string destFileName) - { - if (File.Exists(destFileName)) - { - File.SetAttributes(destFileName, FileAttributes.Normal); - } - - File.Copy(sourceFileName, destFileName, true); - } - - /// Tries to copy a file in the file system. - /// The name of the source file. - /// The name of the destination file. - /// A indicating completion. - public static async Task CopyFileAsync(string sourceFileName, string destFileName) - { - if (await File.ExistsAsync(destFileName)) - { - await File.SetAttributesAsync(destFileName, FileAttributes.Normal); - } - - await File.CopyAsync(sourceFileName, destFileName, true); - } - - /// - /// Deletes file in areas with a high degree of concurrent file access (i.e. caching, logging). - /// This solves file concurrency issues under heavy load. - /// - /// The file name. - /// The number of milliseconds to wait. - /// The maximum number of attempts. - /// Whether the file is deleted. - public static bool DeleteFileWithWait(string fileName, short waitInMilliseconds, short maxAttempts) - { - fileName = FixPath(fileName); - if (!File.Exists(fileName)) - { - return true; - } - - var fileDeleted = false; - var i = 0; - while (fileDeleted != true) - { - if (i > maxAttempts) - { - break; - } - - i = i + 1; - try - { - if (File.Exists(fileName)) - { - File.Delete(fileName); - } - - fileDeleted = true; // we don't care if it didn't exist...the operation didn't fail, that's what we care about - } - catch (Exception exc) - { - Logger.Error(exc); - fileDeleted = false; - } - - if (fileDeleted == false) - { - Thread.Sleep(waitInMilliseconds); - } - } - - return fileDeleted; - } - - /// - /// Deletes file in areas with a high degree of concurrent file access (i.e. caching, logging). - /// This solves file concurrency issues under heavy load. - /// - /// The file name. - /// The number of milliseconds to wait. - /// The maximum number of attempts. - /// The cancellation token. - /// Whether the file is deleted. - public static async Task DeleteFileWithWaitAsync(string fileName, short waitInMilliseconds, short maxAttempts, CancellationToken cancellationToken = default) - { - fileName = FixPath(fileName); - if (!await File.ExistsAsync(fileName)) - { - return true; - } - - var fileDeleted = false; - var i = 0; - while (fileDeleted != true) - { - if (i > maxAttempts) - { - break; - } - - i = i + 1; - try - { - if (await File.ExistsAsync(fileName)) - { - await File.DeleteAsync(fileName); - } - - fileDeleted = true; // we don't care if it didn't exist...the operation didn't fail, that's what we care about - } - catch (Exception exc) - { - Logger.Error(exc); - fileDeleted = false; - } - - if (fileDeleted == false) - { - await Task.Delay(waitInMilliseconds, cancellationToken); - } - } - - return fileDeleted; - } - - /// Tries to delete a file from the file system. - /// The name of the file. - public static void DeleteFile(string fileName) - { - fileName = FixPath(fileName); - if (File.Exists(fileName)) - { - File.SetAttributes(fileName, FileAttributes.Normal); - File.Delete(fileName); - } - } - - /// Tries to delete a file from the file system. - /// The name of the file. - /// A indicating completion. - public static async Task DeleteFileAsync(string fileName) - { - fileName = FixPath(fileName); - if (await File.ExistsAsync(fileName)) - { - await File.SetAttributesAsync(fileName, FileAttributes.Normal); - await File.DeleteAsync(fileName); - } - } - - /// Reads a file. - /// The file path. - /// The string content of the file. - public static string ReadFile(string filePath) - { - using var reader = File.OpenText(filePath); - return reader.ReadToEnd(); - } - - /// Reads a file. - /// The file path. - /// The cancellation token. - /// The string content of the file. - public static async Task ReadFileAsync(string filePath, CancellationToken cancellationToken = default) - { - using var reader = File.OpenText(filePath); - return await reader.ReadToEndAsync(); - } - - /// Unzips a resources zip file. - /// The zip archive stream. - /// The destination path to extract to. - public static void UnzipResources(ZipArchive zipStream, string destPath) - { - try - { - UnzipResources(zipStream.FileEntries(), destPath); - } - finally - { - zipStream?.Dispose(); - } - } - - /// Unzips a resources zip file. - /// The zip entries to unzip. - /// The destination path to extract to. - public static void UnzipResources(IEnumerable zipArchiveEntries, string destPath) - { - foreach (var zipEntry in zipArchiveEntries) - { - HtmlUtils.WriteKeepAlive(); - var localFileName = zipEntry.FullName; - var relativeDir = Path.GetDirectoryName(zipEntry.FullName); - if (!string.IsNullOrEmpty(relativeDir)) - { - var destDir = Path.Combine(destPath, relativeDir); - if (!Directory.Exists(destDir)) - { - Directory.Create(destDir, true); - } - } - - if (string.IsNullOrEmpty(localFileName)) - { - continue; - } - - var fileNamePath = FixPath(Path.Combine(destPath, localFileName)); - try - { - if (File.Exists(fileNamePath)) - { - File.SetAttributes(fileNamePath, FileAttributes.Normal); - File.Delete(fileNamePath); - } - - using var fileStream = File.Open(fileNamePath, FileMode.CreateNew); - zipEntry.Open().CopyToStream(fileStream, 25000); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - } - - /// Unzips a resources zip file. - /// The zip archive stream. - /// The destination path to extract to. - /// The cancellation token. - /// A indicating completion. - public static async Task UnzipResourcesAsync(ZipArchive zipStream, string destPath, CancellationToken cancellationToken = default) - { - try - { - await UnzipResourcesAsync(zipStream.FileEntries(), destPath, cancellationToken); - } - finally - { - zipStream?.Dispose(); - } - } - - /// Unzips a resources zip file. - /// The zip archive entries to extract. - /// The destination path to extract to. - /// The cancellation token. - /// A indicating completion. - public static async Task UnzipResourcesAsync(IEnumerable zipArchiveEntries, string destPath, CancellationToken cancellationToken) - { - foreach (var zipEntry in zipArchiveEntries) - { - cancellationToken.ThrowIfCancellationRequested(); - HtmlUtils.WriteKeepAlive(); - - var localFileName = zipEntry.FullName; - var relativeDir = Path.GetDirectoryName(zipEntry.FullName); - if (!string.IsNullOrEmpty(relativeDir)) - { - var destDir = Path.Combine(destPath, relativeDir); - if (!await Directory.ExistsAsync(destDir)) - { - await Directory.CreateAsync(destDir, true); - } - } - - if (string.IsNullOrEmpty(localFileName)) - { - continue; - } - - var fileNamePath = FixPath(Path.Combine(destPath, localFileName)); - try - { - if (await File.ExistsAsync(fileNamePath)) - { - await File.SetAttributesAsync(fileNamePath, FileAttributes.Normal); - await File.DeleteAsync(fileNamePath); - } - - using var fileStream = File.Open(fileNamePath, FileMode.CreateNew); - await zipEntry.Open().CopyToAsync(fileStream, 25000, cancellationToken); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - } - - /// Deletes the files specified. - /// An array of the file paths for the files to delete. - /// An empty string if succeeded or a list of errors in case of failures. - [Obsolete("Deprecated in DotNetNuke 10.0.2. Please use overload with IApplicationStatusInfo. Scheduled removal in v12.0.0.")] - public static string DeleteFiles(Array arrPaths) - => DeleteFiles(Globals.GetCurrentServiceProvider().GetRequiredService(), arrPaths); - - /// Deletes the files specified. - /// The application status. - /// An array of the file paths for the files to delete. - /// An empty string if succeeded or a list of errors in case of failures. - public static string DeleteFiles(IApplicationStatusInfo appStatus, Array arrPaths) - { - var strExceptions = string.Empty; - for (var i = 0; i < arrPaths.Length; i++) - { - var strPath = (arrPaths.GetValue(i) ?? string.Empty).ToString(); - var pos = strPath.IndexOf("'", StringComparison.Ordinal); - if (pos != -1) - { - // the (') represents a comment to the end of the line - strPath = strPath.Substring(0, pos); - } - - strPath = FixPath(strPath).TrimStart('\\'); - if (string.IsNullOrEmpty(strPath)) - { - continue; - } - - strPath = Path.Combine(appStatus.ApplicationMapPath, strPath); - if (strPath.EndsWith("\\") && Directory.Exists(strPath)) - { - var directoryInfo = new System.IO.DirectoryInfo(strPath); - var applicationPath = appStatus.ApplicationMapPath + "\\"; - if (!directoryInfo.FullName.StartsWith(applicationPath, StringComparison.InvariantCultureIgnoreCase) || - directoryInfo.FullName.Equals(applicationPath, StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - try - { - Globals.DeleteFolderRecursive(strPath); - } - catch (Exception ex) - { - Logger.Error(ex); - strExceptions += $"Processing folder ({strPath}) Error: {ex.Message}{Environment.NewLine}"; - } - } - else - { - if (!File.Exists(strPath)) - { - continue; - } - - try - { - File.SetAttributes(strPath, FileAttributes.Normal); - File.Delete(strPath); - } - catch (Exception ex) - { - Logger.Error(ex); - strExceptions += $"Processing file ({strPath}) Error: {ex.Message}{Environment.NewLine}"; - } - } - } - - return strExceptions; - } - - /// Deletes the files specified. - /// The application status. - /// An array of the file paths for the files to delete. - /// The cancellation token. - /// An empty string if succeeded or a list of errors in case of failures. - public static async Task DeleteFilesAsync(IApplicationStatusInfo appStatus, Array arrPaths, CancellationToken cancellationToken = default) - { - var strExceptions = string.Empty; - for (var i = 0; i < arrPaths.Length; i++) - { - var strPath = (arrPaths.GetValue(i) ?? string.Empty).ToString(); - var pos = strPath.IndexOf("'", StringComparison.Ordinal); - if (pos != -1) - { - // the (') represents a comment to the end of the line - strPath = strPath.Substring(0, pos); - } - - strPath = FixPath(strPath).TrimStart('\\'); - if (string.IsNullOrEmpty(strPath)) - { - continue; - } - - strPath = Path.Combine(appStatus.ApplicationMapPath, strPath); - if (strPath.EndsWith("\\") && await Directory.ExistsAsync(strPath)) - { - var directoryInfo = new System.IO.DirectoryInfo(strPath); - var applicationPath = appStatus.ApplicationMapPath + "\\"; - if (!directoryInfo.FullName.StartsWith(applicationPath, StringComparison.InvariantCultureIgnoreCase) || - directoryInfo.FullName.Equals(applicationPath, StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - try - { - await DeleteFolderRecursiveAsync(strPath, cancellationToken); - } - catch (Exception ex) - { - Logger.Error(ex); - strExceptions += $"Processing folder ({strPath}) Error: {ex.Message}{Environment.NewLine}"; - } - } - else - { - if (!await File.ExistsAsync(strPath)) - { - continue; - } - - try - { - await File.SetAttributesAsync(strPath, FileAttributes.Normal); - await File.DeleteAsync(strPath); - } - catch (Exception ex) - { - Logger.Error(ex); - strExceptions += $"Processing file ({strPath}) Error: {ex.Message}{Environment.NewLine}"; - } - } - } - - return strExceptions; - } - - /// Deletes files that match a filter recursively within folders. - /// The root path to filter from. - /// The filter to select the files to delete. - public static void DeleteFilesRecursive(string strRoot, string filter) - { - if (string.IsNullOrEmpty(strRoot)) - { - return; - } - - strRoot = FixPath(strRoot); - if (!Directory.Exists(strRoot)) - { - return; - } - - foreach (var strFolder in Directory.EnumerateDirectoryPaths(strRoot)) - { - var directory = new DirectoryInfo(strFolder); - if ((directory.Attributes & FileAttributes.Hidden) == 0 && (directory.Attributes & FileAttributes.System) == 0) - { - DeleteFilesRecursive(strFolder, filter); - } - } - - foreach (var strFile in Directory.EnumerateFilePaths(strRoot).Where(f => f.Contains(filter))) - { - try - { - DeleteFile(strFile); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - } - - /// Deletes files that match a filter recursively within folders. - /// The root path to filter from. - /// The filter to select the files to delete. - /// The cancellation token. - /// A indicating completion. - public static async Task DeleteFilesRecursiveAsync(string strRoot, string filter, CancellationToken cancellationToken = default) - { - if (string.IsNullOrEmpty(strRoot)) - { - return; - } - - strRoot = FixPath(strRoot); - if (!await Directory.ExistsAsync(strRoot)) - { - return; - } - - foreach (var strFolder in await Directory.EnumerateDirectoryPathsAsync(strRoot)) - { - cancellationToken.ThrowIfCancellationRequested(); - var directory = new DirectoryInfo(strFolder); - if ((directory.Attributes & FileAttributes.Hidden) == 0 && (directory.Attributes & FileAttributes.System) == 0) - { - await DeleteFilesRecursiveAsync(strFolder, filter, cancellationToken); - } - } - - foreach (var strFile in (await Directory.EnumerateFilePathsAsync(strRoot)).Where(f => f.Contains(filter))) - { - cancellationToken.ThrowIfCancellationRequested(); - - try - { - await DeleteFileAsync(strFile); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - } - - /// Deletes a folder and all its child files and folders. - /// The root path to delete from. - public static void DeleteFolderRecursive(string strRoot) - { - strRoot = FixPath(strRoot); - if (string.IsNullOrEmpty(strRoot) || !Directory.Exists(strRoot)) - { - Logger.Info($"{strRoot} does not exist. "); - return; - } - - foreach (var strFolder in Directory.EnumerateDirectoryPaths(strRoot)) - { - DeleteFolderRecursive(strFolder); - } - - foreach (var strFile in Directory.EnumerateFilePaths(strRoot)) - { - try - { - DeleteFile(strFile); - } - catch (Exception ex) - { - Logger.Info($"{strRoot} does not exist."); - Logger.Error(ex); - } - } - - try - { - Directory.SetAttributes(strRoot, FileAttributes.Normal); - Directory.Delete(strRoot); - } - catch (Exception ex) - { - Logger.Info($"{strRoot} does not exist."); - Logger.Error(ex); - } - } - - /// Deletes a folder and all its child files and folders. - /// The root path to delete from. - /// The cancellation token. - /// A indicating completion. - public static async Task DeleteFolderRecursiveAsync(string strRoot, CancellationToken cancellationToken = default) - { - strRoot = FixPath(strRoot); - if (string.IsNullOrEmpty(strRoot) || !await Directory.ExistsAsync(strRoot)) - { - Logger.Info($"{strRoot} does not exist. "); - return; - } - - foreach (var strFolder in await Directory.EnumerateDirectoryPathsAsync(strRoot)) - { - cancellationToken.ThrowIfCancellationRequested(); - await DeleteFolderRecursiveAsync(strFolder, cancellationToken); - } - - foreach (var strFile in await Directory.EnumerateFilePathsAsync(strRoot)) - { - cancellationToken.ThrowIfCancellationRequested(); - try - { - await DeleteFileAsync(strFile); - } - catch (Exception ex) - { - Logger.Info($"{strRoot} does not exist."); - Logger.Error(ex); - } - } - - try - { - await Directory.SetAttributesAsync(strRoot, FileAttributes.Normal); - await Directory.DeleteAsync(strRoot); - } - catch (Exception ex) - { - Logger.Info($"{strRoot} does not exist."); - Logger.Error(ex); - } - } - - /// Deletes all empty folders beneath a given root folder and the root folder itself as well if empty. - /// The root folder path. - public static void DeleteEmptyFoldersRecursive(string path) - { - if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path)) - { - Logger.Info($"{path} does not exist."); - return; - } - - // first take care of folders - foreach (var folder in Directory.EnumerateDirectoryPaths(path)) - { - DeleteEmptyFoldersRecursive(folder); - } - - // if any files or folders left, return - if (Directory.EnumerateFileSystemEntries(path).Any()) - { - return; - } - - try - { - // delete this empty folder - Directory.SetAttributes(path, FileAttributes.Normal); - Directory.Delete(path); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - - /// Deletes all empty folders beneath a given root folder and the root folder itself as well if empty. - /// The root folder path. - /// The cancellation token. - /// A indicating completion. - public static async Task DeleteEmptyFoldersRecursiveAsync(string path, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(path) || !await Directory.ExistsAsync(path)) - { - Logger.Info($"{path} does not exist."); - return; - } - - // first take care of folders - foreach (var folder in await Directory.EnumerateDirectoryPathsAsync(path)) - { - cancellationToken.ThrowIfCancellationRequested(); - await DeleteEmptyFoldersRecursiveAsync(folder, cancellationToken); - } - - // if any files or folders left, return - if ((await Directory.EnumerateFileSystemEntriesAsync(path)).Any()) - { - return; - } - - try - { - // delete this empty folder - await Directory.SetAttributesAsync(path, FileAttributes.Normal); - await Directory.DeleteAsync(path); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - - /// Fixes the path in case the path separator is not windows style. - /// The path to fix. - /// A valid Windows path. - public static string FixPath(string input) - { - return string.IsNullOrEmpty(input) ? input : input.Trim().Replace("/", "\\"); - } - - /// Adds a file to a zip. - /// The zip file stream to add to. - /// The path to the file to add. - /// Name of the file to use in the zip entry. - /// The name of the folder to use in the zip entry.. - [DnnDeprecated(9, 11, 0, "Replaced with .NET compression types.")] - public static partial void AddToZip(ref ZipOutputStream zipFile, string filePath, string fileName, string folder) - { - FileStream fs = null; - try - { - // Open File Stream - fs = File.OpenRead(FixPath(filePath)); - - // Read file into byte array buffer - var buffer = new byte[fs.Length]; - - var len = fs.Read(buffer, 0, buffer.Length); - if (len != fs.Length) - { - Logger.ErrorFormat( - "Reading from " + - filePath + - " didn't read all data in buffer. " + - "Requested to read {0} bytes, but was read {1} bytes", - fs.Length, - len); - } - - // Create Zip Entry - var entry = new ZipEntry(Path.Combine(folder, fileName)); - entry.DateTime = DateTime.Now; - entry.Size = fs.Length; - fs.Close(); - - // Compress file and add to Zip file - zipFile.PutNextEntry(entry); - zipFile.Write(buffer, 0, buffer.Length); - } - finally - { - if (fs != null) - { - fs.Close(); - fs.Dispose(); - } - } - } - - /// Unzips a resources zip file. - /// The zip stream. - /// The destination path to extract to. - [DnnDeprecated(9, 11, 0, "Replaced with .NET compression types.")] - public static partial void UnzipResources(ZipInputStream zipStream, string destPath) - { - try - { - var zipEntry = zipStream.GetNextEntry(); - while (zipEntry != null) - { - zipEntry.CheckZipEntry(); - HtmlUtils.WriteKeepAlive(); - var localFileName = zipEntry.Name; - var relativeDir = Path.GetDirectoryName(zipEntry.Name); - if (!string.IsNullOrEmpty(relativeDir) && (!Directory.Exists(Path.Combine(destPath, relativeDir)))) - { - Directory.Create(Path.Combine(destPath, relativeDir), true); - } - - if (!zipEntry.IsDirectory && (!string.IsNullOrEmpty(localFileName))) - { - var fileNamePath = FixPath(Path.Combine(destPath, localFileName)); - try - { - if (File.Exists(fileNamePath)) - { - File.SetAttributes(fileNamePath, FileAttributes.Normal); - File.Delete(fileNamePath); - } - - FileStream objFileStream = null; - try - { - File.Create(fileNamePath); - objFileStream = File.Open(fileNamePath); - var arrData = new byte[2048]; - var intSize = zipStream.Read(arrData, 0, arrData.Length); - while (intSize > 0) - { - objFileStream.Write(arrData, 0, intSize); - intSize = zipStream.Read(arrData, 0, arrData.Length); - } - } - finally - { - if (objFileStream != null) - { - objFileStream.Close(); - objFileStream.Dispose(); - } - } - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - - zipEntry = zipStream.GetNextEntry(); - } - } - finally - { - if (zipStream != null) - { - zipStream.Close(); - zipStream.Dispose(); - } - } - } - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Common.Utilities +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.IO.Compression; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; + using ICSharpCode.SharpZipLib.Zip; + using Microsoft.Extensions.DependencyInjection; + + using Directory = SchwabenCode.QuickIO.QuickIODirectory; + using DirectoryInfo = SchwabenCode.QuickIO.QuickIODirectoryInfo; + using File = SchwabenCode.QuickIO.QuickIOFile; + + /// File System utilities. + public partial class FileSystemUtils + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSystemUtils)); + + /// Adds a File to a Zip File. + /// The Zip File to add to. + /// The path to the file to add. + /// The name of the file to add. + /// The name of the folder to use for the zip entry. + public static void AddToZip(ref ZipArchive zipFile, string filePath, string fileName, string folder) + { + using var fs = File.OpenRead(FixPath(filePath)); + + var buffer = new byte[fs.Length]; + + var len = fs.Read(buffer, 0, buffer.Length); + if (len != fs.Length) + { + Logger.ErrorFormat( + CultureInfo.InvariantCulture, + "Reading from {0} didn't read all data in buffer. Requested to read {1} bytes, but was read {2} bytes", + filePath, + fs.Length, + len); + } + + // Create Zip Entry + zipFile.CreateEntryFromFile(FixPath(filePath), Path.Combine(folder, fileName)); + } + + /// Adds a File to a Zip File. + /// The Zip File to add to. + /// The path to the file to add. + /// The name of the file to add. + /// The name of the folder to use for the zip entry. + /// The cancellation token. + /// A indicating completion. + public static async Task AddToZipAsync(ZipArchive zipFile, string filePath, string fileName, string folder, CancellationToken cancellationToken = default) + { + using var fs = File.OpenRead(FixPath(filePath)); + + // Read file into byte array buffer + var buffer = new byte[fs.Length]; + + var len = await fs.ReadAsync(buffer, 0, buffer.Length, cancellationToken); + if (len != fs.Length) + { + Logger.ErrorFormat( + CultureInfo.InvariantCulture, + "Reading from {0} didn't read all data in buffer. Requested to read {1} bytes, but was read {2} bytes", + filePath, + fs.Length, + len); + } + + // Create Zip Entry + zipFile.CreateEntryFromFile(FixPath(filePath), Path.Combine(folder, fileName)); + } + + /// Tries to copy a file in the file system. + /// The name of the source file. + /// The name of the destination file. + public static void CopyFile(string sourceFileName, string destFileName) + { + if (File.Exists(destFileName)) + { + File.SetAttributes(destFileName, FileAttributes.Normal); + } + + File.Copy(sourceFileName, destFileName, true); + } + + /// Tries to copy a file in the file system. + /// The name of the source file. + /// The name of the destination file. + /// A indicating completion. + public static async Task CopyFileAsync(string sourceFileName, string destFileName) + { + if (await File.ExistsAsync(destFileName)) + { + await File.SetAttributesAsync(destFileName, FileAttributes.Normal); + } + + await File.CopyAsync(sourceFileName, destFileName, true); + } + + /// + /// Deletes file in areas with a high degree of concurrent file access (i.e. caching, logging). + /// This solves file concurrency issues under heavy load. + /// + /// The file name. + /// The number of milliseconds to wait. + /// The maximum number of attempts. + /// Whether the file is deleted. + public static bool DeleteFileWithWait(string fileName, short waitInMilliseconds, short maxAttempts) + { + fileName = FixPath(fileName); + if (!File.Exists(fileName)) + { + return true; + } + + var fileDeleted = false; + var i = 0; + while (fileDeleted != true) + { + if (i > maxAttempts) + { + break; + } + + i = i + 1; + try + { + if (File.Exists(fileName)) + { + File.Delete(fileName); + } + + fileDeleted = true; // we don't care if it didn't exist...the operation didn't fail, that's what we care about + } + catch (Exception exc) + { + Logger.Error(exc); + fileDeleted = false; + } + + if (fileDeleted == false) + { + Thread.Sleep(waitInMilliseconds); + } + } + + return fileDeleted; + } + + /// + /// Deletes file in areas with a high degree of concurrent file access (i.e. caching, logging). + /// This solves file concurrency issues under heavy load. + /// + /// The file name. + /// The number of milliseconds to wait. + /// The maximum number of attempts. + /// The cancellation token. + /// Whether the file is deleted. + public static async Task DeleteFileWithWaitAsync(string fileName, short waitInMilliseconds, short maxAttempts, CancellationToken cancellationToken = default) + { + fileName = FixPath(fileName); + if (!await File.ExistsAsync(fileName)) + { + return true; + } + + var fileDeleted = false; + var i = 0; + while (fileDeleted != true) + { + if (i > maxAttempts) + { + break; + } + + i = i + 1; + try + { + if (await File.ExistsAsync(fileName)) + { + await File.DeleteAsync(fileName); + } + + fileDeleted = true; // we don't care if it didn't exist...the operation didn't fail, that's what we care about + } + catch (Exception exc) + { + Logger.Error(exc); + fileDeleted = false; + } + + if (fileDeleted == false) + { + await Task.Delay(waitInMilliseconds, cancellationToken); + } + } + + return fileDeleted; + } + + /// Tries to delete a file from the file system. + /// The name of the file. + public static void DeleteFile(string fileName) + { + fileName = FixPath(fileName); + if (File.Exists(fileName)) + { + File.SetAttributes(fileName, FileAttributes.Normal); + File.Delete(fileName); + } + } + + /// Tries to delete a file from the file system. + /// The name of the file. + /// A indicating completion. + public static async Task DeleteFileAsync(string fileName) + { + fileName = FixPath(fileName); + if (await File.ExistsAsync(fileName)) + { + await File.SetAttributesAsync(fileName, FileAttributes.Normal); + await File.DeleteAsync(fileName); + } + } + + /// Reads a file. + /// The file path. + /// The string content of the file. + public static string ReadFile(string filePath) + { + using var reader = File.OpenText(filePath); + return reader.ReadToEnd(); + } + + /// Reads a file. + /// The file path. + /// The cancellation token. + /// The string content of the file. + public static async Task ReadFileAsync(string filePath, CancellationToken cancellationToken = default) + { + using var reader = File.OpenText(filePath); + return await reader.ReadToEndAsync(); + } + + /// Unzips a resources zip file. + /// The zip archive stream. + /// The destination path to extract to. + public static void UnzipResources(ZipArchive zipStream, string destPath) + { + try + { + UnzipResources(zipStream.FileEntries(), destPath); + } + finally + { + zipStream?.Dispose(); + } + } + + /// Unzips a resources zip file. + /// The zip entries to unzip. + /// The destination path to extract to. + public static void UnzipResources(IEnumerable zipArchiveEntries, string destPath) + { + foreach (var zipEntry in zipArchiveEntries) + { + HtmlUtils.WriteKeepAlive(); + var localFileName = zipEntry.FullName; + var relativeDir = Path.GetDirectoryName(zipEntry.FullName); + if (!string.IsNullOrEmpty(relativeDir)) + { + var destDir = Path.Combine(destPath, relativeDir); + if (!Directory.Exists(destDir)) + { + Directory.Create(destDir, true); + } + } + + if (string.IsNullOrEmpty(localFileName)) + { + continue; + } + + var fileNamePath = FixPath(Path.Combine(destPath, localFileName)); + try + { + if (File.Exists(fileNamePath)) + { + File.SetAttributes(fileNamePath, FileAttributes.Normal); + File.Delete(fileNamePath); + } + + using var fileStream = File.Open(fileNamePath, FileMode.CreateNew); + zipEntry.Open().CopyToStream(fileStream, 25000); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + } + + /// Unzips a resources zip file. + /// The zip archive stream. + /// The destination path to extract to. + /// The cancellation token. + /// A indicating completion. + public static async Task UnzipResourcesAsync(ZipArchive zipStream, string destPath, CancellationToken cancellationToken = default) + { + try + { + await UnzipResourcesAsync(zipStream.FileEntries(), destPath, cancellationToken); + } + finally + { + zipStream?.Dispose(); + } + } + + /// Unzips a resources zip file. + /// The zip archive entries to extract. + /// The destination path to extract to. + /// The cancellation token. + /// A indicating completion. + public static async Task UnzipResourcesAsync(IEnumerable zipArchiveEntries, string destPath, CancellationToken cancellationToken) + { + foreach (var zipEntry in zipArchiveEntries) + { + cancellationToken.ThrowIfCancellationRequested(); + HtmlUtils.WriteKeepAlive(); + + var localFileName = zipEntry.FullName; + var relativeDir = Path.GetDirectoryName(zipEntry.FullName); + if (!string.IsNullOrEmpty(relativeDir)) + { + var destDir = Path.Combine(destPath, relativeDir); + if (!await Directory.ExistsAsync(destDir)) + { + await Directory.CreateAsync(destDir, true); + } + } + + if (string.IsNullOrEmpty(localFileName)) + { + continue; + } + + var fileNamePath = FixPath(Path.Combine(destPath, localFileName)); + try + { + if (await File.ExistsAsync(fileNamePath)) + { + await File.SetAttributesAsync(fileNamePath, FileAttributes.Normal); + await File.DeleteAsync(fileNamePath); + } + + using var fileStream = File.Open(fileNamePath, FileMode.CreateNew); + await zipEntry.Open().CopyToAsync(fileStream, 25000, cancellationToken); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + } + + /// Deletes the files specified. + /// An array of the file paths for the files to delete. + /// An empty string if succeeded or a list of errors in case of failures. + [Obsolete("Deprecated in DotNetNuke 10.0.2. Please use overload with IApplicationStatusInfo. Scheduled removal in v12.0.0.")] + public static string DeleteFiles(Array arrPaths) + => DeleteFiles(Globals.GetCurrentServiceProvider().GetRequiredService(), arrPaths); + + /// Deletes the files specified. + /// The application status. + /// An array of the file paths for the files to delete. + /// An empty string if succeeded or a list of errors in case of failures. + public static string DeleteFiles(IApplicationStatusInfo appStatus, Array arrPaths) + { + var strExceptions = string.Empty; + for (var i = 0; i < arrPaths.Length; i++) + { + var strPath = (arrPaths.GetValue(i) ?? string.Empty).ToString(); + var pos = strPath.IndexOf("'", StringComparison.Ordinal); + if (pos != -1) + { + // the (') represents a comment to the end of the line + strPath = strPath.Substring(0, pos); + } + + strPath = FixPath(strPath).TrimStart('\\'); + if (string.IsNullOrEmpty(strPath)) + { + continue; + } + + strPath = Path.Combine(appStatus.ApplicationMapPath, strPath); + if (strPath.EndsWith(@"\", StringComparison.Ordinal) && Directory.Exists(strPath)) + { + var directoryInfo = new System.IO.DirectoryInfo(strPath); + var applicationPath = $@"{appStatus.ApplicationMapPath}\"; + if (!directoryInfo.FullName.StartsWith(applicationPath, StringComparison.OrdinalIgnoreCase) || + directoryInfo.FullName.Equals(applicationPath, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + try + { + Globals.DeleteFolderRecursive(strPath); + } + catch (Exception ex) + { + Logger.Error(ex); + strExceptions += $"Processing folder ({strPath}) Error: {ex.Message}{Environment.NewLine}"; + } + } + else + { + if (!File.Exists(strPath)) + { + continue; + } + + try + { + File.SetAttributes(strPath, FileAttributes.Normal); + File.Delete(strPath); + } + catch (Exception ex) + { + Logger.Error(ex); + strExceptions += $"Processing file ({strPath}) Error: {ex.Message}{Environment.NewLine}"; + } + } + } + + return strExceptions; + } + + /// Deletes the files specified. + /// The application status. + /// An array of the file paths for the files to delete. + /// The cancellation token. + /// An empty string if succeeded or a list of errors in case of failures. + public static async Task DeleteFilesAsync(IApplicationStatusInfo appStatus, Array arrPaths, CancellationToken cancellationToken = default) + { + var strExceptions = string.Empty; + for (var i = 0; i < arrPaths.Length; i++) + { + var strPath = (arrPaths.GetValue(i) ?? string.Empty).ToString(); + var pos = strPath.IndexOf("'", StringComparison.Ordinal); + if (pos != -1) + { + // the (') represents a comment to the end of the line + strPath = strPath.Substring(0, pos); + } + + strPath = FixPath(strPath).TrimStart('\\'); + if (string.IsNullOrEmpty(strPath)) + { + continue; + } + + strPath = Path.Combine(appStatus.ApplicationMapPath, strPath); + if (strPath.EndsWith(@"\", StringComparison.Ordinal) && await Directory.ExistsAsync(strPath)) + { + var directoryInfo = new System.IO.DirectoryInfo(strPath); + var applicationPath = $@"{appStatus.ApplicationMapPath}\"; + if (!directoryInfo.FullName.StartsWith(applicationPath, StringComparison.OrdinalIgnoreCase) || + directoryInfo.FullName.Equals(applicationPath, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + try + { + await DeleteFolderRecursiveAsync(strPath, cancellationToken); + } + catch (Exception ex) + { + Logger.Error(ex); + strExceptions += $"Processing folder ({strPath}) Error: {ex.Message}{Environment.NewLine}"; + } + } + else + { + if (!await File.ExistsAsync(strPath)) + { + continue; + } + + try + { + await File.SetAttributesAsync(strPath, FileAttributes.Normal); + await File.DeleteAsync(strPath); + } + catch (Exception ex) + { + Logger.Error(ex); + strExceptions += $"Processing file ({strPath}) Error: {ex.Message}{Environment.NewLine}"; + } + } + } + + return strExceptions; + } + + /// Deletes files that match a filter recursively within folders. + /// The root path to filter from. + /// The filter to select the files to delete. + public static void DeleteFilesRecursive(string strRoot, string filter) + { + if (string.IsNullOrEmpty(strRoot)) + { + return; + } + + strRoot = FixPath(strRoot); + if (!Directory.Exists(strRoot)) + { + return; + } + + foreach (var strFolder in Directory.EnumerateDirectoryPaths(strRoot)) + { + var directory = new DirectoryInfo(strFolder); + if ((directory.Attributes & FileAttributes.Hidden) == 0 && (directory.Attributes & FileAttributes.System) == 0) + { + DeleteFilesRecursive(strFolder, filter); + } + } + + foreach (var strFile in Directory.EnumerateFilePaths(strRoot).Where(f => f.Contains(filter))) + { + try + { + DeleteFile(strFile); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + } + + /// Deletes files that match a filter recursively within folders. + /// The root path to filter from. + /// The filter to select the files to delete. + /// The cancellation token. + /// A indicating completion. + public static async Task DeleteFilesRecursiveAsync(string strRoot, string filter, CancellationToken cancellationToken = default) + { + if (string.IsNullOrEmpty(strRoot)) + { + return; + } + + strRoot = FixPath(strRoot); + if (!await Directory.ExistsAsync(strRoot)) + { + return; + } + + foreach (var strFolder in await Directory.EnumerateDirectoryPathsAsync(strRoot)) + { + cancellationToken.ThrowIfCancellationRequested(); + var directory = new DirectoryInfo(strFolder); + if ((directory.Attributes & FileAttributes.Hidden) == 0 && (directory.Attributes & FileAttributes.System) == 0) + { + await DeleteFilesRecursiveAsync(strFolder, filter, cancellationToken); + } + } + + foreach (var strFile in (await Directory.EnumerateFilePathsAsync(strRoot)).Where(f => f.Contains(filter))) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + await DeleteFileAsync(strFile); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + } + + /// Deletes a folder and all its child files and folders. + /// The root path to delete from. + public static void DeleteFolderRecursive(string strRoot) + { + strRoot = FixPath(strRoot); + if (string.IsNullOrEmpty(strRoot) || !Directory.Exists(strRoot)) + { + Logger.Info($"{strRoot} does not exist. "); + return; + } + + foreach (var strFolder in Directory.EnumerateDirectoryPaths(strRoot)) + { + DeleteFolderRecursive(strFolder); + } + + foreach (var strFile in Directory.EnumerateFilePaths(strRoot)) + { + try + { + DeleteFile(strFile); + } + catch (Exception ex) + { + Logger.Info($"{strRoot} does not exist."); + Logger.Error(ex); + } + } + + try + { + Directory.SetAttributes(strRoot, FileAttributes.Normal); + Directory.Delete(strRoot); + } + catch (Exception ex) + { + Logger.Info($"{strRoot} does not exist."); + Logger.Error(ex); + } + } + + /// Deletes a folder and all its child files and folders. + /// The root path to delete from. + /// The cancellation token. + /// A indicating completion. + public static async Task DeleteFolderRecursiveAsync(string strRoot, CancellationToken cancellationToken = default) + { + strRoot = FixPath(strRoot); + if (string.IsNullOrEmpty(strRoot) || !await Directory.ExistsAsync(strRoot)) + { + Logger.Info($"{strRoot} does not exist. "); + return; + } + + foreach (var strFolder in await Directory.EnumerateDirectoryPathsAsync(strRoot)) + { + cancellationToken.ThrowIfCancellationRequested(); + await DeleteFolderRecursiveAsync(strFolder, cancellationToken); + } + + foreach (var strFile in await Directory.EnumerateFilePathsAsync(strRoot)) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + await DeleteFileAsync(strFile); + } + catch (Exception ex) + { + Logger.Info($"{strRoot} does not exist."); + Logger.Error(ex); + } + } + + try + { + await Directory.SetAttributesAsync(strRoot, FileAttributes.Normal); + await Directory.DeleteAsync(strRoot); + } + catch (Exception ex) + { + Logger.Info($"{strRoot} does not exist."); + Logger.Error(ex); + } + } + + /// Deletes all empty folders beneath a given root folder and the root folder itself as well if empty. + /// The root folder path. + public static void DeleteEmptyFoldersRecursive(string path) + { + if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path)) + { + Logger.Info($"{path} does not exist."); + return; + } + + // first take care of folders + foreach (var folder in Directory.EnumerateDirectoryPaths(path)) + { + DeleteEmptyFoldersRecursive(folder); + } + + // if any files or folders left, return + if (Directory.EnumerateFileSystemEntries(path).Any()) + { + return; + } + + try + { + // delete this empty folder + Directory.SetAttributes(path, FileAttributes.Normal); + Directory.Delete(path); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + + /// Deletes all empty folders beneath a given root folder and the root folder itself as well if empty. + /// The root folder path. + /// The cancellation token. + /// A indicating completion. + public static async Task DeleteEmptyFoldersRecursiveAsync(string path, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(path) || !await Directory.ExistsAsync(path)) + { + Logger.Info($"{path} does not exist."); + return; + } + + // first take care of folders + foreach (var folder in await Directory.EnumerateDirectoryPathsAsync(path)) + { + cancellationToken.ThrowIfCancellationRequested(); + await DeleteEmptyFoldersRecursiveAsync(folder, cancellationToken); + } + + // if any files or folders left, return + if ((await Directory.EnumerateFileSystemEntriesAsync(path)).Any()) + { + return; + } + + try + { + // delete this empty folder + await Directory.SetAttributesAsync(path, FileAttributes.Normal); + await Directory.DeleteAsync(path); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + + /// Fixes the path in case the path separator is not windows style. + /// The path to fix. + /// A valid Windows path. + public static string FixPath(string input) + { + return string.IsNullOrEmpty(input) ? input : input.Trim().Replace("/", @"\"); + } + + /// Adds a file to a zip. + /// The zip file stream to add to. + /// The path to the file to add. + /// Name of the file to use in the zip entry. + /// The name of the folder to use in the zip entry.. + [DnnDeprecated(9, 11, 0, "Replaced with .NET compression types.")] + public static partial void AddToZip(ref ZipOutputStream zipFile, string filePath, string fileName, string folder) + { + FileStream fs = null; + try + { + // Open File Stream + fs = File.OpenRead(FixPath(filePath)); + + // Read file into byte array buffer + var buffer = new byte[fs.Length]; + + var len = fs.Read(buffer, 0, buffer.Length); + if (len != fs.Length) + { + Logger.ErrorFormat( + CultureInfo.InvariantCulture, + "Reading from {0} didn't read all data in buffer. Requested to read {1} bytes, but was read {2} bytes", + filePath, + fs.Length, + len); + } + + // Create Zip Entry + var entry = new ZipEntry(Path.Combine(folder, fileName)); + entry.DateTime = DateTime.Now; + entry.Size = fs.Length; + fs.Close(); + + // Compress file and add to Zip file + zipFile.PutNextEntry(entry); + zipFile.Write(buffer, 0, buffer.Length); + } + finally + { + if (fs != null) + { + fs.Close(); + fs.Dispose(); + } + } + } + + /// Unzips a resources zip file. + /// The zip stream. + /// The destination path to extract to. + [DnnDeprecated(9, 11, 0, "Replaced with .NET compression types.")] + public static partial void UnzipResources(ZipInputStream zipStream, string destPath) + { + try + { + var zipEntry = zipStream.GetNextEntry(); + while (zipEntry != null) + { + zipEntry.CheckZipEntry(); + HtmlUtils.WriteKeepAlive(); + var localFileName = zipEntry.Name; + var relativeDir = Path.GetDirectoryName(zipEntry.Name); + if (!string.IsNullOrEmpty(relativeDir) && (!Directory.Exists(Path.Combine(destPath, relativeDir)))) + { + Directory.Create(Path.Combine(destPath, relativeDir), true); + } + + if (!zipEntry.IsDirectory && (!string.IsNullOrEmpty(localFileName))) + { + var fileNamePath = FixPath(Path.Combine(destPath, localFileName)); + try + { + if (File.Exists(fileNamePath)) + { + File.SetAttributes(fileNamePath, FileAttributes.Normal); + File.Delete(fileNamePath); + } + + FileStream objFileStream = null; + try + { + File.Create(fileNamePath); + objFileStream = File.Open(fileNamePath); + var arrData = new byte[2048]; + var intSize = zipStream.Read(arrData, 0, arrData.Length); + while (intSize > 0) + { + objFileStream.Write(arrData, 0, intSize); + intSize = zipStream.Read(arrData, 0, arrData.Length); + } + } + finally + { + if (objFileStream != null) + { + objFileStream.Close(); + objFileStream.Dispose(); + } + } + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + + zipEntry = zipStream.GetNextEntry(); + } + } + finally + { + if (zipStream != null) + { + zipStream.Close(); + zipStream.Dispose(); + } + } + } + } +} diff --git a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs index 6d133caf9ab..762688aa79a 100644 --- a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs @@ -125,7 +125,7 @@ public static string FormatEmail(string email, bool cloak) { if (email.IndexOf("@", StringComparison.Ordinal) != -1) { - formatEmail = string.Format("{0}", email); + formatEmail = $"{email}"; } else { @@ -554,16 +554,16 @@ public static string AbsoluteToRelativeUrls(string html, IEnumerable ali foreach (string portalAlias in aliases) { string searchAlias = portalAlias; - if (!portalAlias.EndsWith("/")) + if (!portalAlias.EndsWith("/", StringComparison.Ordinal)) { - searchAlias = string.Format("{0}/", portalAlias); + searchAlias = $"{portalAlias}/"; } var exp = new Regex("((?:href|src)=")https?://" + searchAlias + "(.*?")", RegexOptions.IgnoreCase); - if (portalAlias.Contains("/")) + if (portalAlias.Contains("/", StringComparison.Ordinal)) { - html = exp.Replace(html, "$1" + portalAlias.Substring(portalAlias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase)) + "/$2"); + html = exp.Replace(html, "$1" + portalAlias.Substring(portalAlias.IndexOf("/", StringComparison.Ordinal)) + "/$2"); } else { diff --git a/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs b/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs index 220031db327..940bf78b46c 100644 --- a/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs +++ b/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs @@ -5,9 +5,12 @@ using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; +using System.Diagnostics.CodeAnalysis; using System.Text; using System.Web; +[SuppressMessage("Microsoft.Design", "CA1050:DeclareTypesInNamespaces", Justification = "Breaking change")] +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public class JavaScriptObjectDictionary : IEnumerable> { private OrderedDictionary dictionary; diff --git a/DNN Platform/Library/Common/Utilities/JavaScriptUtils.cs b/DNN Platform/Library/Common/Utilities/JavaScriptUtils.cs index 4533d372516..2bb955bd2b2 100644 --- a/DNN Platform/Library/Common/Utilities/JavaScriptUtils.cs +++ b/DNN Platform/Library/Common/Utilities/JavaScriptUtils.cs @@ -2,37 +2,37 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Common.Utilities -{ - using System; - using System.Web.UI; +namespace DotNetNuke.Common.Utilities +{ + using System; + using System.Web.UI; - using DotNetNuke.Framework; + using DotNetNuke.Framework; - public class JavaScriptUtils : ServiceLocator, IJavaScriptUtils + public class JavaScriptUtils : ServiceLocator, IJavaScriptUtils { /// - public void RegisterJavascriptVariable(string variableName, object value, Page page, Type type) - { - var valueAsJson = Json.Serialize(value); - - var script = string.Format("var {0} = {1};", variableName, valueAsJson); - - if (ScriptManager.GetCurrent(page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(page, type, variableName, script, true); - } - else - { - page.ClientScript.RegisterStartupScript(type, variableName, script, true); - } + public void RegisterJavascriptVariable(string variableName, object value, Page page, Type type) + { + var valueAsJson = Json.Serialize(value); + + var script = $"var {variableName} = {valueAsJson};"; + + if (ScriptManager.GetCurrent(page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(page, type, variableName, script, true); + } + else + { + page.ClientScript.RegisterStartupScript(type, variableName, script, true); + } } /// - protected override Func GetFactory() - { - return () => new JavaScriptUtils(); - } - } -} + protected override Func GetFactory() + { + return () => new JavaScriptUtils(); + } + } +} diff --git a/DNN Platform/Library/Common/Utilities/NetworkUtils.cs b/DNN Platform/Library/Common/Utilities/NetworkUtils.cs index 7ed5a8b2e54..7ecf4969f78 100644 --- a/DNN Platform/Library/Common/Utilities/NetworkUtils.cs +++ b/DNN Platform/Library/Common/Utilities/NetworkUtils.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Common.Utils { using System; + using System.Globalization; using System.Linq; using System.Net; using System.Net.Sockets; @@ -100,7 +101,7 @@ public static string LongToIp(long ip) { ipByte[x] = Convert.ToByte((ip & mask8) >> ((3 - x) * 8)); mask8 = mask8 >> 8; - addr += ipByte[x].ToString() + "."; + addr += ipByte[x].ToString(CultureInfo.InvariantCulture) + "."; // add current octet to string } @@ -143,14 +144,14 @@ public static string FormatAsCidr(string startIP, string subnetMask) oneBit = oneBit >> 1; } - string answer = LongToIp(ipL & maskL) + " /" + cidr.ToString(); + string answer = $"{LongToIp(ipL & maskL)} /{cidr.ToString(CultureInfo.InvariantCulture)}"; return answer; } - /// Network2s the ip range. + /// Converts a network to its IP range. /// The network name. - /// The start ip. - /// The end ip. + /// The start IP. + /// The end IP. public static void Network2IpRange(string sNetwork, out uint startIP, out uint endIP) { try @@ -158,7 +159,7 @@ public static void Network2IpRange(string sNetwork, out uint startIP, out uint e string[] elements = sNetwork.Split('/'); uint ip = IP2Int(elements[0]); - int bits = Convert.ToInt32(elements[1]); + int bits = Convert.ToInt32(elements[1], CultureInfo.InvariantCulture); uint mask = ~(0xffffffff >> bits); @@ -194,10 +195,10 @@ public static uint IP2Int(string ipNumber) string[] elements = ipNumber.Split('.'); if (elements.Length == 4) { - ip = Convert.ToUInt32(elements[0]) << 24; - ip += Convert.ToUInt32(elements[1]) << 16; - ip += Convert.ToUInt32(elements[2]) << 8; - ip += Convert.ToUInt32(elements[3]); + ip = Convert.ToUInt32(elements[0], CultureInfo.InvariantCulture) << 24; + ip += Convert.ToUInt32(elements[1], CultureInfo.InvariantCulture) << 16; + ip += Convert.ToUInt32(elements[2], CultureInfo.InvariantCulture) << 8; + ip += Convert.ToUInt32(elements[3], CultureInfo.InvariantCulture); } return ip; diff --git a/DNN Platform/Library/Common/Utilities/Null.cs b/DNN Platform/Library/Common/Utilities/Null.cs index 0cae1dba9a0..ba0660110ee 100644 --- a/DNN Platform/Library/Common/Utilities/Null.cs +++ b/DNN Platform/Library/Common/Utilities/Null.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Common.Utilities { using System; + using System.Globalization; using System.Reflection; public class Null @@ -210,39 +211,39 @@ public static object SetNull(PropertyInfo objPropertyInfo) public static bool SetNullBoolean(object objValue) { - return objValue != DBNull.Value ? Convert.ToBoolean(objValue) : NullBoolean; + return objValue != DBNull.Value ? Convert.ToBoolean(objValue, CultureInfo.InvariantCulture) : NullBoolean; } public static DateTime SetNullDateTime(object objValue) { - return objValue != DBNull.Value ? Convert.ToDateTime(objValue) : NullDate; + return objValue != DBNull.Value ? Convert.ToDateTime(objValue, CultureInfo.InvariantCulture) : NullDate; } public static DateTime SetNullDateTime(object objValue, DateTimeKind dateTimeKind) { return objValue != DBNull.Value - ? DateTime.SpecifyKind(Convert.ToDateTime(objValue), dateTimeKind) + ? DateTime.SpecifyKind(Convert.ToDateTime(objValue, CultureInfo.InvariantCulture), dateTimeKind) : NullDate; } public static int SetNullInteger(object objValue) { - return objValue != DBNull.Value ? Convert.ToInt32(objValue) : NullInteger; + return objValue != DBNull.Value ? Convert.ToInt32(objValue, CultureInfo.InvariantCulture) : NullInteger; } public static float SetNullSingle(object objValue) { - return objValue != DBNull.Value ? Convert.ToSingle(objValue) : NullSingle; + return objValue != DBNull.Value ? Convert.ToSingle(objValue, CultureInfo.InvariantCulture) : NullSingle; } public static string SetNullString(object objValue) { - return objValue != DBNull.Value ? Convert.ToString(objValue) : NullString; + return objValue != DBNull.Value ? Convert.ToString(objValue, CultureInfo.InvariantCulture) : NullString; } public static Guid SetNullGuid(object objValue) { - if ((!(objValue == DBNull.Value)) && !string.IsNullOrEmpty(objValue.ToString())) + if ((objValue != DBNull.Value) && !string.IsNullOrEmpty(objValue.ToString())) { return new Guid(objValue.ToString()); } @@ -252,6 +253,9 @@ public static Guid SetNullGuid(object objValue) // convert an application encoded null value to a database null value ( used in DAL ) public static object GetNull(object objField, object objDBNull) + => GetNull(objField, objDBNull, CultureInfo.CurrentCulture); + + public static object GetNull(object objField, object objDBNull, IFormatProvider provider) { object returnValue = objField; if (objField == null) @@ -260,42 +264,42 @@ public static object GetNull(object objField, object objDBNull) } else if (objField is byte) { - if (Convert.ToByte(objField) == NullByte) + if (Convert.ToByte(objField, provider) == NullByte) { returnValue = objDBNull; } } else if (objField is short) { - if (Convert.ToInt16(objField) == NullShort) + if (Convert.ToInt16(objField, provider) == NullShort) { returnValue = objDBNull; } } else if (objField is int) { - if (Convert.ToInt32(objField) == NullInteger) + if (Convert.ToInt32(objField, provider) == NullInteger) { returnValue = objDBNull; } } else if (objField is float) { - if (Convert.ToSingle(objField) == NullSingle) + if (Convert.ToSingle(objField, provider) == NullSingle) { returnValue = objDBNull; } } else if (objField is double) { - if (Convert.ToDouble(objField) == NullDouble) + if (Convert.ToDouble(objField, provider) == NullDouble) { returnValue = objDBNull; } } else if (objField is decimal) { - if (Convert.ToDecimal(objField) == NullDecimal) + if (Convert.ToDecimal(objField, provider) == NullDecimal) { returnValue = objDBNull; } @@ -303,7 +307,7 @@ public static object GetNull(object objField, object objDBNull) else if (objField is DateTime) { // compare the Date part of the DateTime with the DatePart of the NullDate ( this avoids subtle time differences ) - if (Convert.ToDateTime(objField).Date == NullDate.Date) + if (Convert.ToDateTime(objField, provider).Date == NullDate.Date) { returnValue = objDBNull; } @@ -324,14 +328,14 @@ public static object GetNull(object objField, object objDBNull) } else if (objField is bool) { - if (Convert.ToBoolean(objField) == NullBoolean) + if (Convert.ToBoolean(objField, provider) == NullBoolean) { returnValue = objDBNull; } } - else if (objField is Guid) + else if (objField is Guid guid) { - if (((Guid)objField).Equals(NullGuid)) + if (guid.Equals(NullGuid)) { returnValue = objDBNull; } @@ -370,9 +374,8 @@ public static bool IsNull(object objField) { isNull = objField.Equals(NullDecimal); } - else if (objField is DateTime) + else if (objField is DateTime objDate) { - var objDate = (DateTime)objField; isNull = objDate.Date.Equals(NullDate.Date); } else if (objField is string) diff --git a/DNN Platform/Library/Common/Utilities/PathUtils.cs b/DNN Platform/Library/Common/Utilities/PathUtils.cs index ebd418442b1..71487a90457 100644 --- a/DNN Platform/Library/Common/Utilities/PathUtils.cs +++ b/DNN Platform/Library/Common/Utilities/PathUtils.cs @@ -39,7 +39,7 @@ public virtual string AddTrailingSlash(string source) { Requires.PropertyNotNull("source", source); - return source.EndsWith("\\") ? source : source + "\\"; + return source.EndsWith(@"\", StringComparison.Ordinal) ? source : $@"{source}\"; } /// @@ -52,7 +52,7 @@ public virtual string FormatFolderPath(string folderPath) return string.Empty; } - return folderPath.EndsWith("/") ? folderPath.Trim() : folderPath.Trim() + "/"; + return folderPath.EndsWith("/", StringComparison.Ordinal) ? folderPath.Trim() : folderPath.Trim() + "/"; } /// @@ -61,7 +61,7 @@ public virtual string GetPhysicalPath(int portalID, string relativePath) Requires.PropertyNotNull("relativePath", relativePath); var path1 = this.GetRootFolderMapPath(portalID); - var path2 = relativePath.Replace("/", "\\"); + var path2 = relativePath.Replace("/", @"\"); if (Path.IsPathRooted(path2)) { @@ -96,7 +96,7 @@ public virtual string GetRelativePath(int portalID, string physicalPath) relativePath = relativePath.TrimStart(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); } - relativePath = relativePath.Replace("\\", "/"); + relativePath = relativePath.Replace(@"\", "/"); } else { @@ -140,21 +140,21 @@ public virtual string MapPath(string path) var applicationPath = Globals.ApplicationPath; var applicationMapPath = Globals.ApplicationMapPath; - if (applicationPath.Length > 1 && convertedPath.StartsWith(applicationPath)) + if (applicationPath.Length > 1 && convertedPath.StartsWith(applicationPath, StringComparison.OrdinalIgnoreCase)) { convertedPath = convertedPath.Substring(applicationPath.Length); } - convertedPath = convertedPath.Replace("/", "\\"); + convertedPath = convertedPath.Replace("/", @"\"); - if (path.StartsWith("~") | path.StartsWith(".") | path.StartsWith("/")) + if (path.StartsWith("~", StringComparison.Ordinal) | path.StartsWith(".", StringComparison.Ordinal) | path.StartsWith("/", StringComparison.Ordinal)) { convertedPath = convertedPath.Length > 1 ? string.Concat(this.AddTrailingSlash(applicationMapPath), convertedPath.Substring(1)) : applicationMapPath; } convertedPath = Path.GetFullPath(convertedPath); - if (!convertedPath.StartsWith(applicationMapPath)) + if (!convertedPath.StartsWith(applicationMapPath, StringComparison.OrdinalIgnoreCase)) { throw new HttpException(); } @@ -170,7 +170,7 @@ public virtual string RemoveTrailingSlash(string source) return string.Empty; } - if (source.EndsWith("\\") || source.EndsWith("/")) + if (source.EndsWith(@"\", StringComparison.Ordinal) || source.EndsWith("/", StringComparison.Ordinal)) { return source.Substring(0, source.Length - 1); } @@ -183,7 +183,7 @@ public virtual string StripFolderPath(string originalPath) { Requires.PropertyNotNull("originalPath", originalPath); - if (originalPath.IndexOf("\\", StringComparison.InvariantCulture) >= 0) + if (originalPath.IndexOf(@"\", StringComparison.InvariantCulture) >= 0) { return FolderPathRx.Replace(originalPath, string.Empty); } @@ -202,11 +202,11 @@ internal static string GetUserFolderPathElement(int userId, UserFolderElement mo return mode switch { - UserFolderElement.Root => (Convert.ToInt32(userId) & ByteOffset).ToString("000"), + UserFolderElement.Root => (userId & ByteOffset).ToString("000", CultureInfo.InvariantCulture), UserFolderElement.SubFolder => - userId.ToString("00") + userId.ToString("00", CultureInfo.InvariantCulture) .Substring( - userId.ToString("00").Length - SubfolderSeedLength, + userId.ToString("00", CultureInfo.InvariantCulture).Length - SubfolderSeedLength, SubfolderSeedLength), _ => string.Empty, }; @@ -222,7 +222,7 @@ internal static string GetUserFolderPathInternal(UserInfo user) var fullPath = Path.Combine(Path.Combine(rootFolder, subFolder), user.UserID.ToString(CultureInfo.InvariantCulture)); - return $"Users/{fullPath.Replace("\\", "/")}/"; + return $"Users/{fullPath.Replace(@"\", "/")}/"; } private static string GetHostMapPath() diff --git a/DNN Platform/Library/Common/Utilities/RegexUtils.cs b/DNN Platform/Library/Common/Utilities/RegexUtils.cs index b5e8d054113..9f63fc98cac 100644 --- a/DNN Platform/Library/Common/Utilities/RegexUtils.cs +++ b/DNN Platform/Library/Common/Utilities/RegexUtils.cs @@ -30,7 +30,7 @@ public static Regex GetCachedRegex(string pattern, RegexOptions options = RegexO // // should not allow for compiled dynamic regex object options &= ~RegexOptions.Compiled; - key = string.Join(":", "REGEX_ITEM", options.ToString("X"), key.GetHashCode().ToString("X")); + key = string.Join(":", "REGEX_ITEM", options.ToString("X"), key.GetHashCode().ToString("X", CultureInfo.InvariantCulture)); // limit timeout between 1 and 10 seconds if (timeoutSeconds < 1) @@ -43,8 +43,7 @@ public static Regex GetCachedRegex(string pattern, RegexOptions options = RegexO } var cache = CachingProvider.Instance(); - var regex = cache.GetItem(key) as Regex; - if (regex == null) + if (cache.GetItem(key) is not Regex regex) { regex = new Regex(pattern, options & ~RegexOptions.Compiled, TimeSpan.FromSeconds(timeoutSeconds)); cache.Insert(key, regex, (DNNCacheDependency)null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10), CacheItemPriority.BelowNormal, null); diff --git a/DNN Platform/Library/Common/Utilities/RetryableAction.cs b/DNN Platform/Library/Common/Utilities/RetryableAction.cs index 2342301726b..3428446976b 100644 --- a/DNN Platform/Library/Common/Utilities/RetryableAction.cs +++ b/DNN Platform/Library/Common/Utilities/RetryableAction.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Common.Utilities.Internal { using System; + using System.Globalization; using System.Threading; using DotNetNuke.Instrumentation; @@ -42,7 +43,7 @@ public RetryableAction(Action action, string description, int maxRetries, TimeSp { if (delay.TotalMilliseconds > int.MaxValue) { - throw new ArgumentException(string.Format("delay must be less than {0} milliseconds", int.MaxValue)); + throw new ArgumentException($"delay must be less than {int.MaxValue} milliseconds"); } this.Action = action; @@ -90,7 +91,7 @@ public static void Retry5TimesWith2SecondsDelay(Action action, string descriptio public void TryIt() { var currentDelay = (int)this.Delay.TotalMilliseconds; - int retrysRemaining = this.MaxRetries; + var retriesRemaining = this.MaxRetries; do { @@ -99,22 +100,22 @@ public void TryIt() this.Action(); if (Logger.IsTraceEnabled) { - Logger.TraceFormat("Action succeeded - {0}", this.Description); + Logger.TraceFormat(CultureInfo.InvariantCulture, "Action succeeded - {0}", this.Description); } return; } catch (Exception) { - if (retrysRemaining <= 0) + if (retriesRemaining <= 0) { - Logger.WarnFormat("All retries of action failed - {0}", this.Description); + Logger.WarnFormat(CultureInfo.InvariantCulture, "All retries of action failed - {0}", this.Description); throw; } if (Logger.IsTraceEnabled) { - Logger.TraceFormat("Retrying action {0} - {1}", retrysRemaining, this.Description); + Logger.TraceFormat(CultureInfo.InvariantCulture, "Retrying action {0} - {1}", retriesRemaining, this.Description); } SleepAction.Invoke(currentDelay); @@ -126,7 +127,7 @@ public void TryIt() } } - retrysRemaining--; + retriesRemaining--; } while (true); } diff --git a/DNN Platform/Library/Common/Utilities/UrlController.cs b/DNN Platform/Library/Common/Utilities/UrlController.cs index a8c3c51d398..a94f1772df6 100644 --- a/DNN Platform/Library/Common/Utilities/UrlController.cs +++ b/DNN Platform/Library/Common/Utilities/UrlController.cs @@ -71,12 +71,12 @@ public void DeleteUrl(int portalID, string url) public void UpdateUrlTracking(int portalID, string url, int moduleId, int userID) { TabType urlType = Globals.GetURLType(url); - if (urlType == TabType.File && url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) == false) + if (urlType == TabType.File && !url.StartsWith("fileid=", StringComparison.OrdinalIgnoreCase)) { // to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(url); - var folderPath = url.Substring(0, url.LastIndexOf(fileName)); + var folderPath = url.Substring(0, url.LastIndexOf(fileName, StringComparison.OrdinalIgnoreCase)); var folder = FolderManager.Instance.GetFolder(portalID, folderPath); var file = FileManager.Instance.GetFile(folder, fileName); diff --git a/DNN Platform/Library/Common/Utilities/UrlUtils.cs b/DNN Platform/Library/Common/Utilities/UrlUtils.cs index 7dc59227a33..202e50203a6 100644 --- a/DNN Platform/Library/Common/Utilities/UrlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/UrlUtils.cs @@ -315,7 +315,7 @@ public static string PopUpUrl(string url, Control control, PortalSettings portal } // Removes the javascript txt for onClick scripts - if (onClickEvent && popUpUrl.StartsWith("javascript:")) + if (onClickEvent && popUpUrl.StartsWith("javascript:", StringComparison.OrdinalIgnoreCase)) { popUpUrl = popUpUrl.Replace("javascript:", string.Empty); } diff --git a/DNN Platform/Library/Common/Utilities/XmlUtils.cs b/DNN Platform/Library/Common/Utilities/XmlUtils.cs index 4c4a547bac5..6373cf7d23d 100644 --- a/DNN Platform/Library/Common/Utilities/XmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/XmlUtils.cs @@ -119,12 +119,12 @@ public static Dictionary DeSerializeDictionary(Stream objSt foreach (XmlElement xmlItem in xmlDoc.SelectNodes(rootname + "/item")) { - int key = Convert.ToInt32(xmlItem.GetAttribute("key")); + int key = Convert.ToInt32(xmlItem.GetAttribute("key"), CultureInfo.InvariantCulture); var objValue = Activator.CreateInstance(); // Create the XmlSerializer - var xser = new XmlSerializer(objValue.GetType()); + var xmlSerializer = new XmlSerializer(objValue.GetType()); // A reader is needed to read the XML document. var reader = new XmlTextReader(new StringReader(xmlItem.InnerXml)) @@ -135,7 +135,7 @@ public static Dictionary DeSerializeDictionary(Stream objSt // Use the Deserialize method to restore the object's state, and store it // in the Hashtable - objDictionary.Add(key, (TValue)xser.Deserialize(reader)); + objDictionary.Add(key, (TValue)xmlSerializer.Deserialize(reader)); } return objDictionary; @@ -208,7 +208,7 @@ public static int GetAttributeValueAsInteger(XPathNavigator navigator, string at string strValue = GetAttributeValue(navigator, attributeName); if (!string.IsNullOrEmpty(strValue)) { - intValue = Convert.ToInt32(strValue); + intValue = Convert.ToInt32(strValue, CultureInfo.InvariantCulture); } return intValue; @@ -221,7 +221,7 @@ public static long GetAttributeValueAsLong(XPathNavigator navigator, string attr string strValue = GetAttributeValue(navigator, attributeName); if (!string.IsNullOrEmpty(strValue)) { - intValue = Convert.ToInt64(strValue); + intValue = Convert.ToInt64(strValue, CultureInfo.InvariantCulture); } return intValue; @@ -360,7 +360,7 @@ public static bool GetNodeValueBoolean(XPathNavigator navigator, string path, bo /// Child node to look for. /// Default value to return. /// The node value parsed as a or . - /// If the node does not exist or it causes any error the default value will be returned. + /// If the node does not exist, or it causes any error the default value will be returned. /// public static DateTime GetNodeValueDate(XmlNode objNode, string nodeName, DateTime defaultValue) { @@ -370,7 +370,7 @@ public static DateTime GetNodeValueDate(XmlNode objNode, string nodeName, DateTi string strValue = objNode[nodeName].InnerText; if (!string.IsNullOrEmpty(strValue)) { - dateValue = Convert.ToDateTime(strValue); + dateValue = Convert.ToDateTime(strValue, CultureInfo.InvariantCulture); if (dateValue.Date.Equals(Null.NullDate.Date)) { dateValue = Null.NullDate; @@ -401,7 +401,7 @@ public static DateTime GetNodeValueDate(XPathNavigator navigator, string path, D return defaultValue; } - var dateValue = Convert.ToDateTime(strValue); + var dateValue = Convert.ToDateTime(strValue, CultureInfo.InvariantCulture); if (dateValue.Date.Equals(Null.NullDate.Date)) { return Null.NullDate; @@ -414,7 +414,7 @@ public static DateTime GetNodeValueDate(XPathNavigator navigator, string path, D /// Parent node. /// Child node to look for. /// The node value parsed as an or 0. - /// If the node does not exist or it causes any error the default value (0) will be returned. + /// If the node does not exist, or it causes any error the default value (0) will be returned. /// public static int GetNodeValueInt(XmlNode node, string nodeName) { @@ -426,7 +426,7 @@ public static int GetNodeValueInt(XmlNode node, string nodeName) /// Child node to look for. /// Default value to return. /// The node value parsed as an or . - /// If the node does not exist or it causes any error the default value will be returned. + /// If the node does not exist, or it causes any error the default value will be returned. /// public static int GetNodeValueInt(XmlNode node, string nodeName, int defaultValue) { @@ -436,7 +436,7 @@ public static int GetNodeValueInt(XmlNode node, string nodeName, int defaultValu string strValue = node[nodeName].InnerText; if (!string.IsNullOrEmpty(strValue)) { - intValue = Convert.ToInt32(strValue); + intValue = Convert.ToInt32(strValue, CultureInfo.InvariantCulture); } } @@ -473,14 +473,14 @@ public static int GetNodeValueInt(XPathNavigator navigator, string path, int def return defaultValue; } - return Convert.ToInt32(strValue); + return Convert.ToInt32(strValue, CultureInfo.InvariantCulture); } /// Gets the value of node. /// Parent node. /// Child node to look for. /// The value of the node or 0 if the node doesn't exist or doesn't have a value. - /// If the node does not exist or it causes any error the default value (0) will be returned. + /// If the node does not exist, or it causes any error the default value (0) will be returned. /// public static float GetNodeValueSingle(XmlNode node, string nodeName) { @@ -559,9 +559,6 @@ public static string SerializeDictionary(IDictionary source, string rootName) string strString; if (source.Count != 0) { - XmlSerializer xser; - StringWriter sw; - var xmlDoc = new XmlDocument { XmlResolver = null }; XmlElement xmlRoot = xmlDoc.CreateElement(rootName); xmlDoc.AppendChild(xmlRoot); @@ -572,14 +569,14 @@ public static string SerializeDictionary(IDictionary source, string rootName) XmlElement xmlItem = xmlDoc.CreateElement("item"); // Save the key name and the object type - xmlItem.SetAttribute("key", Convert.ToString(key)); + xmlItem.SetAttribute("key", Convert.ToString(key, CultureInfo.InvariantCulture)); xmlItem.SetAttribute("type", source[key].GetType().AssemblyQualifiedName); // Serialize the object var xmlObject = new XmlDocument { XmlResolver = null }; - xser = new XmlSerializer(source[key].GetType()); - sw = new StringWriter(); - xser.Serialize(sw, source[key]); + var xmlSerializer = new XmlSerializer(source[key].GetType()); + var sw = new StringWriter(); + xmlSerializer.Serialize(sw, source[key]); xmlObject.LoadXml(sw.ToString()); // import and append the node to the root diff --git a/DNN Platform/Library/Common/XmlValidatorBase.cs b/DNN Platform/Library/Common/XmlValidatorBase.cs index 4edb8bec1b8..295055e3674 100644 --- a/DNN Platform/Library/Common/XmlValidatorBase.cs +++ b/DNN Platform/Library/Common/XmlValidatorBase.cs @@ -3,48 +3,30 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Common { + using System; using System.Collections; using System.IO; using System.Xml; using System.Xml.Schema; /// Base class of XmlValidator. - public class XmlValidatorBase + public class XmlValidatorBase : IDisposable { - private readonly XmlSchemaSet schemaSet; - private ArrayList errs; private XmlTextReader reader; /// Initializes a new instance of the class. public XmlValidatorBase() { - this.errs = new ArrayList(); - this.schemaSet = new XmlSchemaSet(); + this.Errors = new ArrayList(); + this.SchemaSet = new XmlSchemaSet(); } /// Gets the schema set. - public XmlSchemaSet SchemaSet - { - get - { - return this.schemaSet; - } - } + public XmlSchemaSet SchemaSet { get; } /// Gets or sets the errors. /// The errors. - public ArrayList Errors - { - get - { - return this.errs; - } - - set - { - this.errs = value; - } - } + public ArrayList Errors { get; set; } /// Determines whether this instance is valid. /// if this instance is valid; otherwise, . @@ -53,11 +35,11 @@ public bool IsValid() // There is a bug here which I haven't been able to fix. // If the XML Instance does not include a reference to the // schema, then the validation fails. If the reference exists - // the the validation works correctly. + // the validation works correctly. // Create a validating reader var settings = new XmlReaderSettings(); - settings.Schemas = this.schemaSet; + settings.Schemas = this.SchemaSet; settings.ValidationType = ValidationType.Schema; // Set the validation event handler. @@ -70,7 +52,7 @@ public bool IsValid() } vreader.Close(); - return this.errs.Count == 0; + return this.Errors.Count == 0; } /// Validates the specified XML stream. @@ -100,12 +82,27 @@ public virtual bool Validate(string filename) return this.IsValid(); } + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.reader?.Dispose(); + } + } + /// Validations the call back. /// The sender. /// The instance containing the event data. protected void ValidationCallBack(object sender, ValidationEventArgs args) { - this.errs.Add(args.Message); + this.Errors.Add(args.Message); } } } diff --git a/DNN Platform/Library/ComponentModel/ComponentBase.cs b/DNN Platform/Library/ComponentModel/ComponentBase.cs index 767b45a1533..0697e534469 100644 --- a/DNN Platform/Library/ComponentModel/ComponentBase.cs +++ b/DNN Platform/Library/ComponentModel/ComponentBase.cs @@ -1,66 +1,69 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ComponentModel -{ +namespace DotNetNuke.ComponentModel +{ using System; + using System.Diagnostics.CodeAnalysis; /// A base class for a Dnn component. /// The contract type. /// The component type. public abstract class ComponentBase where TType : class, TContract - { - private static TContract testableInstance; - private static bool useTestable; + { + private static TContract testableInstance; + private static bool useTestable; - /// Gets an instance of the Component. - public static TContract Instance - { - get - { - if (useTestable && testableInstance != null) - { - return testableInstance; - } - - var component = ComponentFactory.GetComponent(); - - if (component == null) - { - component = (TContract)Activator.CreateInstance(typeof(TType), true); - ComponentFactory.RegisterComponentInstance(component); - } - - return component; - } - } + /// Gets an instance of the Component. + [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "Breaking change")] + public static TContract Instance + { + get + { + if (useTestable && testableInstance != null) + { + return testableInstance; + } + + var component = ComponentFactory.GetComponent(); + + if (component == null) + { + component = (TContract)Activator.CreateInstance(typeof(TType), true); + ComponentFactory.RegisterComponentInstance(component); + } + + return component; + } + } /// Registers an instance of a component. - /// The instance to register. - public static void RegisterInstance(TContract instance) - { - if (ComponentFactory.GetComponent() == null) - { - ComponentFactory.RegisterComponentInstance(instance); - } - } - - /// Registers an instance to use for the Singleton. - /// Intended for unit testing purposes, not thread safe. - /// The instance to set. - internal static void SetTestableInstance(TContract instance) - { - testableInstance = instance; - useTestable = true; - } - - /// Clears the current instance, a new instance will be initialized when next requested. - /// Intended for unit testing purposes, not thread safe. - internal static void ClearInstance() - { - useTestable = false; - testableInstance = default(TContract); - } - } -} + /// The instance to register. + [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "Breaking change")] + public static void RegisterInstance(TContract instance) + { + if (ComponentFactory.GetComponent() == null) + { + ComponentFactory.RegisterComponentInstance(instance); + } + } + + /// Registers an instance to use for the Singleton. + /// Intended for unit testing purposes, not thread safe. + /// The instance to set. + internal static void SetTestableInstance(TContract instance) + { + testableInstance = instance; + useTestable = true; + } + + /// Clears the current instance, a new instance will be initialized when next requested. + /// Intended for unit testing purposes, not thread safe. + internal static void ClearInstance() + { + useTestable = false; + testableInstance = default(TContract); + } + } +} diff --git a/DNN Platform/Library/ComponentModel/ComponentBuilderCollection.cs b/DNN Platform/Library/ComponentModel/ComponentBuilderCollection.cs index 721e853a628..16dadb4ee49 100644 --- a/DNN Platform/Library/ComponentModel/ComponentBuilderCollection.cs +++ b/DNN Platform/Library/ComponentModel/ComponentBuilderCollection.cs @@ -1,25 +1,25 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ComponentModel -{ +namespace DotNetNuke.ComponentModel +{ using DotNetNuke.Collections.Internal; - internal class ComponentBuilderCollection : SharedDictionary - { - internal IComponentBuilder DefaultBuilder { get; set; } - - internal void AddBuilder(IComponentBuilder builder, bool setDefault) - { - if (!this.ContainsKey(builder.Name)) - { - this[builder.Name] = builder; - - if (setDefault && this.DefaultBuilder == null) - { - this.DefaultBuilder = builder; - } - } - } - } -} + internal class ComponentBuilderCollection : SharedDictionary + { + internal IComponentBuilder DefaultBuilder { get; set; } + + internal void AddBuilder(IComponentBuilder builder, bool setDefault) + { + if (!this.ContainsKey(builder.Name)) + { + this[builder.Name] = builder; + + if (setDefault && this.DefaultBuilder == null) + { + this.DefaultBuilder = builder; + } + } + } + } +} diff --git a/DNN Platform/Library/ComponentModel/ComponentType.cs b/DNN Platform/Library/ComponentModel/ComponentType.cs index 3275f3b5e4a..56d5a89c2e8 100644 --- a/DNN Platform/Library/ComponentModel/ComponentType.cs +++ b/DNN Platform/Library/ComponentModel/ComponentType.cs @@ -1,36 +1,27 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ComponentModel -{ +namespace DotNetNuke.ComponentModel +{ using System; - internal class ComponentType - { - private readonly Type baseType; - private readonly ComponentBuilderCollection componentBuilders = new ComponentBuilderCollection(); - - /// Initializes a new instance of the class. - /// The base type of Components of this ComponentType. - public ComponentType(Type baseType) - { - this.baseType = baseType; - } - - public Type BaseType - { - get - { - return this.baseType; - } - } - - public ComponentBuilderCollection ComponentBuilders - { - get - { - return this.componentBuilders; - } - } - } -} + internal sealed class ComponentType : IDisposable + { + /// Initializes a new instance of the class. + /// The base type of Components of this ComponentType. + public ComponentType(Type baseType) + { + this.BaseType = baseType; + } + + public Type BaseType { get; } + + public ComponentBuilderCollection ComponentBuilders { get; } = new ComponentBuilderCollection(); + + /// + public void Dispose() + { + this.ComponentBuilders?.Dispose(); + } + } +} diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs index 13eca466692..197b7823bd2 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs @@ -1,68 +1,59 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ComponentModel.DataAnnotations -{ - using System; +namespace DotNetNuke.ComponentModel.DataAnnotations +{ + using System; using System.Web.Caching; - public class CacheableAttribute : Attribute - { - /// - /// Initializes a new instance of the class. - /// Construct a new CacheableAttribute. - /// - public CacheableAttribute() - { - this.CachePriority = CacheItemPriority.Default; - this.CacheTimeOut = 20; - } - - /// - /// Initializes a new instance of the class. - /// Construct a new CacheableAttribute. - /// - /// The cacheKey to use. - public CacheableAttribute(string cacheKey) - : this(cacheKey, CacheItemPriority.Default, 20) - { - } - - /// - /// Initializes a new instance of the class. - /// Construct a new CacheableAttribute. - /// - /// The cacheKey to use. - /// The priority of the cached item. - public CacheableAttribute(string cacheKey, CacheItemPriority priority) - : this(cacheKey, priority, 20) - { - } - - /// - /// Initializes a new instance of the class. - /// Construct a new CacheableAttribute. - /// - /// The cacheKey to use. - /// The priority of the cached item. - /// The timeout multiplier used to cache the item. - public CacheableAttribute(string cacheKey, CacheItemPriority priority, int timeOut) - { - this.CacheKey = cacheKey; - this.CachePriority = priority; - this.CacheTimeOut = timeOut; - } - - /// Gets or sets the root key to use for the cache. - public string CacheKey { get; set; } - - /// Gets or sets the priority of the cached item. The default value is CacheItemPriority.Default. - public CacheItemPriority CachePriority { get; set; } - - /// - /// Gets or sets the timeout multiplier used to cache the item. This value is multiple by the Host - /// Performance Setting to determine the actual timeout value. The default value is 20. - /// - public int CacheTimeOut { get; set; } - } -} + using DotNetNuke.Abstractions.Application; + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] + public class CacheableAttribute : Attribute + { + /// Initializes a new instance of the class. + public CacheableAttribute() + { + this.CachePriority = CacheItemPriority.Default; + this.CacheTimeOut = 20; + } + + /// Initializes a new instance of the class. + /// The cacheKey to use. + public CacheableAttribute(string cacheKey) + : this(cacheKey, CacheItemPriority.Default, 20) + { + } + + /// Initializes a new instance of the class. + /// The cacheKey to use. + /// The priority of the cached item. + public CacheableAttribute(string cacheKey, CacheItemPriority priority) + : this(cacheKey, priority, 20) + { + } + + /// Initializes a new instance of the class. + /// The cacheKey to use. + /// The priority of the cached item. + /// The timeout multiplier used to cache the item. + public CacheableAttribute(string cacheKey, CacheItemPriority priority, int timeOut) + { + this.CacheKey = cacheKey; + this.CachePriority = priority; + this.CacheTimeOut = timeOut; + } + + /// Gets or sets the root key to use for the cache. + public string CacheKey { get; set; } + + /// Gets or sets the priority of the cached item. The default value is CacheItemPriority.Default. + public CacheItemPriority CachePriority { get; set; } + + /// + /// Gets or sets the timeout multiplier used to cache the item. This value is multiplied by the + /// to determine the actual timeout value. The default value is 20. + /// + public int CacheTimeOut { get; set; } + } +} diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/ColumnNameAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/ColumnNameAttribute.cs index 43651b99ed9..7555ef43221 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/ColumnNameAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/ColumnNameAttribute.cs @@ -4,7 +4,8 @@ namespace DotNetNuke.ComponentModel.DataAnnotations { using System; - + + [AttributeUsage(AttributeTargets.Property)] public class ColumnNameAttribute : Attribute { /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs index 5e4a56f5857..cfd0abda1cd 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ComponentModel.DataAnnotations -{ - using System; +namespace DotNetNuke.ComponentModel.DataAnnotations +{ + using System; - public class DeclareColumnsAttribute : Attribute + [AttributeUsage(AttributeTargets.Property)] + public class DeclareColumnsAttribute : Attribute { } -} +} diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs index b77c52a97d2..7f1416bccce 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ComponentModel.DataAnnotations -{ - using System; +namespace DotNetNuke.ComponentModel.DataAnnotations +{ + using System; - public class IgnoreColumnAttribute : Attribute + [AttributeUsage(AttributeTargets.Property)] + public class IgnoreColumnAttribute : Attribute { } -} +} diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs index de3b21cd390..98b1a0c6743 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ComponentModel.DataAnnotations -{ - using System; +namespace DotNetNuke.ComponentModel.DataAnnotations +{ + using System; - public class IncludeColumnAttribute : Attribute + [AttributeUsage(AttributeTargets.Property)] + public class IncludeColumnAttribute : Attribute { } -} +} diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs index aa97b6a6175..98127041192 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs @@ -4,7 +4,8 @@ namespace DotNetNuke.ComponentModel.DataAnnotations { using System; - + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class PrimaryKeyAttribute : Attribute { /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs index c40b53fded0..2ccaf793743 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ComponentModel.DataAnnotations -{ - using System; +namespace DotNetNuke.ComponentModel.DataAnnotations +{ + using System; - public class ReadOnlyColumnAttribute : Attribute + [AttributeUsage(AttributeTargets.Property)] + public class ReadOnlyColumnAttribute : Attribute { } -} +} diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/ScopeAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/ScopeAttribute.cs index 94e0a7d2403..721e5f42cc1 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/ScopeAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/ScopeAttribute.cs @@ -5,7 +5,8 @@ namespace DotNetNuke.ComponentModel.DataAnnotations { using System; - + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class ScopeAttribute : Attribute { /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/TableNameAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/TableNameAttribute.cs index 45ae5a369b0..3926fa33809 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/TableNameAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/TableNameAttribute.cs @@ -4,7 +4,8 @@ namespace DotNetNuke.ComponentModel.DataAnnotations { using System; - + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class TableNameAttribute : Attribute { /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/ComponentModel/ProviderInstaller.cs b/DNN Platform/Library/ComponentModel/ProviderInstaller.cs index 98834d2a35c..a8ed975a9a0 100644 --- a/DNN Platform/Library/ComponentModel/ProviderInstaller.cs +++ b/DNN Platform/Library/ComponentModel/ProviderInstaller.cs @@ -95,7 +95,7 @@ private void InstallProvider(IContainer container, Provider provider) if (type == null) { - Logger.Error(new ConfigurationErrorsException(string.Format("Could not load provider {0}", provider.Type))); + Logger.Error(new ConfigurationErrorsException($"Could not load provider {provider.Type}")); } else { diff --git a/DNN Platform/Library/ComponentModel/SimpleContainer.cs b/DNN Platform/Library/ComponentModel/SimpleContainer.cs index d01710645fb..baaf3e5fc97 100644 --- a/DNN Platform/Library/ComponentModel/SimpleContainer.cs +++ b/DNN Platform/Library/ComponentModel/SimpleContainer.cs @@ -6,10 +6,11 @@ namespace DotNetNuke.ComponentModel using System; using System.Collections; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Collections.Internal; - public class SimpleContainer : AbstractContainer + public class SimpleContainer : AbstractContainer, IDisposable { private readonly string name; private readonly ComponentBuilderCollection componentBuilders = new ComponentBuilderCollection(); @@ -22,7 +23,7 @@ public class SimpleContainer : AbstractContainer /// Initializes a new instance of the class. public SimpleContainer() - : this(string.Format("Container_{0}", Guid.NewGuid())) + : this($"Container_{Guid.NewGuid()}") { } @@ -43,6 +44,7 @@ public override string Name } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override void RegisterComponent(string name, Type type) { using (this.registeredComponents.GetWriteLock()) @@ -133,6 +135,7 @@ public override IDictionary GetComponentSettings(string name) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override void RegisterComponent(string name, Type contractType, Type type, ComponentLifeStyleType lifestyle) { this.AddComponentType(contractType); @@ -172,6 +175,24 @@ public override void RegisterComponentSettings(string name, IDictionary dependen } } + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.componentBuilders?.Dispose(); + this.componentDependencies?.Dispose(); + this.componentTypes?.Dispose(); + this.registeredComponents?.Dispose(); + } + } + private static object GetComponent(IComponentBuilder builder) { object component; diff --git a/DNN Platform/Library/Data/ControllerBase.cs b/DNN Platform/Library/Data/ControllerBase.cs index 88c7cc36f38..679846aa63b 100644 --- a/DNN Platform/Library/Data/ControllerBase.cs +++ b/DNN Platform/Library/Data/ControllerBase.cs @@ -14,6 +14,7 @@ public abstract class ControllerBase : ServiceLocator where TEntity : class { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected readonly IDataContext DataContext; /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/Data/DataProvider.cs b/DNN Platform/Library/Data/DataProvider.cs index caa2a54970a..1f31d1f7cad 100644 --- a/DNN Platform/Library/Data/DataProvider.cs +++ b/DNN Platform/Library/Data/DataProvider.cs @@ -58,7 +58,7 @@ public virtual string DatabaseOwner get { string databaseOwner = this.Settings["databaseOwner"]; - if (!string.IsNullOrEmpty(databaseOwner) && databaseOwner.EndsWith(".") == false) + if (!string.IsNullOrEmpty(databaseOwner) && !databaseOwner.EndsWith(".", StringComparison.Ordinal)) { databaseOwner += "."; } @@ -77,7 +77,7 @@ public virtual string ObjectQualifier get { string objectQualifier = this.Settings["objectQualifier"]; - if (!string.IsNullOrEmpty(objectQualifier) && objectQualifier.EndsWith("_") == false) + if (!string.IsNullOrEmpty(objectQualifier) && !objectQualifier.EndsWith("_", StringComparison.Ordinal)) { objectQualifier += "_"; } @@ -184,7 +184,7 @@ public virtual void RollbackTransaction(DbTransaction transaction) } finally { - if (transaction != null && transaction.Connection != null) + if (transaction is { Connection: not null, }) { transaction.Connection.Close(); } @@ -193,7 +193,7 @@ public virtual void RollbackTransaction(DbTransaction transaction) public virtual object GetNull(object field) { - return Null.GetNull(field, DBNull.Value); + return Null.GetNull(field, DBNull.Value, CultureInfo.CurrentCulture); } public virtual IDataReader FindDatabaseVersion(int major, int minor, int build) @@ -2335,6 +2335,7 @@ public virtual partial void UpdateUsersOnline(Hashtable userList) } } + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual int AddPropertyDefinition(int portalId, int moduleDefId, int dataType, string defaultValue, string propertyCategory, string propertyName, bool readOnly, bool required, string validationExpression, int viewOrder, bool visible, int length, int defaultVisibility, int createdByUserId) { int retValue; @@ -2410,6 +2411,7 @@ public virtual void UpdateProfileProperty(int profileId, int userId, int propert lastUpdatedDate); } + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual void UpdatePropertyDefinition(int propertyDefinitionId, int dataType, string defaultValue, string propertyCategory, string propertyName, bool readOnly, bool required, string validation, int viewOrder, bool visible, int length, int defaultVisibility, int lastModifiedByUserId) { this.ExecuteNonQuery( @@ -3348,7 +3350,7 @@ public virtual void AddLogTypeConfigInfo(bool loggingIsActive, string logTypeKey } else { - portalID = Convert.ToInt32(logTypePortalID); + portalID = Convert.ToInt32(logTypePortalID, CultureInfo.InvariantCulture); } this.ExecuteNonQuery( @@ -3447,26 +3449,26 @@ public virtual void UpdateLogType(string logTypeKey, string logTypeFriendlyName, public virtual void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, int keepMostRecent, bool emailNotificationIsActive, int threshold, int notificationThresholdTime, int notificationThresholdTimeType, string mailFromAddress, string mailToAddress) { - int portalID; if (logTypeKey == "*") { logTypeKey = string.Empty; } + int portalId; if (logTypePortalID == "*") { - portalID = -1; + portalId = -1; } else { - portalID = Convert.ToInt32(logTypePortalID); + portalId = Convert.ToInt32(logTypePortalID, CultureInfo.CurrentCulture); } this.ExecuteNonQuery( "UpdateEventLogConfig", id, this.GetNull(logTypeKey), - this.GetNull(portalID), + this.GetNull(portalId), loggingIsActive, keepMostRecent, emailNotificationIsActive, @@ -4088,9 +4090,9 @@ private Version GetVersionInternal(bool current) if (dr.Read()) { version = new Version( - Convert.ToInt32(dr["Major"]), - Convert.ToInt32(dr["Minor"]), - Convert.ToInt32(dr["Build"])); + Convert.ToInt32(dr["Major"], CultureInfo.InvariantCulture), + Convert.ToInt32(dr["Minor"], CultureInfo.InvariantCulture), + Convert.ToInt32(dr["Build"], CultureInfo.InvariantCulture)); } } catch (SqlException ex) diff --git a/DNN Platform/Library/Data/IRepository.cs b/DNN Platform/Library/Data/IRepository.cs index 4f4ea5042ca..af71c2f1bb1 100644 --- a/DNN Platform/Library/Data/IRepository.cs +++ b/DNN Platform/Library/Data/IRepository.cs @@ -2,108 +2,111 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Data -{ - using System.Collections.Generic; +namespace DotNetNuke.Data +{ + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; - using DotNetNuke.Collections; + using DotNetNuke.Collections; public interface IRepository where T : class - { - /// Delete an Item from the repository. - /// The item to be deleted. - void Delete(T item); - - /// Delete items from the repository based on a sql Condition. - /// The sql condition e.g. "WHERE ArticleId = {0}". - /// A collection of arguments to be mapped to the tokens in the sqlCondition. - void Delete(string sqlCondition, params object[] args); - - /// Find items from the repository based on a sql condition. - /// Find supports both full SQL statements such as "SELECT * FROM table WHERE ..." - /// as well as a SQL condition like "WHERE ...". - /// The sql condition e.g. "WHERE ArticleId = @0". - /// A collection of arguments to be mapped to the tokens in the sqlCondition. - /// Find("where ArticleId = @0 and UserId = @1", articleId, userId). - /// A list of items. - IEnumerable Find(string sqlCondition, params object[] args); - - /// Find a GetPage of items from the repository based on a sql condition. - /// Find supports both full SQL statements such as "SELECT * FROM table WHERE ..." - /// as well as a SQL condition like "WHERE ...". - /// The page Index to fetch. - /// The size of the page to fetch. - /// The sql condition e.g. "WHERE ArticleId = @0". - /// A collection of arguments to be mapped to the tokens in the sqlCondition. - /// A list of items. - IPagedList Find(int pageIndex, int pageSize, string sqlCondition, params object[] args); - - /// Returns all the items in the repository as an enumerable list. - /// The list of items. - IEnumerable Get(); - - /// Returns an enumerable list of items filtered by scope. - /// - /// This overload should be used to get a list of items for a specific module - /// instance or for a specific portal dependening on how the items in the repository - /// are scoped. - /// - /// The type of the scope field. - /// The value of the scope to filter by. - /// The list of items. - IEnumerable Get(TScopeType scopeValue); - - /// Get an individual item based on the items Id field. - /// The type of the Id field. - /// The value of the Id field. - /// An item. - T GetById(TProperty id); - - /// Get an individual item based on the items Id field. - /// - /// This overload should be used to get an item for a specific module - /// instance or for a specific portal dependening on how the items in the repository - /// are scoped. This will allow the relevant cache to be searched first. - /// - /// The type of the Id field. - /// The value of the Id field. - /// The type of the scope field. - /// The value of the scope to filter by. - /// An item. - T GetById(TProperty id, TScopeType scopeValue); - - /// Returns a page of items in the repository as a paged list. - /// The page Index to fetch. - /// The size of the page to fetch. - /// The list of items. - IPagedList GetPage(int pageIndex, int pageSize); - - /// Returns a page of items in the repository as a paged list filtered by scope. - /// - /// This overload should be used to get a list of items for a specific module - /// instance or for a specific portal dependening on how the items in the repository - /// are scoped. - /// - /// The type of the scope field. - /// The value of the scope to filter by. - /// The page Index to fetch. - /// The size of the page to fetch. - /// The list of items. - IPagedList GetPage(TScopeType scopeValue, int pageIndex, int pageSize); - - /// Inserts an Item into the repository. - /// The item to be inserted. - void Insert(T item); - - /// Updates an Item in the repository. - /// The item to be updated. - void Update(T item); - - /// Update items in the repository based on a sql Condition. - /// The sql condition e.g. "SET ArticelName = @1 WHERE ArticleId = @0". - /// A collection of arguments to be mapped to the tokens in the sqlCondition. - /// Update("SET Age=@1, Name=@2 WHERE ID=@0", 1, 21, "scooby"). - void Update(string sqlCondition, params object[] args); - } -} + { + /// Delete an Item from the repository. + /// The item to be deleted. + void Delete(T item); + + /// Delete items from the repository based on a sql Condition. + /// The sql condition e.g. "WHERE ArticleId = {0}". + /// A collection of arguments to be mapped to the tokens in the sqlCondition. + void Delete(string sqlCondition, params object[] args); + + /// Find items from the repository based on a sql condition. + /// Find supports both full SQL statements such as "SELECT * FROM table WHERE ..." + /// as well as a SQL condition like "WHERE ...". + /// The sql condition e.g. "WHERE ArticleId = @0". + /// A collection of arguments to be mapped to the tokens in the sqlCondition. + /// Find("where ArticleId = @0 and UserId = @1", articleId, userId). + /// A list of items. + IEnumerable Find(string sqlCondition, params object[] args); + + /// Find a GetPage of items from the repository based on a sql condition. + /// Find supports both full SQL statements such as "SELECT * FROM table WHERE ..." + /// as well as a SQL condition like "WHERE ...". + /// The page Index to fetch. + /// The size of the page to fetch. + /// The sql condition e.g. "WHERE ArticleId = @0". + /// A collection of arguments to be mapped to the tokens in the sqlCondition. + /// A list of items. + IPagedList Find(int pageIndex, int pageSize, string sqlCondition, params object[] args); + + /// Returns all the items in the repository as an enumerable list. + /// The list of items. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + IEnumerable Get(); + + /// Returns an enumerable list of items filtered by scope. + /// + /// This overload should be used to get a list of items for a specific module + /// instance or for a specific portal depending on how the items in the repository + /// are scoped. + /// + /// The type of the scope field. + /// The value of the scope to filter by. + /// The list of items. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + IEnumerable Get(TScopeType scopeValue); + + /// Get an individual item based on the items ID field. + /// The type of the ID field. + /// The value of the ID field. + /// An item. + T GetById(TProperty id); + + /// Get an individual item based on the items ID field. + /// + /// This overload should be used to get an item for a specific module + /// instance or for a specific portal dependening on how the items in the repository + /// are scoped. This will allow the relevant cache to be searched first. + /// + /// The type of the Id field. + /// The value of the Id field. + /// The type of the scope field. + /// The value of the scope to filter by. + /// An item. + T GetById(TProperty id, TScopeType scopeValue); + + /// Returns a page of items in the repository as a paged list. + /// The page Index to fetch. + /// The size of the page to fetch. + /// The list of items. + IPagedList GetPage(int pageIndex, int pageSize); + + /// Returns a page of items in the repository as a paged list filtered by scope. + /// + /// This overload should be used to get a list of items for a specific module + /// instance or for a specific portal dependening on how the items in the repository + /// are scoped. + /// + /// The type of the scope field. + /// The value of the scope to filter by. + /// The page Index to fetch. + /// The size of the page to fetch. + /// The list of items. + IPagedList GetPage(TScopeType scopeValue, int pageIndex, int pageSize); + + /// Inserts an Item into the repository. + /// The item to be inserted. + void Insert(T item); + + /// Updates an Item in the repository. + /// The item to be updated. + void Update(T item); + + /// Update items in the repository based on a sql Condition. + /// The sql condition e.g. "SET ArticelName = @1 WHERE ArticleId = @0". + /// A collection of arguments to be mapped to the tokens in the sqlCondition. + /// Update("SET Age=@1, Name=@2 WHERE ID=@0", 1, 21, "scooby"). + void Update(string sqlCondition, params object[] args); + } +} diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs index 1630038aa9f..82df05371b7 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs @@ -2,231 +2,229 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Data.PetaPoco -{ - using System; - using System.Collections.Generic; - using System.Data; - using System.Data.SqlClient; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Instrumentation; - using global::PetaPoco; - - public static class PetaPocoHelper - { - private const string SqlProviderName = "System.Data.SqlClient"; - - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PetaPocoHelper)); - - public static void ExecuteNonQuery(string connectionString, CommandType type, string sql, params object[] args) - { - ExecuteNonQuery(connectionString, type, Null.NullInteger, sql, args); - } - - public static void ExecuteNonQuery(string connectionString, CommandType type, int timeoutSec, string sql, params object[] args) - { - using (var database = new Database(connectionString, SqlProviderName) { EnableAutoSelect = false }) - { - if (type == CommandType.StoredProcedure) - { - sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); - } - - if (timeoutSec > 0) - { - database.CommandTimeout = timeoutSec; - } - - try - { - database.Execute(sql, args); - } - catch (Exception ex) - { - Logger.Error("[1] Error executing SQL: " + sql + Environment.NewLine + ex.Message); - throw; - } - } - } - - public static void BulkInsert(string connectionString, string procedureName, string tableParameterName, DataTable dataTable) - { - BulkInsert(connectionString, Null.NullInteger, procedureName, tableParameterName, dataTable); - } - - public static void BulkInsert(string connectionString, int timeoutSec, string procedureName, string tableParameterName, DataTable dataTable) - { - if (dataTable.Rows.Count > 0) - { - using (var con = new SqlConnection(connectionString)) - using (var cmd = new SqlCommand(procedureName, con)) - { - if (!tableParameterName.StartsWith("@")) - { - tableParameterName = "@" + tableParameterName; - } - - if (timeoutSec > 0) - { - cmd.CommandTimeout = timeoutSec; - } - - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.AddWithValue(tableParameterName, dataTable); - con.Open(); - try - { - cmd.ExecuteNonQuery(); - } - catch (Exception ex) - { - Logger.Error("[2] Error executing SQL: " + cmd.CommandText + Environment.NewLine + ex.Message); - throw; - } - - con.Close(); - } - } - } - - public static void BulkInsert(string connectionString, string procedureName, string tableParameterName, DataTable dataTable, Dictionary args) - { - BulkInsert(connectionString, procedureName, tableParameterName, dataTable, Null.NullInteger, args); - } - - public static void BulkInsert(string connectionString, string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec, Dictionary args) - { - if (dataTable.Rows.Count > 0) - { - using (var con = new SqlConnection(connectionString)) - using (var cmd = new SqlCommand(procedureName, con)) - { - if (!tableParameterName.StartsWith("@")) - { - tableParameterName = "@" + tableParameterName; - } - - if (timeoutSec > 0) - { - cmd.CommandTimeout = timeoutSec; - } - - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.AddWithValue(tableParameterName, dataTable); - foreach (var arg in args) - { - cmd.Parameters.AddWithValue(arg.Key, arg.Value); - } - - con.Open(); - try - { - cmd.ExecuteNonQuery(); - } - catch (Exception) - { - Logger.Error("[2] Error executing SQL: " + cmd.CommandText); - throw; - } - - con.Close(); - } - } - } - - public static IDataReader ExecuteReader(string connectionString, CommandType type, string sql, params object[] args) - { - return ExecuteReader(connectionString, type, Null.NullInteger, sql, args); - } - - public static IDataReader ExecuteReader(string connectionString, CommandType type, int timeoutSec, string sql, params object[] args) - { - var database = new Database(connectionString, SqlProviderName) { EnableAutoSelect = false }; - - if (type == CommandType.StoredProcedure) - { - sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); - } - - if (timeoutSec > 0) - { - database.CommandTimeout = timeoutSec; - } - - try - { - return database.ExecuteReader(sql, args); - } - catch (Exception ex) - { - // very special case for installation - if (!sql.EndsWith("GetDatabaseVersion")) - { - Logger.Error("[3] Error executing SQL: " + sql + Environment.NewLine + ex.Message); - } - - throw; - } - } - - public static T ExecuteScalar(string connectionString, CommandType type, string sql, params object[] args) - { - return ExecuteScalar(connectionString, type, Null.NullInteger, sql, args); - } - - public static T ExecuteScalar(string connectionString, CommandType type, int timeoutSec, string sql, params object[] args) - { - using (var database = new Database(connectionString, SqlProviderName) { EnableAutoSelect = false }) - { - if (type == CommandType.StoredProcedure) - { - sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); - } - - if (timeoutSec > 0) - { - database.CommandTimeout = timeoutSec; - } - - try - { - return database.ExecuteScalar(sql, args); - } - catch (Exception ex) - { - Logger.Error("[4] Error executing SQL: " + sql + Environment.NewLine + ex.Message); - throw; - } - } - } - - // ReSharper disable once InconsistentNaming - public static void ExecuteSQL(string connectionString, string sql) - { - ExecuteSQL(connectionString, sql, Null.NullInteger); - } - - // ReSharper disable once InconsistentNaming - public static void ExecuteSQL(string connectionString, string sql, int timeoutSec) - { - using (var database = new Database(connectionString, SqlProviderName) { EnableAutoSelect = false }) - { - if (timeoutSec > 0) - { - database.CommandTimeout = timeoutSec; - } - - try - { - database.Execute(sql); - } - catch (Exception ex) - { - Logger.Error("[5] Error executing SQL: " + sql + Environment.NewLine + ex.Message); - throw; - } - } - } - } -} +namespace DotNetNuke.Data.PetaPoco +{ + using System; + using System.Collections.Generic; + using System.Data; + using System.Data.SqlClient; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using global::PetaPoco; + + public static class PetaPocoHelper + { + private const string SqlProviderName = "System.Data.SqlClient"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PetaPocoHelper)); + + public static void ExecuteNonQuery(string connectionString, CommandType type, string sql, params object[] args) + { + ExecuteNonQuery(connectionString, type, Null.NullInteger, sql, args); + } + + public static void ExecuteNonQuery(string connectionString, CommandType type, int timeoutSec, string sql, params object[] args) + { + using (var database = new Database(connectionString, SqlProviderName) { EnableAutoSelect = false }) + { + if (type == CommandType.StoredProcedure) + { + sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); + } + + if (timeoutSec > 0) + { + database.CommandTimeout = timeoutSec; + } + + try + { + database.Execute(sql, args); + } + catch (Exception ex) + { + Logger.Error("[1] Error executing SQL: " + sql + Environment.NewLine + ex.Message); + throw; + } + } + } + + public static void BulkInsert(string connectionString, string procedureName, string tableParameterName, DataTable dataTable) + { + BulkInsert(connectionString, Null.NullInteger, procedureName, tableParameterName, dataTable); + } + + public static void BulkInsert(string connectionString, int timeoutSec, string procedureName, string tableParameterName, DataTable dataTable) + { + if (dataTable.Rows.Count > 0) + { + using var con = new SqlConnection(connectionString); + using var cmd = new SqlCommand(procedureName, con); + if (!tableParameterName.StartsWith("@", StringComparison.Ordinal)) + { + tableParameterName = "@" + tableParameterName; + } + + if (timeoutSec > 0) + { + cmd.CommandTimeout = timeoutSec; + } + + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue(tableParameterName, dataTable); + con.Open(); + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception ex) + { + Logger.Error("[2] Error executing SQL: " + cmd.CommandText + Environment.NewLine + ex.Message); + throw; + } + + con.Close(); + } + } + + public static void BulkInsert(string connectionString, string procedureName, string tableParameterName, DataTable dataTable, Dictionary args) + { + BulkInsert(connectionString, procedureName, tableParameterName, dataTable, Null.NullInteger, args); + } + + public static void BulkInsert(string connectionString, string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec, Dictionary args) + { + if (dataTable.Rows.Count > 0) + { + using (var con = new SqlConnection(connectionString)) + using (var cmd = new SqlCommand(procedureName, con)) + { + if (!tableParameterName.StartsWith("@", StringComparison.Ordinal)) + { + tableParameterName = "@" + tableParameterName; + } + + if (timeoutSec > 0) + { + cmd.CommandTimeout = timeoutSec; + } + + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue(tableParameterName, dataTable); + foreach (var arg in args) + { + cmd.Parameters.AddWithValue(arg.Key, arg.Value); + } + + con.Open(); + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception) + { + Logger.Error("[2] Error executing SQL: " + cmd.CommandText); + throw; + } + + con.Close(); + } + } + } + + public static IDataReader ExecuteReader(string connectionString, CommandType type, string sql, params object[] args) + { + return ExecuteReader(connectionString, type, Null.NullInteger, sql, args); + } + + public static IDataReader ExecuteReader(string connectionString, CommandType type, int timeoutSec, string sql, params object[] args) + { + var database = new Database(connectionString, SqlProviderName) { EnableAutoSelect = false, }; + + if (type == CommandType.StoredProcedure) + { + sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); + } + + if (timeoutSec > 0) + { + database.CommandTimeout = timeoutSec; + } + + try + { + return database.ExecuteReader(sql, args); + } + catch (Exception ex) + { + // very special case for installation + if (!sql.EndsWith("GetDatabaseVersion", StringComparison.Ordinal)) + { + Logger.Error("[3] Error executing SQL: " + sql + Environment.NewLine + ex.Message); + } + + throw; + } + } + + public static T ExecuteScalar(string connectionString, CommandType type, string sql, params object[] args) + { + return ExecuteScalar(connectionString, type, Null.NullInteger, sql, args); + } + + public static T ExecuteScalar(string connectionString, CommandType type, int timeoutSec, string sql, params object[] args) + { + using (var database = new Database(connectionString, SqlProviderName) { EnableAutoSelect = false }) + { + if (type == CommandType.StoredProcedure) + { + sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args); + } + + if (timeoutSec > 0) + { + database.CommandTimeout = timeoutSec; + } + + try + { + return database.ExecuteScalar(sql, args); + } + catch (Exception ex) + { + Logger.Error("[4] Error executing SQL: " + sql + Environment.NewLine + ex.Message); + throw; + } + } + } + + // ReSharper disable once InconsistentNaming + public static void ExecuteSQL(string connectionString, string sql) + { + ExecuteSQL(connectionString, sql, Null.NullInteger); + } + + // ReSharper disable once InconsistentNaming + public static void ExecuteSQL(string connectionString, string sql, int timeoutSec) + { + using (var database = new Database(connectionString, SqlProviderName) { EnableAutoSelect = false }) + { + if (timeoutSec > 0) + { + database.CommandTimeout = timeoutSec; + } + + try + { + database.Execute(sql); + } + catch (Exception ex) + { + Logger.Error("[5] Error executing SQL: " + sql + Environment.NewLine + ex.Message); + throw; + } + } + } + } +} diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs index fbcfc04e3eb..f50b76e7e04 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Data.PetaPoco { using System; + using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Threading; @@ -45,7 +46,7 @@ public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) { bool includeColumn = true; - // Check if the class has the ExplictColumnsAttribute + // Check if the class has the DeclareColumnsAttribute bool declareColumns = pocoProperty.DeclaringType != null && pocoProperty.DeclaringType.GetCustomAttributes(typeof(DeclareColumnsAttribute), true).Length > 0; @@ -95,6 +96,7 @@ public TableInfo GetTableInfo(Type pocoType) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public Func GetFromDbConverter(PropertyInfo pi, Type sourceType) { return null; diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs index 7600a30ca59..95e27ff812b 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs @@ -46,7 +46,7 @@ public override IPagedList Find(int pageIndex, int pageSize, string sqlCondit // Make sure that the sql Condition contains an ORDER BY Clause if (!sqlCondition.ToUpperInvariant().Contains("ORDER BY")) { - sqlCondition = string.Format("{0} ORDER BY {1}", sqlCondition, this.mapper.GetTableInfo(typeof(T)).PrimaryKey); + sqlCondition = $"{sqlCondition} ORDER BY {this.mapper.GetTableInfo(typeof(T)).PrimaryKey}"; } Page petaPocoPage = this.database.Page(pageIndex + 1, pageSize, DataUtil.ReplaceTokens(sqlCondition), args); @@ -110,7 +110,7 @@ protected override void UpdateInternal(T item) private string GetScopeSql() { - return string.Format("WHERE {0} = @0", DataUtil.GetColumnName(typeof(T), this.Scope)); + return $"WHERE {DataUtil.GetColumnName(typeof(T), this.Scope)} = @0"; } } } diff --git a/DNN Platform/Library/Data/RepositoryBase.cs b/DNN Platform/Library/Data/RepositoryBase.cs index ee49dc88f7d..833405b3ce6 100644 --- a/DNN Platform/Library/Data/RepositoryBase.cs +++ b/DNN Platform/Library/Data/RepositoryBase.cs @@ -2,40 +2,41 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Data -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Web.Caching; - - using DotNetNuke.Collections; - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.ComponentModel.DataAnnotations; +namespace DotNetNuke.Data +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web.Caching; + + using DotNetNuke.Collections; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.ComponentModel.DataAnnotations; public abstract class RepositoryBase : IRepository where T : class { /// Initializes a new instance of the class. - protected RepositoryBase() - { - this.InitializeInternal(); - } - - protected CacheItemArgs CacheArgs { get; private set; } - - protected string Scope { get; private set; } - - protected bool IsCacheable { get; private set; } - + protected RepositoryBase() + { + this.InitializeInternal(); + } + + protected CacheItemArgs CacheArgs { get; private set; } + + protected string Scope { get; private set; } + + protected bool IsCacheable { get; private set; } + protected bool IsScoped { get; private set; } /// - public void Delete(T item) - { - this.DeleteInternal(item); - this.ClearCache(item); + public void Delete(T item) + { + this.DeleteInternal(item); + this.ClearCache(item); } /// @@ -48,195 +49,195 @@ public void Delete(T item) public abstract IPagedList Find(int pageIndex, int pageSize, string sqlCondition, params object[] args); /// - public IEnumerable Get() - { - return this.IsCacheable && !this.IsScoped - ? DataCache.GetCachedData>(this.CacheArgs, c => this.GetInternal()) - : this.GetInternal(); + public IEnumerable Get() + { + return this.IsCacheable && !this.IsScoped + ? DataCache.GetCachedData>(this.CacheArgs, c => this.GetInternal()) + : this.GetInternal(); } /// - public IEnumerable Get(TScopeType scopeValue) - { - this.CheckIfScoped(); - - if (this.IsCacheable) - { - this.CacheArgs.CacheKey = string.Format(this.CacheArgs.CacheKey, scopeValue); - } - - return this.IsCacheable - ? DataCache.GetCachedData>(this.CacheArgs, c => this.GetByScopeInternal(scopeValue)) - : this.GetByScopeInternal(scopeValue); + public IEnumerable Get(TScopeType scopeValue) + { + this.CheckIfScoped(); + + if (this.IsCacheable) + { + this.CacheArgs.CacheKey = string.Format(CultureInfo.InvariantCulture, this.CacheArgs.CacheKey, scopeValue); + } + + return this.IsCacheable + ? DataCache.GetCachedData>(this.CacheArgs, c => this.GetByScopeInternal(scopeValue)) + : this.GetByScopeInternal(scopeValue); } /// - public T GetById(TProperty id) - { - return this.IsCacheable && !this.IsScoped - ? this.Get().SingleOrDefault(t => this.CompareTo(this.GetPrimaryKey(t), id) == 0) - : this.GetByIdInternal(id); + public T GetById(TProperty id) + { + return this.IsCacheable && !this.IsScoped + ? this.Get().SingleOrDefault(t => this.CompareTo(this.GetPrimaryKey(t), id) == 0) + : this.GetByIdInternal(id); } /// - public T GetById(TProperty id, TScopeType scopeValue) - { - this.CheckIfScoped(); - - return this.Get(scopeValue).SingleOrDefault(t => this.CompareTo(this.GetPrimaryKey(t), id) == 0); + public T GetById(TProperty id, TScopeType scopeValue) + { + this.CheckIfScoped(); + + return this.Get(scopeValue).SingleOrDefault(t => this.CompareTo(this.GetPrimaryKey(t), id) == 0); } /// - public IPagedList GetPage(int pageIndex, int pageSize) - { - return this.IsCacheable && !this.IsScoped - ? this.Get().InPagesOf(pageSize).GetPage(pageIndex) - : this.GetPageInternal(pageIndex, pageSize); + public IPagedList GetPage(int pageIndex, int pageSize) + { + return this.IsCacheable && !this.IsScoped + ? this.Get().InPagesOf(pageSize).GetPage(pageIndex) + : this.GetPageInternal(pageIndex, pageSize); } /// - public IPagedList GetPage(TScopeType scopeValue, int pageIndex, int pageSize) - { - this.CheckIfScoped(); - - return this.IsCacheable - ? this.Get(scopeValue).InPagesOf(pageSize).GetPage(pageIndex) - : this.GetPageByScopeInternal(scopeValue, pageIndex, pageSize); + public IPagedList GetPage(TScopeType scopeValue, int pageIndex, int pageSize) + { + this.CheckIfScoped(); + + return this.IsCacheable + ? this.Get(scopeValue).InPagesOf(pageSize).GetPage(pageIndex) + : this.GetPageByScopeInternal(scopeValue, pageIndex, pageSize); } /// - public void Insert(T item) - { - this.InsertInternal(item); - this.ClearCache(item); + public void Insert(T item) + { + this.InsertInternal(item); + this.ClearCache(item); } /// - public void Update(T item) - { - this.UpdateInternal(item); - this.ClearCache(item); + public void Update(T item) + { + this.UpdateInternal(item); + this.ClearCache(item); } /// - public abstract void Update(string sqlCondition, params object[] args); - - public void Initialize(string cacheKey, int cacheTimeOut = 20, CacheItemPriority cachePriority = CacheItemPriority.Default, string scope = "") - { - this.Scope = scope; - this.IsScoped = !string.IsNullOrEmpty(this.Scope); - this.IsCacheable = !string.IsNullOrEmpty(cacheKey); - if (this.IsCacheable) - { - if (this.IsScoped) - { - cacheKey += "_" + this.Scope + "_{0}"; - } - - this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); - } - else - { - this.CacheArgs = null; - } - } - - protected int CompareTo(TProperty first, TProperty second) - { - Requires.IsTypeOf("first", first); - Requires.IsTypeOf("second", second); - - var firstComparable = first as IComparable; - var secondComparable = second as IComparable; - - // ReSharper disable PossibleNullReferenceException - return firstComparable.CompareTo(secondComparable); - - // ReSharper restore PossibleNullReferenceException - } - - protected TProperty GetPropertyValue(T item, string propertyName) - { - return DataUtil.GetPropertyValue(item, propertyName); - } - - protected TProperty GetPrimaryKey(T item) - { - return DataUtil.GetPrimaryKey(item); - } - - protected TProperty GetScopeValue(T item) - { - return DataUtil.GetPropertyValue(item, this.Scope); - } - - protected abstract void DeleteInternal(T item); - - protected abstract IEnumerable GetInternal(); - - protected abstract IPagedList GetPageInternal(int pageIndex, int pageSize); - - protected abstract IEnumerable GetByScopeInternal(object propertyValue); - - protected abstract IPagedList GetPageByScopeInternal(object propertyValue, int pageIndex, int pageSize); - - protected abstract T GetByIdInternal(object id); - - protected abstract void InsertInternal(T item); - - protected abstract void UpdateInternal(T item); - - private void CheckIfScoped() - { - if (!this.IsScoped) - { - throw new NotSupportedException("This method requires the model to be cacheable and have a cache scope defined"); - } - } - - private void ClearCache(T item) - { - if (this.IsCacheable) - { - DataCache.RemoveCache(this.IsScoped - ? string.Format(this.CacheArgs.CacheKey, this.GetScopeValue(item)) - : this.CacheArgs.CacheKey); - } - } - - private void InitializeInternal() - { - var type = typeof(T); - this.Scope = string.Empty; - this.IsCacheable = false; - this.IsScoped = false; - this.CacheArgs = null; - - var scopeAttribute = DataUtil.GetAttribute(type); - if (scopeAttribute != null) - { - this.Scope = scopeAttribute.Scope; - } - - this.IsScoped = !string.IsNullOrEmpty(this.Scope); - - var cacheableAttribute = DataUtil.GetAttribute(type); - if (cacheableAttribute != null) - { - this.IsCacheable = true; - var cacheKey = !string.IsNullOrEmpty(cacheableAttribute.CacheKey) - ? cacheableAttribute.CacheKey - : string.Format("OR_{0}", type.Name); - var cachePriority = cacheableAttribute.CachePriority; - var cacheTimeOut = cacheableAttribute.CacheTimeOut; - - if (this.IsScoped) - { - cacheKey += "_" + this.Scope + "_{0}"; - } - - this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); - } - } - } -} + public abstract void Update(string sqlCondition, params object[] args); + + public void Initialize(string cacheKey, int cacheTimeOut = 20, CacheItemPriority cachePriority = CacheItemPriority.Default, string scope = "") + { + this.Scope = scope; + this.IsScoped = !string.IsNullOrEmpty(this.Scope); + this.IsCacheable = !string.IsNullOrEmpty(cacheKey); + if (this.IsCacheable) + { + if (this.IsScoped) + { + cacheKey += "_" + this.Scope + "_{0}"; + } + + this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); + } + else + { + this.CacheArgs = null; + } + } + + protected int CompareTo(TProperty first, TProperty second) + { + Requires.IsTypeOf("first", first); + Requires.IsTypeOf("second", second); + + var firstComparable = first as IComparable; + var secondComparable = second as IComparable; + + // ReSharper disable PossibleNullReferenceException + return firstComparable.CompareTo(secondComparable); + + // ReSharper restore PossibleNullReferenceException + } + + protected TProperty GetPropertyValue(T item, string propertyName) + { + return DataUtil.GetPropertyValue(item, propertyName); + } + + protected TProperty GetPrimaryKey(T item) + { + return DataUtil.GetPrimaryKey(item); + } + + protected TProperty GetScopeValue(T item) + { + return DataUtil.GetPropertyValue(item, this.Scope); + } + + protected abstract void DeleteInternal(T item); + + protected abstract IEnumerable GetInternal(); + + protected abstract IPagedList GetPageInternal(int pageIndex, int pageSize); + + protected abstract IEnumerable GetByScopeInternal(object propertyValue); + + protected abstract IPagedList GetPageByScopeInternal(object propertyValue, int pageIndex, int pageSize); + + protected abstract T GetByIdInternal(object id); + + protected abstract void InsertInternal(T item); + + protected abstract void UpdateInternal(T item); + + private void CheckIfScoped() + { + if (!this.IsScoped) + { + throw new NotSupportedException("This method requires the model to be cacheable and have a cache scope defined"); + } + } + + private void ClearCache(T item) + { + if (this.IsCacheable) + { + DataCache.RemoveCache(this.IsScoped + ? string.Format(CultureInfo.InvariantCulture, this.CacheArgs.CacheKey, this.GetScopeValue(item)) + : this.CacheArgs.CacheKey); + } + } + + private void InitializeInternal() + { + var type = typeof(T); + this.Scope = string.Empty; + this.IsCacheable = false; + this.IsScoped = false; + this.CacheArgs = null; + + var scopeAttribute = DataUtil.GetAttribute(type); + if (scopeAttribute != null) + { + this.Scope = scopeAttribute.Scope; + } + + this.IsScoped = !string.IsNullOrEmpty(this.Scope); + + var cacheableAttribute = DataUtil.GetAttribute(type); + if (cacheableAttribute != null) + { + this.IsCacheable = true; + var cacheKey = !string.IsNullOrEmpty(cacheableAttribute.CacheKey) + ? cacheableAttribute.CacheKey + : $"OR_{type.Name}"; + var cachePriority = cacheableAttribute.CachePriority; + var cacheTimeOut = cacheableAttribute.CacheTimeOut; + + if (this.IsScoped) + { + cacheKey += $"_{this.Scope}_{{0}}"; + } + + this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); + } + } + } +} diff --git a/DNN Platform/Library/Data/SqlDataProvider.cs b/DNN Platform/Library/Data/SqlDataProvider.cs index fe0c81c1943..b0ef4f2ef59 100644 --- a/DNN Platform/Library/Data/SqlDataProvider.cs +++ b/DNN Platform/Library/Data/SqlDataProvider.cs @@ -143,12 +143,14 @@ public override string ExecuteScript(string script, int timeoutSec) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override string ExecuteScript(string connectionString, string script) { return ExecuteScriptInternal(connectionString, script); } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override string ExecuteScript(string connectionString, string script, int timeoutSec) { return ExecuteScriptInternal(connectionString, script, timeoutSec); diff --git a/DNN Platform/Library/DotNetNuke.Library.csproj b/DNN Platform/Library/DotNetNuke.Library.csproj index d56fede6e5f..2182540d289 100644 --- a/DNN Platform/Library/DotNetNuke.Library.csproj +++ b/DNN Platform/Library/DotNetNuke.Library.csproj @@ -15,7 +15,7 @@ Recommended true 1591, 3001, 3002, 1574, 1573 - CS0618,SA1600,CA1000,CA1001,CA1010,CA1018,CA1050,CA1051,CA1305,CA1310,CA1311,CA1707,CA1708,CA1710,CA1711,CA1716,CA1720,CA1725,CA3075,CA5350,CA5351,CA5368,CA5369,CA5372,CA5379 + CS0618,SA1600,CA3075,CA5350,CA5351,CA5368,CA5369,CA5372,CA5379 true false diff --git a/DNN Platform/Library/Entities/Content/AttachmentController.cs b/DNN Platform/Library/Entities/Content/AttachmentController.cs index 2c375d75b19..00ba5f566c7 100644 --- a/DNN Platform/Library/Entities/Content/AttachmentController.cs +++ b/DNN Platform/Library/Entities/Content/AttachmentController.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Entities.Content using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.Linq; using DotNetNuke.Common.Utilities; @@ -113,12 +114,12 @@ internal static IEnumerable DeserializeFileInfo(string content) yield break; } - foreach (var file in content.FromJson().ToArray()) + foreach (var fileId in content.FromJson().ToArray()) { IFileInfo fileInfo = null; try { - fileInfo = FileManager.Instance.GetFile(file); + fileInfo = FileManager.Instance.GetFile(fileId); } catch { @@ -127,7 +128,7 @@ internal static IEnumerable DeserializeFileInfo(string content) // On second thought, I don't know how much sense it makes to be throwing an exception here. If the file // has been deleted or is otherwise unavailable, there's really no reason we can't continue on handling the // ContentItem without its attachment. Better than the yellow screen of death? --cbond - Logger.WarnFormat("Unable to load file properties for File ID {0}", file); + Logger.WarnFormat(CultureInfo.InvariantCulture, "Unable to load file properties for File ID {0}", fileId); } if (fileInfo != null) diff --git a/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs b/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs index 813135750ad..96a1fcfdf80 100644 --- a/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs +++ b/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Entities.Content.Common using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.Linq; using System.Text; @@ -40,24 +41,24 @@ public static string ToDelimittedString(this List terms, string delimitter return sb.ToString(); } - /// Toes the delimitted string. + /// Toes the delimited string. /// The terms. /// The format. - /// The delimitter. - /// formatted terms' name as a string and split with the given delimitter order by name A-Z. + /// The delimiter. + /// formatted terms' name as a string and split with the given delimiter order by name A-Z. public static string ToDelimittedString(this List terms, string format, string delimitter) { var sb = new StringBuilder(); if (terms != null) { - foreach (Term term in terms.OrderBy(term => term.Name)) + foreach (var term in terms.OrderBy(term => term.Name)) { if (sb.Length > 0) { sb.Append(delimitter); } - sb.Append(string.Format(format, term.Name)); + sb.Append(string.Format(CultureInfo.InvariantCulture, format, term.Name)); } } diff --git a/DNN Platform/Library/Entities/Content/ContentController.cs b/DNN Platform/Library/Entities/Content/ContentController.cs index 5c266b6def8..51d42f2143b 100644 --- a/DNN Platform/Library/Entities/Content/ContentController.cs +++ b/DNN Platform/Library/Entities/Content/ContentController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Content using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -65,14 +66,14 @@ public void DeleteContentItem(ContentItem contentItem) Requires.NotNull("contentItem", contentItem); Requires.PropertyNotNegative("contentItem", "ContentItemId", contentItem.ContentItemId); - var searrchDoc = new SearchDocumentToDelete + var searchDoc = new SearchDocumentToDelete { - UniqueKey = contentItem.ContentItemId.ToString("D"), + UniqueKey = contentItem.ContentItemId.ToString("D", CultureInfo.InvariantCulture), ModuleId = contentItem.ModuleID, TabId = contentItem.TabID, SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, }; - DotNetNuke.Data.DataProvider.Instance().AddSearchDeletedItems(searrchDoc); + DotNetNuke.Data.DataProvider.Instance().AddSearchDeletedItems(searchDoc); this.dataService.DeleteContentItem(contentItem.ContentItemId); @@ -279,7 +280,7 @@ private static void UpdateContentItemsCache(ContentItem contentItem, bool readdI private static string GetContentItemCacheKey(int contetnItemId) { - return string.Format(DataCache.ContentItemsCacheKey, contetnItemId); + return string.Format(CultureInfo.InvariantCulture, DataCache.ContentItemsCacheKey, contetnItemId); } private void SaveMetadataDelta(ContentItem contentItem) diff --git a/DNN Platform/Library/Entities/Content/Data/DataService.cs b/DNN Platform/Library/Entities/Content/Data/DataService.cs index 6d0c462bfb5..67db3eaef2c 100644 --- a/DNN Platform/Library/Entities/Content/Data/DataService.cs +++ b/DNN Platform/Library/Entities/Content/Data/DataService.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Content.Data { using System.Collections.Generic; using System.Data; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Data; using DotNetNuke.Entities.Content.Common; @@ -124,6 +125,7 @@ public IDataReader GetUnIndexedContentItems() /// Updates the content item. /// The content item. /// The created by user id. + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void UpdateContentItem(ContentItem contentItem, int createdByUserId) { this.provider.ExecuteNonQuery( diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs b/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs index 9a018b77243..e6802e1dc53 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Content.Taxonomy using System; using System.Collections.Generic; using System.Data; + using System.Globalization; using System.Linq; using System.Web.Script.Serialization; using System.Xml.Serialization; @@ -307,17 +308,17 @@ public virtual void Fill(IDataReader dr) if (dr["TermLeft"] != DBNull.Value) { - this.left = Convert.ToInt32(dr["TermLeft"]); + this.left = Convert.ToInt32(dr["TermLeft"], CultureInfo.InvariantCulture); } if (dr["TermRight"] != DBNull.Value) { - this.right = Convert.ToInt32(dr["TermRight"]); + this.right = Convert.ToInt32(dr["TermRight"], CultureInfo.InvariantCulture); } if (dr["ParentTermID"] != DBNull.Value) { - this.ParentTermId = Convert.ToInt32(dr["ParentTermID"]); + this.ParentTermId = Convert.ToInt32(dr["ParentTermID"], CultureInfo.InvariantCulture); } // Fill base class properties @@ -326,7 +327,7 @@ public virtual void Fill(IDataReader dr) public string GetTermPath() { - string path = "\\\\" + this.Name; + string path = $@"\\{this.Name}"; if (this.ParentTermId.HasValue) { diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs index 7971658e1d9..9514c132f21 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Content.Taxonomy { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Web; using System.Web.Caching; @@ -69,7 +70,7 @@ public int AddTerm(Term term) } // Clear Cache - DataCache.RemoveCache(string.Format(DataCache.TermCacheKey, term.VocabularyId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.TermCacheKey, term.VocabularyId)); return term.TermId; } @@ -88,7 +89,7 @@ public void AddTermToContent(Term term, ContentItem contentItem) this.dataService.AddTermToContent(term, contentItem); // We have adjusted a content item, remove it from cache - DataCache.RemoveCache(string.Format(DataCache.ContentItemsCacheKey, contentItem.ContentTypeId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.ContentItemsCacheKey, contentItem.ContentTypeId)); } /// Deletes the term. @@ -111,7 +112,7 @@ public void DeleteTerm(Term term) } // Clear Cache - DataCache.RemoveCache(string.Format(DataCache.TermCacheKey, term.VocabularyId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.TermCacheKey, term.VocabularyId)); } /// Gets the term. @@ -157,7 +158,7 @@ public IQueryable GetTermsByVocabulary(int vocabularyId) // Argument Contract Requires.NotNegative("vocabularyId", vocabularyId); - return CBO.GetCachedObject>(new CacheItemArgs(string.Format(DataCache.TermCacheKey, vocabularyId), CacheTimeOut, CachePriority, vocabularyId), this.GetTermsCallBack).AsQueryable(); + return CBO.GetCachedObject>(new CacheItemArgs(string.Format(CultureInfo.InvariantCulture, DataCache.TermCacheKey, vocabularyId), CacheTimeOut, CachePriority, vocabularyId), this.GetTermsCallBack).AsQueryable(); } /// Gets the terms by vocabulary name. @@ -193,7 +194,7 @@ public void RemoveTermsFromContent(ContentItem contentItem) this.dataService.RemoveTermsFromContent(contentItem); // We have adjusted a content item, remove it from cache - DataCache.RemoveCache(string.Format(DataCache.ContentItemsCacheKey, contentItem.ContentTypeId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.ContentItemsCacheKey, contentItem.ContentTypeId)); } /// Updates the term. @@ -220,7 +221,7 @@ public void UpdateTerm(Term term) } // Clear Cache - DataCache.RemoveCache(string.Format(DataCache.TermCacheKey, term.VocabularyId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.TermCacheKey, term.VocabularyId)); } private object GetTermsCallBack(CacheItemArgs cacheItemArgs) diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs b/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs index b302a6a8b86..e23809483d1 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Content.Taxonomy using System; using System.Collections.Generic; using System.Data; + using System.Globalization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Content.Common; @@ -236,7 +237,7 @@ public virtual int KeyID public virtual void Fill(IDataReader dr) { this.VocabularyId = Null.SetNullInteger(dr["VocabularyID"]); - switch (Convert.ToInt16(dr["VocabularyTypeID"])) + switch (Convert.ToInt16(dr["VocabularyTypeID"], CultureInfo.InvariantCulture)) { case 1: this.Type = VocabularyType.Simple; diff --git a/DNN Platform/Library/Entities/Content/Workflow/Actions/TabActions/TabActionBase.cs b/DNN Platform/Library/Entities/Content/Workflow/Actions/TabActions/TabActionBase.cs index 4be1e4762c6..359f7771f68 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Actions/TabActions/TabActionBase.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Actions/TabActions/TabActionBase.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Content.Workflow.Actions.TabActions { using System.Data; using System.Data.SqlClient; + using System.Globalization; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; @@ -80,6 +81,6 @@ internal static string GetString(string key, string defaultValue) /// The parameters to format the string. /// The formatted localized string value. internal static string GetString(string key, string defaultValue, params object[] @params) - => string.Format(GetString(key, defaultValue), @params); + => string.Format(CultureInfo.CurrentCulture, GetString(key, defaultValue), @params); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs index 95c41bac4e0..d8aec53f365 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs @@ -2,65 +2,65 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Content.Workflow.Entities -{ - using System; - using System.Collections.Generic; - using System.ComponentModel.DataAnnotations; - using System.Linq; +namespace DotNetNuke.Entities.Content.Workflow.Entities +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.Linq; - using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.ComponentModel.DataAnnotations; - /// This entity represents a Workflow. - [PrimaryKey("WorkflowID")] - [TableName("ContentWorkflows")] - [Serializable] - public class Workflow - { - /// Gets first workflow state. - [IgnoreColumn] - public WorkflowState FirstState - { - get - { - return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).FirstOrDefault(); - } - } - - /// Gets last workflow state. - [IgnoreColumn] - public WorkflowState LastState - { - get - { - return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).LastOrDefault(); - } - } - - /// Gets or sets workflow Id. - public int WorkflowID { get; set; } - - /// Gets or sets portal Id. - public int PortalID { get; set; } - - /// Gets or sets workflow Name. - [Required] - [StringLength(40)] - public string WorkflowName { get; set; } - - /// Gets or sets workflow Key. This property can be used to. - [StringLength(40)] - public string WorkflowKey { get; set; } - - /// Gets or sets workflow Description. - [StringLength(256)] - public string Description { get; set; } - - /// Gets a value indicating whether system workflow have a special behavior. It cannot be deleted and new states cannot be added. - public bool IsSystem { get; internal set; } - - /// Gets workflow states. - [IgnoreColumn] - public IEnumerable States { get; internal set; } - } -} + /// This entity represents a Workflow. + [PrimaryKey("WorkflowID")] + [TableName("ContentWorkflows")] + [Serializable] + public class Workflow + { + /// Gets first workflow state. + [IgnoreColumn] + public WorkflowState FirstState + { + get + { + return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).FirstOrDefault(); + } + } + + /// Gets last workflow state. + [IgnoreColumn] + public WorkflowState LastState + { + get + { + return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).LastOrDefault(); + } + } + + /// Gets or sets workflow Id. + public int WorkflowID { get; set; } + + /// Gets or sets portal Id. + public int PortalID { get; set; } + + /// Gets or sets workflow Name. + [Required] + [StringLength(40)] + public string WorkflowName { get; set; } + + /// Gets or sets workflow Key. This property can be used to. + [StringLength(40)] + public string WorkflowKey { get; set; } + + /// Gets or sets workflow Description. + [StringLength(256)] + public string Description { get; set; } + + /// Gets a value indicating whether system workflow have a special behavior. It cannot be deleted and new states cannot be added. + public bool IsSystem { get; internal set; } + + /// Gets workflow states. + [IgnoreColumn] + public IEnumerable States { get; internal set; } + } +} diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowStatePermission.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowStatePermission.cs index 45f90dbaaa0..e124953fcec 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowStatePermission.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/WorkflowStatePermission.cs @@ -2,17 +2,20 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Content.Workflow.Entities -{ - using DotNetNuke.Security.Permissions; +namespace DotNetNuke.Entities.Content.Workflow.Entities +{ + using System.Diagnostics.CodeAnalysis; - /// This entity represents a state permission. - public class WorkflowStatePermission : PermissionInfoBase - { - /// Gets or sets workflow state permission Id. - public int WorkflowStatePermissionID { get; set; } - - /// Gets or sets state Id. - public int StateID { get; set; } - } -} + using DotNetNuke.Security.Permissions; + + /// This entity represents a state permission. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public class WorkflowStatePermission : PermissionInfoBase + { + /// Gets or sets workflow state permission ID. + public int WorkflowStatePermissionID { get; set; } + + /// Gets or sets state ID. + public int StateID { get; set; } + } +} diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs index 2b242cc397c..0a2ee057c8c 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Content.Workflow.Repositories { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Common.Utilities; @@ -148,7 +149,7 @@ public void DeleteWorkflow(Entities.Workflow workflow) internal static string GetWorkflowItemKey(int workflowId) { - return string.Format(DataCache.ContentWorkflowCacheKey, workflowId); + return string.Format(CultureInfo.InvariantCulture, DataCache.ContentWorkflowCacheKey, workflowId); } /// diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs index 41edbb8b818..f3f737724db 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Content.Workflow.Repositories { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -120,7 +121,7 @@ private static bool DoesExistWorkflowState(WorkflowState state, IRepository, IWorkflowSecurity - { - private const string ReviewPermissionKey = "REVIEW"; + public class WorkflowSecurity : ServiceLocator, IWorkflowSecurity + { + private const string ReviewPermissionKey = "REVIEW"; private const string ReviewPermissionCode = "SYSTEM_CONTENTWORKFLOWSTATE"; - private const string ContentManagers = "Content Managers"; - private readonly IUserController userController = UserController.Instance; - private readonly IWorkflowManager workflowManager = WorkflowManager.Instance; + private const string ContentManagers = "Content Managers"; + private readonly IUserController userController = UserController.Instance; + private readonly IWorkflowManager workflowManager = WorkflowManager.Instance; private readonly IWorkflowStatePermissionsRepository statePermissionsRepository = WorkflowStatePermissionsRepository.Instance; /// - public bool HasStateReviewerPermission(PortalSettings settings, UserInfo user, int stateId) - { - var permissions = this.statePermissionsRepository.GetWorkflowStatePermissionByState(stateId); - + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] + public bool HasStateReviewerPermission(PortalSettings settings, UserInfo user, int stateId) + { + var permissions = this.statePermissionsRepository.GetWorkflowStatePermissionByState(stateId); + return user.IsSuperUser || PortalSecurity.IsInRoles(user, settings, settings.AdministratorRoleName) || - PortalSecurity.IsInRoles(user, settings, ContentManagers) || - PortalSecurity.IsInRoles(user, settings, PermissionController.BuildPermissions(permissions.ToList(), ReviewPermissionKey)); + PortalSecurity.IsInRoles(user, settings, ContentManagers) || + PortalSecurity.IsInRoles(user, settings, PermissionController.BuildPermissions(permissions.ToList(), ReviewPermissionKey)); } /// - public bool HasStateReviewerPermission(int portalId, int userId, int stateId) - { - var user = this.userController.GetUserById(portalId, userId); - var portalSettings = new PortalSettings(portalId); - return this.HasStateReviewerPermission(portalSettings, user, stateId); + public bool HasStateReviewerPermission(int portalId, int userId, int stateId) + { + var user = this.userController.GetUserById(portalId, userId); + var portalSettings = new PortalSettings(portalId); + return this.HasStateReviewerPermission(portalSettings, user, stateId); } /// - public bool HasStateReviewerPermission(int stateId) - { - var user = this.userController.GetCurrentUserInfo(); - return this.HasStateReviewerPermission(PortalSettings.Current, user, stateId); + public bool HasStateReviewerPermission(int stateId) + { + var user = this.userController.GetCurrentUserInfo(); + return this.HasStateReviewerPermission(PortalSettings.Current, user, stateId); } /// - public bool IsWorkflowReviewer(int workflowId, int userId) - { - var workflow = this.workflowManager.GetWorkflow(workflowId); - return workflow.States.Any(contentWorkflowState => this.HasStateReviewerPermission(workflow.PortalID, userId, contentWorkflowState.StateID)); + public bool IsWorkflowReviewer(int workflowId, int userId) + { + var workflow = this.workflowManager.GetWorkflow(workflowId); + return workflow.States.Any(contentWorkflowState => this.HasStateReviewerPermission(workflow.PortalID, userId, contentWorkflowState.StateID)); } /// - public PermissionInfo GetStateReviewPermission() - { - return (PermissionInfo)new PermissionController().GetPermissionByCodeAndKey(ReviewPermissionCode, ReviewPermissionKey)[0]; + public PermissionInfo GetStateReviewPermission() + { + return (PermissionInfo)new PermissionController().GetPermissionByCodeAndKey(ReviewPermissionCode, ReviewPermissionKey)[0]; } /// - protected override Func GetFactory() - { - return () => new WorkflowSecurity(); - } - } -} + protected override Func GetFactory() + { + return () => new WorkflowSecurity(); + } + } +} diff --git a/DNN Platform/Library/Entities/Controllers/HostController.cs b/DNN Platform/Library/Entities/Controllers/HostController.cs index d2605324415..9e80375b028 100644 --- a/DNN Platform/Library/Entities/Controllers/HostController.cs +++ b/DNN Platform/Library/Entities/Controllers/HostController.cs @@ -269,7 +269,7 @@ private static Dictionary GetSettingsFromDatabase var config = new ConfigurationSetting { Key = key, - IsSecure = Convert.ToBoolean(dr[2]), + IsSecure = Convert.ToBoolean(dr[2], CultureInfo.InvariantCulture), Value = dr.IsDBNull(1) ? string.Empty : dr.GetString(1), }; diff --git a/DNN Platform/Library/Entities/DataStructures/NTree.cs b/DNN Platform/Library/Entities/DataStructures/NTree.cs index f45e492cb11..b1f300f6ec8 100644 --- a/DNN Platform/Library/Entities/DataStructures/NTree.cs +++ b/DNN Platform/Library/Entities/DataStructures/NTree.cs @@ -15,10 +15,12 @@ public class NTree { [DataMember(Name = "data")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public T Data; [DataMember(Name = "children")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public List> Children; /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/Entities/EventManager.cs b/DNN Platform/Library/Entities/EventManager.cs index 00a01f1cee2..ee680c341d9 100644 --- a/DNN Platform/Library/Entities/EventManager.cs +++ b/DNN Platform/Library/Entities/EventManager.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Entities { using System; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Abstractions.Logging; using DotNetNuke.Common; @@ -268,6 +269,7 @@ public virtual void OnFileMetadataChanged(FileChangedEventArgs args) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public virtual void OnFileDownloaded(FileDownloadedEventArgs args) { if (this.FileDownloaded != null) diff --git a/DNN Platform/Library/Entities/Host/Host.cs b/DNN Platform/Library/Entities/Host/Host.cs index 62a4c4b16b0..d148da74060 100644 --- a/DNN Platform/Library/Entities/Host/Host.cs +++ b/DNN Platform/Library/Entities/Host/Host.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Host { using System; + using System.Diagnostics.CodeAnalysis; using System.Web; using DotNetNuke.Common; @@ -275,6 +276,7 @@ public static string SMTPAuthProvider public static FileExtensionWhitelist DefaultEndUserExtensionWhitelist => new(HostController.Instance.GetString("DefaultEndUserExtensionWhitelist")); /// Gets the GUID. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] public static string GUID => HostController.Instance.GetString("GUID"); /// Gets the Help URL. diff --git a/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs b/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs index 06960618964..5a18a7fd5bb 100644 --- a/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs +++ b/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Host { + using System.Diagnostics.CodeAnalysis; using System.Globalization; using DotNetNuke.Entities.Controllers; @@ -18,6 +19,7 @@ public HostPropertyAccess() } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { if (propertyName.Equals("hosttitle", System.StringComparison.OrdinalIgnoreCase) || currentScope == Scope.Debug) diff --git a/DNN Platform/Library/Entities/Host/HostSettings.cs b/DNN Platform/Library/Entities/Host/HostSettings.cs index 4763f8090eb..0b337418281 100644 --- a/DNN Platform/Library/Entities/Host/HostSettings.cs +++ b/DNN Platform/Library/Entities/Host/HostSettings.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Host; using System; +using System.Diagnostics.CodeAnalysis; using DotNetNuke.Abstractions.Application; using DotNetNuke.Abstractions.Security; @@ -212,6 +213,7 @@ public string DefaultPortalSkin new FileExtensionWhitelist(hostSettingsService.GetString("DefaultEndUserExtensionWhitelist")); /// + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] public string Guid => GetHostGuid(hostSettingsService); /// diff --git a/DNN Platform/Library/Entities/Host/ServerController.cs b/DNN Platform/Library/Entities/Host/ServerController.cs index 479519642af..76639d4a4aa 100644 --- a/DNN Platform/Library/Entities/Host/ServerController.cs +++ b/DNN Platform/Library/Entities/Host/ServerController.cs @@ -5,10 +5,12 @@ namespace DotNetNuke.Entities.Host { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Web.Caching; + using DotNetNuke.Abstractions.Logging; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; @@ -152,9 +154,9 @@ public static void UpdateServerActivity(ServerInfo server) var log = new LogInfo(); log.AddProperty(existServer != null ? "Server Updated" : "Add New Server", server.ServerName); log.AddProperty("IISAppName", server.IISAppName); - log.AddProperty("Last Activity Date", server.LastActivityDate.ToString()); - log.LogTypeKey = existServer != null ? EventLogController.EventLogType.WEBSERVER_UPDATED.ToString() - : EventLogController.EventLogType.WEBSERVER_CREATED.ToString(); + log.AddProperty("Last Activity Date", server.LastActivityDate.ToString(CultureInfo.InvariantCulture)); + log.LogTypeKey = existServer != null ? nameof(EventLogType.WEBSERVER_UPDATED) + : nameof(EventLogType.WEBSERVER_CREATED); LogController.Instance.AddLog(log); } diff --git a/DNN Platform/Library/Entities/Host/ServerWebRequestAdapter.cs b/DNN Platform/Library/Entities/Host/ServerWebRequestAdapter.cs index ec2055c67e6..dab4b8b203d 100644 --- a/DNN Platform/Library/Entities/Host/ServerWebRequestAdapter.cs +++ b/DNN Platform/Library/Entities/Host/ServerWebRequestAdapter.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Host { + using System; using System.Net; using System.Web; @@ -18,13 +19,13 @@ public virtual string GetServerUrl() { domainName = Globals.GetDomainName(HttpContext.Current.Request); - if (domainName.Contains("/")) + if (domainName.Contains("/", StringComparison.Ordinal)) { - domainName = domainName.Substring(0, domainName.IndexOf("/")); + domainName = domainName.Substring(0, domainName.IndexOf("/", StringComparison.Ordinal)); if (!string.IsNullOrEmpty(Globals.ApplicationPath)) { - domainName = string.Format("{0}{1}", domainName, Globals.ApplicationPath); + domainName = $"{domainName}{Globals.ApplicationPath}"; } } } diff --git a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs index eadf070b5af..60ebac9ac57 100644 --- a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs +++ b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Host { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Web; @@ -140,6 +141,7 @@ public bool CanIPStillAccess(string myip, IList filterList) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public bool IsAllowableDeny(string currentIP, IPFilterInfo ipFilter) { if (ipFilter.RuleType == (int)FilterType.Allow) diff --git a/DNN Platform/Library/Entities/Icons/IconController.cs b/DNN Platform/Library/Entities/Icons/IconController.cs index 12994f84ed8..cef3e9d4785 100644 --- a/DNN Platform/Library/Entities/Icons/IconController.cs +++ b/DNN Platform/Library/Entities/Icons/IconController.cs @@ -74,7 +74,7 @@ public static string IconURL(string key, string size, string style) style = DefaultIconStyle; } - string fileName = string.Format("{0}/{1}_{2}_{3}.png", PortalSettings.Current.DefaultIconLocation, key, size, style); + string fileName = $"{PortalSettings.Current.DefaultIconLocation}/{key}_{size}_{style}.png"; // In debug mode, we want to warn (only once) if icon is not present on disk #if DEBUG @@ -136,7 +136,7 @@ private static void CheckIconOnDisk(string path) var iconPhysicalPath = Path.Combine(Globals.ApplicationMapPath, path.Replace('/', '\\')); if (!File.Exists(iconPhysicalPath)) { - Logger.WarnFormat(string.Format("Icon Not Present on Disk {0}", iconPhysicalPath)); + Logger.Warn($"Icon Not Present on Disk {iconPhysicalPath}"); } } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ActionEventHandler.cs b/DNN Platform/Library/Entities/Modules/Actions/ActionEventHandler.cs index f5523f5f0d9..c39adf838fe 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ActionEventHandler.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ActionEventHandler.cs @@ -4,8 +4,11 @@ namespace DotNetNuke.Entities.Modules.Actions { + using System.Diagnostics.CodeAnalysis; + /// The ActionEventHandler delegate defines a custom event handler for an Action Event. /// The event sender. /// The event arguments. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public delegate void ActionEventHandler(object sender, ActionEventArgs e); } diff --git a/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs b/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs index bfe42c27aee..1a83c03b02e 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs @@ -2,16 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Actions -{ - public interface IModuleEventHandler - { - void ModuleCreated(object sender, ModuleEventArgs args); - - void ModuleUpdated(object sender, ModuleEventArgs args); - - void ModuleRemoved(object sender, ModuleEventArgs args); - - void ModuleDeleted(object sender, ModuleEventArgs args); - } -} +namespace DotNetNuke.Entities.Modules.Actions +{ + using System.Diagnostics.CodeAnalysis; + + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public interface IModuleEventHandler + { + void ModuleCreated(object sender, ModuleEventArgs args); + + void ModuleUpdated(object sender, ModuleEventArgs args); + + void ModuleRemoved(object sender, ModuleEventArgs args); + + void ModuleDeleted(object sender, ModuleEventArgs args); + } +} diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs index 6f723c04f23..bdacf487524 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs @@ -3,6 +3,8 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Actions { + using System; + using DotNetNuke.Security; /// @@ -286,20 +288,20 @@ internal string ControlKey string controlKey = string.Empty; if (!string.IsNullOrEmpty(this.Url)) { - int startIndex = this.Url.IndexOf("/ctl/"); + int startIndex = this.Url.IndexOf("/ctl/", StringComparison.OrdinalIgnoreCase); int endIndex = -1; if (startIndex > -1) { startIndex += 4; - endIndex = this.Url.IndexOf("/", startIndex + 1); + endIndex = this.Url.IndexOf("/", startIndex + 1, StringComparison.Ordinal); } else { - startIndex = this.Url.IndexOf("ctl="); + startIndex = this.Url.IndexOf("ctl=", StringComparison.OrdinalIgnoreCase); if (startIndex > -1) { startIndex += 4; - endIndex = this.Url.IndexOf("&", startIndex + 1); + endIndex = this.Url.IndexOf("&", startIndex + 1, StringComparison.Ordinal); } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs index 0b005e313db..4b5e27e6fef 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs @@ -3,139 +3,80 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Actions { - using System.Collections; - + using DotNetNuke.Collections; using DotNetNuke.Security; - /// Represents a collection of objects. + /// Represents a collection of objects. /// The ModuleActionCollection is a custom collection of ModuleActions. /// Each ModuleAction in the collection has its own /// collection which provides the ability to create a hierarchy of ModuleActions. - public class ModuleActionCollection : CollectionBase + public class ModuleActionCollection : GenericCollectionBase { - /// - /// Initializes a new instance of the class. - /// Initializes a new, empty instance of the class. - /// - /// The default constructor creates an empty collection of - /// objects. + /// Initializes a new instance of the class. + /// The default constructor creates an empty collection of objects. public ModuleActionCollection() { } - /// - /// Initializes a new instance of the - /// class containing the elements of the specified source collection. - /// - /// A with which to initialize the collection. - /// This overloaded constructor copies the s - /// from the indicated collection. + /// Initializes a new instance of the class containing the elements of the specified source collection. + /// A with which to initialize the collection. + /// This overloaded constructor copies the s from the indicated collection. public ModuleActionCollection(ModuleActionCollection value) { this.AddRange(value); } - /// - /// Initializes a new instance of the - /// class containing the specified array of objects. - /// - /// An array of objects - /// with which to initialize the collection. - /// This overloaded constructor copies the s - /// from the indicated array. + /// Initializes a new instance of the class containing the specified array of objects. + /// An array of objects with which to initialize the collection. + /// This overloaded constructor copies the s from the indicated array. public ModuleActionCollection(ModuleAction[] value) { this.AddRange(value); } - /// - /// Gets or sets the at the - /// specified index in the collection. - /// - /// In VB.Net, this property is the indexer for the class. - /// - /// - /// The index of the collection to access. - /// A at each valid index. - /// This method is an indexer that can be used to access the collection. - public ModuleAction this[int index] - { - get - { - return (ModuleAction)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - /// Add an element of the specified to the end of the collection. - /// An object of type to add to the collection. - /// The index of the newly added . - public int Add(ModuleAction value) - { - return this.List.Add(value); - } - - /// Add an element of the specified to the end of the collection. + /// Add an element of the specified to the end of the collection. /// This is the identifier to use for this action. /// This is the title that will be displayed for this action. - /// The command name passed to the client when this action is - /// clicked. - /// The index of the newly added . - /// This method creates a new with the specified - /// values, adds it to the collection and returns the index of the newly created ModuleAction. + /// The command name passed to the client when this action is clicked. + /// The index of the newly added . + /// This method creates a new with the specified values, adds it to the collection and returns the index of the newly created ModuleAction. public ModuleAction Add(int iD, string title, string cmdName) { return this.Add(iD, title, cmdName, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false); } - /// Add an element of the specified to the end of the collection. + /// Add an element of the specified to the end of the collection. /// This is the identifier to use for this action. /// This is the title that will be displayed for this action. - /// The command name passed to the client when this action is - /// clicked. - /// The command argument passed to the client when this action is - /// clicked. + /// The command name passed to the client when this action is clicked. + /// The command argument passed to the client when this action is clicked. /// The URL of the Icon to place next to this action. - /// The destination URL to redirect the client browser when this - /// action is clicked. - /// Determines whether client will receive an event - /// notification. + /// The destination URL to redirect the client browser when this action is clicked. + /// Determines whether client will receive an event notification. /// The security access level required for access to this action. /// Whether this action will be displayed. /// Whether open in new window. - /// The index of the newly added . - /// This method creates a new with the specified - /// values, adds it to the collection and returns the index of the newly created ModuleAction. + /// The index of the newly added . + /// This method creates a new with the specified values, adds it to the collection and returns the index of the newly created ModuleAction. public ModuleAction Add(int iD, string title, string cmdName, string cmdArg, string icon, string url, bool useActionEvent, SecurityAccessLevel secure, bool visible, bool newWindow) { return this.Add(iD, title, cmdName, cmdArg, icon, url, string.Empty, useActionEvent, secure, visible, newWindow); } - /// Add an element of the specified to the end of the collection. + /// Add an element of the specified to the end of the collection. /// This is the identifier to use for this action. /// This is the title that will be displayed for this action. - /// The command name passed to the client when this action is - /// clicked. - /// The command argument passed to the client when this action is - /// clicked. + /// The command name passed to the client when this action is clicked. + /// The command argument passed to the client when this action is clicked. /// The URL of the Icon to place next to this action. - /// The destination URL to redirect the client browser when this - /// action is clicked. - /// Client side script to be run when this action is - /// clicked. - /// Determines whether client will receive an event - /// notification. + /// The destination URL to redirect the client browser when this action is clicked. + /// Client side script to be run when this action is clicked. + /// Determines whether client will receive an event notification. /// The security access level required for access to this action. /// Whether this action will be displayed. /// Whether open in new window. - /// The index of the newly added . - /// This method creates a new with the specified - /// values, adds it to the collection and returns the index of the newly created ModuleAction. - /// + /// The index of the newly added . + /// This method creates a new with the specified values, adds it to the collection and returns the index of the newly created ModuleAction. public ModuleAction Add(int iD, string title, string cmdName, string cmdArg, string icon, string url, string clientScript, bool useActionEvent, SecurityAccessLevel secure, bool visible, bool newWindow) { var modAction = new ModuleAction(iD, title, cmdName, cmdArg, icon, url, clientScript, useActionEvent, secure, visible, newWindow); @@ -143,12 +84,8 @@ public ModuleAction Add(int iD, string title, string cmdName, string cmdArg, str return modAction; } - /// - /// Copies the elements of the specified - /// array to the end of the collection. - /// - /// An array of type - /// containing the objects to add to the collection. + /// Copies the elements of the specified array to the end of the collection. + /// An array of type containing the objects to add to the collection. public void AddRange(ModuleAction[] value) { int i; @@ -158,12 +95,8 @@ public void AddRange(ModuleAction[] value) } } - /// - /// Adds the contents of another - /// to the end of the collection. - /// - /// A containing - /// the objects to add to the collection. + /// Adds the contents of another to the end of the collection. + /// A containing the objects to add to the collection. public void AddRange(ModuleActionCollection value) { foreach (ModuleAction mA in value) @@ -172,26 +105,6 @@ public void AddRange(ModuleActionCollection value) } } - /// Gets a value indicating whether the collection contains the specified . - /// The to search for in the collection. - /// true if the collection contains the specified object; otherwise, false. - /// - /// - /// ' Tests for the presence of a ModuleAction in the - /// ' collection, and retrieves its index if it is found. - /// Dim testModuleAction = New ModuleAction(5, "Edit Action", "Edit") - /// Dim itemIndex As Integer = -1 - /// If collection.Contains(testModuleAction) Then - /// itemIndex = collection.IndexOf(testModuleAction) - /// End If - /// - /// - public bool Contains(ModuleAction value) - { - // If value is not of type ModuleAction, this will return false. - return this.List.Contains(value); - } - public ModuleAction GetActionByCommandName(string name) { ModuleAction retAction = null; @@ -269,57 +182,5 @@ public ModuleAction GetActionByID(int id) return retAction; } - - /// - /// Gets the index in the collection of the specified , - /// if it exists in the collection. - /// - /// The to locate in the collection. - /// The index in the collection of the specified object, if found; otherwise, -1. - /// This example tests for the presence of a ModuleAction in the - /// collection, and retrieves its index if it is found. - /// - /// Dim testModuleAction = New ModuleAction(5, "Edit Action", "Edit") - /// Dim itemIndex As Integer = -1 - /// If collection.Contains(testModuleAction) Then - /// itemIndex = collection.IndexOf(testModuleAction) - /// End If - /// - /// - public int IndexOf(ModuleAction value) - { - return this.List.IndexOf(value); - } - - /// - /// Add an element of the specified to the - /// collection at the designated index. - /// - /// An Integer to indicate the location to add the object to the collection. - /// An object of type to add to the collection. - /// - /// - /// ' Inserts a ModuleAction at index 0 of the collection. - /// collection.Insert(0, New ModuleAction(5, "Edit Action", "Edit")) - /// - /// - public void Insert(int index, ModuleAction value) - { - this.List.Insert(index, value); - } - - /// Remove the specified object of type from the collection. - /// An object of type to remove from the collection. - /// - /// - /// ' Removes the specified ModuleAction from the collection. - /// Dim testModuleAction = New ModuleAction(5, "Edit Action", "Edit") - /// collection.Remove(testModuleAction) - /// - /// - public void Remove(ModuleAction value) - { - this.List.Remove(value); - } } } diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs index 9f86af35d4b..c7c5bd509c3 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs @@ -1,85 +1,60 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Communications -{ +namespace DotNetNuke.Entities.Modules.Communications +{ using System.Web.UI; - /// - /// Specifies communications between modules. - /// There are listeners and communicators. - /// - public class ModuleCommunicate - { - private readonly ModuleCommunicators moduleCommunicators = new ModuleCommunicators(); - - private readonly ModuleListeners moduleListeners = new ModuleListeners(); - - /// Gets the module communicators. - /// - /// The module communicators. - /// - public ModuleCommunicators ModuleCommunicators - { - get - { - return this.moduleCommunicators; - } - } - - /// Gets the module listeners. - /// - /// The module listeners. - /// - public ModuleListeners ModuleListeners - { - get - { - return this.moduleListeners; - } - } - - /// Loads the communicator. - /// The control. - public void LoadCommunicator(Control ctrl) - { - // Check and see if the module implements IModuleCommunicator - if (ctrl is IModuleCommunicator) - { - this.Add((IModuleCommunicator)ctrl); - } - - // Check and see if the module implements IModuleListener - if (ctrl is IModuleListener) - { - this.Add((IModuleListener)ctrl); - } - } - - private int Add(IModuleCommunicator item) - { - int returnData = this.moduleCommunicators.Add(item); - - int i = 0; - for (i = 0; i <= this.moduleListeners.Count - 1; i++) - { - item.ModuleCommunication += this.moduleListeners[i].OnModuleCommunication; - } - - return returnData; - } - - private int Add(IModuleListener item) - { - int returnData = this.moduleListeners.Add(item); - - int i = 0; - for (i = 0; i <= this.moduleCommunicators.Count - 1; i++) - { - this.moduleCommunicators[i].ModuleCommunication += item.OnModuleCommunication; - } - - return returnData; - } - } -} + /// Specifies communications between modules. There are listeners and communicators. + public class ModuleCommunicate + { + /// Gets the module communicators. + public ModuleCommunicators ModuleCommunicators { get; } = new ModuleCommunicators(); + + /// Gets the module listeners. + public ModuleListeners ModuleListeners { get; } = new ModuleListeners(); + + /// Loads the communicator. + /// The control. + public void LoadCommunicator(Control ctrl) + { + // Check and see if the module implements IModuleCommunicator + if (ctrl is IModuleCommunicator communicator) + { + this.Add(communicator); + } + + // Check and see if the module implements IModuleListener + if (ctrl is IModuleListener listener) + { + this.Add(listener); + } + } + + private int Add(IModuleCommunicator item) + { + int returnData = this.ModuleCommunicators.Add(item); + + int i = 0; + for (i = 0; i <= this.ModuleListeners.Count - 1; i++) + { + item.ModuleCommunication += this.ModuleListeners[i].OnModuleCommunication; + } + + return returnData; + } + + private int Add(IModuleListener item) + { + int returnData = this.ModuleListeners.Add(item); + + int i = 0; + for (i = 0; i <= this.ModuleCommunicators.Count - 1; i++) + { + this.ModuleCommunicators[i].ModuleCommunication += item.OnModuleCommunication; + } + + return returnData; + } + } +} diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventHandler.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventHandler.cs index 09ec41adf44..bfb9fbc9e3e 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventHandler.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicationEventHandler.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Communications -{ - public delegate void ModuleCommunicationEventHandler(object sender, ModuleCommunicationEventArgs e); -} +namespace DotNetNuke.Entities.Modules.Communications; + +using System.Diagnostics.CodeAnalysis; + +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] +public delegate void ModuleCommunicationEventHandler(object sender, ModuleCommunicationEventArgs e); diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs index 0337ab243b9..552d5d41aa5 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs @@ -1,28 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Communications -{ - using System.Collections; +namespace DotNetNuke.Entities.Modules.Communications; - public class ModuleCommunicators : CollectionBase - { - public IModuleCommunicator this[int index] - { - get - { - return (IModuleCommunicator)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public int Add(IModuleCommunicator item) - { - return this.List.Add(item); - } - } -} +using DotNetNuke.Collections; + +public class ModuleCommunicators : GenericCollectionBase; diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs index ab7f5a5d0c1..d06c3d0c279 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs @@ -1,28 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Communications -{ - using System.Collections; +namespace DotNetNuke.Entities.Modules.Communications; - public class ModuleListeners : CollectionBase - { - public IModuleListener this[int index] - { - get - { - return (IModuleListener)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public int Add(IModuleListener item) - { - return this.List.Add(item); - } - } -} +using DotNetNuke.Collections; + +public class ModuleListeners : GenericCollectionBase; diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs index 1f30f6a5c8a..4eac74bd909 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Modules.Definitions using System; using System.Collections.Generic; using System.Data; + using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; @@ -125,7 +126,7 @@ public void ReadXml(XmlReader reader) continue; } - if (reader.NodeType == XmlNodeType.Element && reader.Name == "moduleControls") + if (reader is { NodeType: XmlNodeType.Element, Name: "moduleControls", }) { this.ReadModuleControls(reader); } @@ -139,14 +140,14 @@ public void ReadXml(XmlReader reader) this.FriendlyName = reader.ReadElementContentAsString(); break; case "defaultCacheTime": - string elementvalue = reader.ReadElementContentAsString(); - if (!string.IsNullOrEmpty(elementvalue)) + string elementValue = reader.ReadElementContentAsString(); + if (!string.IsNullOrEmpty(elementValue)) { - this.DefaultCacheTime = int.Parse(elementvalue); + this.DefaultCacheTime = int.Parse(elementValue, CultureInfo.InvariantCulture); } break; - case "permissions": // Ignore permissons node + case "permissions": // Ignore permissions node reader.Skip(); break; case "definitionName": @@ -174,7 +175,7 @@ public void WriteXml(XmlWriter writer) // write out properties writer.WriteElementString("friendlyName", this.FriendlyName); writer.WriteElementString("definitionName", this.DefinitionName); - writer.WriteElementString("defaultCacheTime", this.DefaultCacheTime.ToString()); + writer.WriteElementString("defaultCacheTime", this.DefaultCacheTime.ToString(CultureInfo.InvariantCulture)); // Write start of Module Controls writer.WriteStartElement("moduleControls"); diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs index 69863f6fe07..2a8a1c77d70 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs @@ -1,136 +1,138 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Definitions -{ - using System.Diagnostics.CodeAnalysis; - using System.IO; - using System.Web; - using System.Xml; - - using DotNetNuke.Common; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Services.Localization; - - public enum ModuleDefinitionVersion - { - /// An unknown version. - VUnknown = 0, - - /// Version one. - V1 = 1, - - /// Version two. - V2 = 2, - - /// Version two of a skin. - V2_Skin = 3, - - /// Version two of a provider. - V2_Provider = 4, - - /// Version three. - V3 = 5, - } - - public class ModuleDefinitionValidator : XmlValidatorBase +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Entities.Modules.Definitions +{ + using System.Diagnostics.CodeAnalysis; + using System.IO; + using System.Web; + using System.Xml; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Localization; + + public enum ModuleDefinitionVersion { - [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Breaking change")] - public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) - { - ModuleDefinitionVersion retValue; - xmlStream.Seek(0, SeekOrigin.Begin); - var xmlReader = new XmlTextReader(xmlStream) - { - XmlResolver = null, - DtdProcessing = DtdProcessing.Prohibit, - }; - xmlReader.MoveToContent(); - - // This test assumes provides a simple validation - switch (xmlReader.LocalName.ToLowerInvariant()) - { - case "module": - retValue = ModuleDefinitionVersion.V1; - break; - case "dotnetnuke": - switch (xmlReader.GetAttribute("type")) - { - case "Module": - switch (xmlReader.GetAttribute("version")) - { - case "2.0": - retValue = ModuleDefinitionVersion.V2; - break; - case "3.0": - retValue = ModuleDefinitionVersion.V3; - break; - default: - return ModuleDefinitionVersion.VUnknown; - } - - break; - case "SkinObject": - retValue = ModuleDefinitionVersion.V2_Skin; - break; - case "Provider": - retValue = ModuleDefinitionVersion.V2_Provider; - break; - default: - retValue = ModuleDefinitionVersion.VUnknown; - break; - } - - break; - default: - retValue = ModuleDefinitionVersion.VUnknown; - break; - } - - return retValue; - } - - /// - public override bool Validate(Stream xmlStream) - { - this.SchemaSet.Add(string.Empty, this.GetDnnSchemaPath(xmlStream)); - return base.Validate(xmlStream); - } - - private static string GetLocalizedString(string key) - { - var objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; - if (objPortalSettings == null) - { - return key; - } - - return Localization.GetString(key, objPortalSettings); - } - - private string GetDnnSchemaPath(Stream xmlStream) - { - ModuleDefinitionVersion version = this.GetModuleDefinitionVersion(xmlStream); - string schemaPath = string.Empty; - switch (version) - { - case ModuleDefinitionVersion.V2: - schemaPath = "components\\ResourceInstaller\\ModuleDef_V2.xsd"; - break; - case ModuleDefinitionVersion.V3: - schemaPath = "components\\ResourceInstaller\\ModuleDef_V3.xsd"; - break; - case ModuleDefinitionVersion.V2_Skin: - schemaPath = "components\\ResourceInstaller\\ModuleDef_V2Skin.xsd"; - break; - case ModuleDefinitionVersion.V2_Provider: - schemaPath = "components\\ResourceInstaller\\ModuleDef_V2Provider.xsd"; - break; - case ModuleDefinitionVersion.VUnknown: - throw new UnknownModuleDefinitionVersionException(GetLocalizedString("EXCEPTION_LoadFailed")); - } - - return Path.Combine(Globals.ApplicationMapPath, schemaPath); - } - } -} + /// An unknown version. + VUnknown = 0, + + /// Version one. + V1 = 1, + + /// Version two. + V2 = 2, + + /// Version two of a skin. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + V2_Skin = 3, + + /// Version two of a provider. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] + V2_Provider = 4, + + /// Version three. + V3 = 5, + } + + public class ModuleDefinitionValidator : XmlValidatorBase + { + [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Breaking change")] + public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) + { + ModuleDefinitionVersion retValue; + xmlStream.Seek(0, SeekOrigin.Begin); + var xmlReader = new XmlTextReader(xmlStream) + { + XmlResolver = null, + DtdProcessing = DtdProcessing.Prohibit, + }; + xmlReader.MoveToContent(); + + // This test assumes provides a simple validation + switch (xmlReader.LocalName.ToLowerInvariant()) + { + case "module": + retValue = ModuleDefinitionVersion.V1; + break; + case "dotnetnuke": + switch (xmlReader.GetAttribute("type")) + { + case "Module": + switch (xmlReader.GetAttribute("version")) + { + case "2.0": + retValue = ModuleDefinitionVersion.V2; + break; + case "3.0": + retValue = ModuleDefinitionVersion.V3; + break; + default: + return ModuleDefinitionVersion.VUnknown; + } + + break; + case "SkinObject": + retValue = ModuleDefinitionVersion.V2_Skin; + break; + case "Provider": + retValue = ModuleDefinitionVersion.V2_Provider; + break; + default: + retValue = ModuleDefinitionVersion.VUnknown; + break; + } + + break; + default: + retValue = ModuleDefinitionVersion.VUnknown; + break; + } + + return retValue; + } + + /// + public override bool Validate(Stream xmlStream) + { + this.SchemaSet.Add(string.Empty, this.GetDnnSchemaPath(xmlStream)); + return base.Validate(xmlStream); + } + + private static string GetLocalizedString(string key) + { + var objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; + if (objPortalSettings == null) + { + return key; + } + + return Localization.GetString(key, objPortalSettings); + } + + private string GetDnnSchemaPath(Stream xmlStream) + { + ModuleDefinitionVersion version = this.GetModuleDefinitionVersion(xmlStream); + string schemaPath = string.Empty; + switch (version) + { + case ModuleDefinitionVersion.V2: + schemaPath = "components\\ResourceInstaller\\ModuleDef_V2.xsd"; + break; + case ModuleDefinitionVersion.V3: + schemaPath = "components\\ResourceInstaller\\ModuleDef_V3.xsd"; + break; + case ModuleDefinitionVersion.V2_Skin: + schemaPath = "components\\ResourceInstaller\\ModuleDef_V2Skin.xsd"; + break; + case ModuleDefinitionVersion.V2_Provider: + schemaPath = "components\\ResourceInstaller\\ModuleDef_V2Provider.xsd"; + break; + case ModuleDefinitionVersion.VUnknown: + throw new UnknownModuleDefinitionVersionException(GetLocalizedString("EXCEPTION_LoadFailed")); + } + + return Path.Combine(Globals.ApplicationMapPath, schemaPath); + } + } +} diff --git a/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs b/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs index 8deb7a52232..d097858efdd 100644 --- a/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Entities.Modules using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Xml; @@ -99,7 +100,7 @@ public static DesktopModuleInfo GetDesktopModule(int desktopModuleID, int portal if (module == null) { - Logger.WarnFormat("Unable to find module by module ID. ID:{0} PortalID:{1}", desktopModuleID, portalID); + Logger.WarnFormat(CultureInfo.InvariantCulture, "Unable to find module by module ID. ID:{0} PortalID:{1}", desktopModuleID, portalID); } return module; @@ -110,35 +111,37 @@ public static DesktopModuleInfo GetDesktopModule(int desktopModuleID, int portal /// The or . public static DesktopModuleInfo GetDesktopModuleByPackageID(int packageID) { - DesktopModuleInfo desktopModuleByPackageID = (from kvp in GetDesktopModulesInternal(Null.NullInteger) - where kvp.Value.PackageID == packageID - select kvp.Value) + var desktopModuleByPackageId = ( + from kvp in GetDesktopModulesInternal(Null.NullInteger) + where kvp.Value.PackageID == packageID + select kvp.Value) .FirstOrDefault(); - if (desktopModuleByPackageID == null) + if (desktopModuleByPackageId == null) { - Logger.WarnFormat("Unable to find module by package ID. ID:{0}", packageID); + Logger.WarnFormat(CultureInfo.InvariantCulture, "Unable to find module by package ID. ID:{0}", packageID); } - return desktopModuleByPackageID; + return desktopModuleByPackageId; } /// GetDesktopModuleByModuleName gets a Desktop Module by its Name. /// This method uses the cached Dictionary of DesktopModules. It first checks /// if the DesktopModule is in the cache. If it is not in the cache it then makes a call - /// to the Dataprovider. + /// to the DataProvider. /// The name of the Desktop Module to get. /// The ID of the portal. /// The or . public static DesktopModuleInfo GetDesktopModuleByModuleName(string moduleName, int portalID) { - DesktopModuleInfo desktopModuleByModuleName = (from kvp in GetDesktopModulesInternal(portalID) - where kvp.Value.ModuleName == moduleName - select kvp.Value).FirstOrDefault(); + var desktopModuleByModuleName = + (from kvp in GetDesktopModulesInternal(portalID) + where kvp.Value.ModuleName == moduleName + select kvp.Value).FirstOrDefault(); if (desktopModuleByModuleName == null) { - Logger.WarnFormat("Unable to find module by name. Name:{0} portalId:{1}", moduleName, portalID); + Logger.WarnFormat(CultureInfo.InvariantCulture, "Unable to find module by name. Name:{0} portalId:{1}", moduleName, portalID); } return desktopModuleByModuleName; @@ -158,7 +161,7 @@ public static DesktopModuleInfo GetDesktopModuleByFriendlyName(string friendlyNa if (module == null) { - Logger.WarnFormat("Unable to find module by friendly name. Name:{0}", friendlyName); + Logger.WarnFormat(CultureInfo.InvariantCulture, "Unable to find module by friendly name. Name:{0}", friendlyName); } return module; @@ -199,7 +202,7 @@ public static int AddDesktopModuleToPortal(int portalId, int desktopModuleId, bo portalDesktopModuleID = DataProvider.Instance().AddPortalDesktopModule(portalId, desktopModuleId, UserController.Instance.GetCurrentUserInfo().UserID); EventLogController.Instance.AddLog( "PortalDesktopModuleID", - portalDesktopModuleID.ToString(), + portalDesktopModuleID.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALDESKTOPMODULE_CREATED); @@ -274,7 +277,7 @@ public static Dictionary GetPortalDesktopModulesBy public static Dictionary GetPortalDesktopModulesByPortalID(int portalId) { - string cacheKey = string.Format(DataCache.PortalDesktopModuleCacheKey, portalId); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PortalDesktopModuleCacheKey, portalId); return CBO.GetCachedObject>( new CacheItemArgs(cacheKey, DataCache.PortalDesktopModuleCacheTimeOut, DataCache.PortalDesktopModuleCachePriority, portalId), GetPortalDesktopModulesByPortalIDCallBack); @@ -300,7 +303,7 @@ public static void RemoveDesktopModuleFromPortal(int portalId, int desktopModule DataProvider.Instance().DeletePortalDesktopModules(portalId, desktopModuleId); EventLogController.Instance.AddLog( "DesktopModuleID", - desktopModuleId.ToString(), + desktopModuleId.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); @@ -315,7 +318,7 @@ public static void RemoveDesktopModuleFromPortals(int desktopModuleId) DataProvider.Instance().DeletePortalDesktopModules(Null.NullInteger, desktopModuleId); EventLogController.Instance.AddLog( "DesktopModuleID", - desktopModuleId.ToString(), + desktopModuleId.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); @@ -327,7 +330,7 @@ public static void RemoveDesktopModulesFromPortal(int portalId) DataProvider.Instance().DeletePortalDesktopModules(portalId, Null.NullInteger); EventLogController.Instance.AddLog( "PortalID", - portalId.ToString(), + portalId.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALDESKTOPMODULE_DELETED); @@ -374,7 +377,7 @@ public void DeleteDesktopModule(int desktopModuleID) DataProvider.DeleteDesktopModule(desktopModuleID); EventLogController.Instance.AddLog( "DesktopModuleID", - desktopModuleID.ToString(), + desktopModuleID.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.DESKTOPMODULE_DELETED); @@ -401,7 +404,7 @@ public void UpdateModuleInterfaces(ref DesktopModuleInfo desktopModuleInfo, stri ProcessorCommand = "UpdateSupportedFeatures", }; oAppStartMessage.Attributes.Add("BusinessControllerClass", desktopModuleInfo.BusinessControllerClass); - oAppStartMessage.Attributes.Add("DesktopModuleId", desktopModuleInfo.DesktopModuleID.ToString()); + oAppStartMessage.Attributes.Add("DesktopModuleId", desktopModuleInfo.DesktopModuleID.ToString(CultureInfo.InvariantCulture)); EventQueueController.SendMessage(oAppStartMessage, "Application_Start"); if (forceAppRestart) { @@ -577,7 +580,7 @@ internal static void AddDesktopModuleToPage(DesktopModuleInfo desktopModule, Tab private static Dictionary GetDesktopModulesInternal(int portalID) { - string cacheKey = string.Format(DataCache.DesktopModuleCacheKey, portalID); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.DesktopModuleCacheKey, portalID); var args = new CacheItemArgs(cacheKey, DataCache.DesktopModuleCacheTimeOut, DataCache.DesktopModuleCachePriority, portalID); Dictionary desktopModules = (portalID == Null.NullInteger) ? CBO.GetCachedObject>(args, GetDesktopModulesCallBack) diff --git a/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs b/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs index 4f8c9cccc02..8dc9b7b3ac7 100644 --- a/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs +++ b/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Entities.Modules { using System; + using System.Globalization; using System.Web; using DotNetNuke.Abstractions.Logging; @@ -62,10 +63,10 @@ public static void CreateImportModuleMessage(ModuleInfo objModule, string conten // Add custom Attributes for this message appStartMessage.Attributes.Add("BusinessControllerClass", objModule.DesktopModule.BusinessControllerClass); - appStartMessage.Attributes.Add("ModuleId", objModule.ModuleID.ToString()); + appStartMessage.Attributes.Add("ModuleId", objModule.ModuleID.ToString(CultureInfo.InvariantCulture)); appStartMessage.Attributes.Add("Content", content); appStartMessage.Attributes.Add("Version", version); - appStartMessage.Attributes.Add("UserID", userId.ToString()); + appStartMessage.Attributes.Add("UserID", userId.ToString(CultureInfo.InvariantCulture)); // send it to occur on next App_Start Event EventQueueController.SendMessage(appStartMessage, "Application_Start_FirstRequest"); @@ -106,7 +107,7 @@ private static void UpdateSupportedFeatures(EventMessage message) { var businessControllerClass = message.Attributes["BusinessControllerClass"]; var controllerType = Reflection.CreateType(businessControllerClass); - UpdateSupportedFeatures(controllerType, Convert.ToInt32(message.Attributes["DesktopModuleId"])); + UpdateSupportedFeatures(controllerType, Convert.ToInt32(message.Attributes["DesktopModuleId"], CultureInfo.InvariantCulture)); } private static void UpdateSupportedFeatures(Type controllerType, int desktopModuleId) @@ -130,8 +131,8 @@ private static void UpdateSupportedFeatures(Type controllerType, int desktopModu foreach (IPortalInfo portal in PortalController.Instance.GetPortals()) { - DataCache.RemoveCache(string.Format(DataCache.DesktopModuleCacheKey, portal.PortalId)); - DataCache.RemoveCache(string.Format(DataCache.PortalDesktopModuleCacheKey, portal.PortalId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.DesktopModuleCacheKey, portal.PortalId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.PortalDesktopModuleCacheKey, portal.PortalId)); } } catch (Exception exc) @@ -150,10 +151,10 @@ private void ImportModule(EventMessage message) return; } - var moduleId = Convert.ToInt32(message.Attributes["ModuleId"]); + var moduleId = Convert.ToInt32(message.Attributes["ModuleId"], CultureInfo.InvariantCulture); var content = HttpUtility.HtmlDecode(message.Attributes["Content"]); var version = message.Attributes["Version"]; - var userId = Convert.ToInt32(message.Attributes["UserId"]); + var userId = Convert.ToInt32(message.Attributes["UserId"], CultureInfo.InvariantCulture); // call the IPortable interface for the module/version controller.ImportModule(moduleId, content, version, userId); @@ -184,7 +185,7 @@ private void UpgradeModule(EventMessage message) var results = controller.UpgradeModule(version); // log the upgrade results - var log = new LogInfo { LogTypeKey = EventLogType.MODULE_UPDATED.ToString(), }; + var log = new LogInfo { LogTypeKey = nameof(EventLogType.MODULE_UPDATED), }; log.AddProperty("Module Upgraded", businessControllerClass); log.AddProperty("Version", version); if (!string.IsNullOrEmpty(results)) @@ -196,7 +197,7 @@ private void UpgradeModule(EventMessage message) } } - var desktopModuleId = Convert.ToInt32(message.Attributes["DesktopModuleId"]); + var desktopModuleId = Convert.ToInt32(message.Attributes["DesktopModuleId"], CultureInfo.InvariantCulture); UpdateSupportedFeatures(businessControllerType, desktopModuleId); } catch (Exception exc) diff --git a/DNN Platform/Library/Entities/Modules/IModuleController.cs b/DNN Platform/Library/Entities/Modules/IModuleController.cs index 4a718add6ea..82fa9670b58 100644 --- a/DNN Platform/Library/Entities/Modules/IModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/IModuleController.cs @@ -6,13 +6,14 @@ namespace DotNetNuke.Entities.Modules using System; using System.Collections; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Entities.Tabs; using DotNetNuke.Services.Localization; /// - /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. + /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should be used as a type and for unit test purposes only. /// There is no guarantee that this interface will not change. /// public interface IModuleController @@ -20,6 +21,7 @@ public interface IModuleController /// add a module to a page. /// moduleInfo for the module to create. /// ID of the created module. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] int AddModule(ModuleInfo module); /// Clears the module cache based on the page (tabid). @@ -52,6 +54,7 @@ public interface IModuleController /// 2. add a content item. /// /// the module to add a content item for. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void CreateContentItem(ModuleInfo module); /// @@ -150,7 +153,7 @@ public interface IModuleController ArrayList GetModulesByDefinition(int portalID, string definitionName); /// Gets the modules by DesktopModuleId. - /// The Desktop Module Id. + /// The Desktop Module ID. /// module collection. ArrayList GetModulesByDesktopModuleId(int desktopModuleId); @@ -177,6 +180,7 @@ public interface IModuleController /// ArrayList of ModuleInfo. IList GetTabModulesByModule(int moduleID); + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void InitialModulePermission(ModuleInfo module, int tabId, int permissionType); void LocalizeModule(ModuleInfo sourceModule, Locale locale); @@ -194,6 +198,7 @@ public interface IModuleController /// Update module settings and permissions in database from ModuleInfo. /// ModuleInfo of the module to update. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void UpdateModule(ModuleInfo module); /// set/change the module position within a pane on a page. @@ -223,17 +228,19 @@ public interface IModuleController /// Updates the translation status. /// The localized module. - /// if set to will mark the module as translated]. + /// if set to will mark the module as translated. void UpdateTranslationStatus(ModuleInfo localizedModule, bool isTranslated); /// Check if a ModuleInfo belongs to the referenced Tab or not. /// A ModuleInfo object to be checked. /// True is TabId points to a different tab from initial Tab where the module was added. Otherwise, False. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] bool IsSharedModule(ModuleInfo module); /// Get the Tab ID corresponding to the initial Tab where the module was added. /// A ModuleInfo object to be checked. - /// The Tab Id from initial Tab where the module was added. + /// The Tab ID from initial Tab where the module was added. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] int GetMasterTabId(ModuleInfo module); } } diff --git a/DNN Platform/Library/Entities/Modules/InstalledModuleInfo.cs b/DNN Platform/Library/Entities/Modules/InstalledModuleInfo.cs index 73d77ab475e..3dfcab35761 100644 --- a/DNN Platform/Library/Entities/Modules/InstalledModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/InstalledModuleInfo.cs @@ -1,34 +1,35 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules -{ +namespace DotNetNuke.Entities.Modules +{ + using System.Globalization; using System.Xml; - public class InstalledModuleInfo - { - public int DesktopModuleId { get; set; } - - public int Instances { get; set; } - - public string FriendlyName { get; set; } - - public string ModuleName { get; set; } - - public string Version { get; set; } - - public void WriteXml(XmlWriter writer) - { - // Write start of main elemenst - writer.WriteStartElement("module"); - - writer.WriteElementString("moduleName", this.ModuleName); - writer.WriteElementString("friendlyName", this.FriendlyName); - writer.WriteElementString("version", this.Version); - writer.WriteElementString("instances", this.Instances.ToString()); - - // Write end of Host Info - writer.WriteEndElement(); - } - } -} + public class InstalledModuleInfo + { + public int DesktopModuleId { get; set; } + + public int Instances { get; set; } + + public string FriendlyName { get; set; } + + public string ModuleName { get; set; } + + public string Version { get; set; } + + public void WriteXml(XmlWriter writer) + { + // Write start of main elements + writer.WriteStartElement("module"); + + writer.WriteElementString("moduleName", this.ModuleName); + writer.WriteElementString("friendlyName", this.FriendlyName); + writer.WriteElementString("version", this.Version); + writer.WriteElementString("instances", this.Instances.ToString(CultureInfo.InvariantCulture)); + + // Write end of Host Info + writer.WriteEndElement(); + } + } +} diff --git a/DNN Platform/Library/Entities/Modules/ModuleControlController.cs b/DNN Platform/Library/Entities/Modules/ModuleControlController.cs index 89c0488cda9..5dd965283f9 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleControlController.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleControlController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Modules { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Common.Utilities; @@ -81,7 +82,7 @@ public static int SaveModuleControl(ModuleControlInfo moduleControl, bool clearC moduleControl.ControlTitle, moduleControl.ControlSrc, moduleControl.IconFile, - Convert.ToInt32(moduleControl.ControlType), + (int)moduleControl.ControlType, moduleControl.ViewOrder, moduleControl.HelpURL, moduleControl.SupportsPartialRendering, @@ -98,7 +99,7 @@ public static int SaveModuleControl(ModuleControlInfo moduleControl, bool clearC moduleControl.ControlTitle, moduleControl.ControlSrc, moduleControl.IconFile, - Convert.ToInt32(moduleControl.ControlType), + (int)moduleControl.ControlType, moduleControl.ViewOrder, moduleControl.HelpURL, moduleControl.SupportsPartialRendering, diff --git a/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs index 884790b058b..09ca50a0eb7 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Modules { using System; using System.Data; + using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; @@ -122,10 +123,10 @@ public void ReadXml(XmlReader reader) this.SupportsPopUps = bool.Parse(reader.ReadElementContentAsString()); break; case "viewOrder": - string elementvalue = reader.ReadElementContentAsString(); - if (!string.IsNullOrEmpty(elementvalue)) + string elementValue = reader.ReadElementContentAsString(); + if (!string.IsNullOrEmpty(elementValue)) { - this.ViewOrder = int.Parse(elementvalue); + this.ViewOrder = int.Parse(elementValue, CultureInfo.InvariantCulture); } break; @@ -156,7 +157,7 @@ public void WriteXml(XmlWriter writer) writer.WriteElementString("supportsPopUps", this.SupportsPopUps.ToString()); if (this.ViewOrder > Null.NullInteger) { - writer.WriteElementString("viewOrder", this.ViewOrder.ToString()); + writer.WriteElementString("viewOrder", this.ViewOrder.ToString(CultureInfo.InvariantCulture)); } // Write end of main element diff --git a/DNN Platform/Library/Entities/Modules/ModuleController.cs b/DNN Platform/Library/Entities/Modules/ModuleController.cs index 8ba7bb8065a..1545fe971c1 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleController.cs @@ -74,7 +74,7 @@ public static void DeserializeModule(IBusinessControllerProvider businessControl // Create pane node for private DeserializeModule method var docPane = new XmlDocument { XmlResolver = null }; - docPane.LoadXml(string.Format("{0}", module.PaneName)); + docPane.LoadXml($"{module.PaneName}"); // Create ModuleInfo of Xml ModuleInfo sourceModule = DeserializeModule(nodeModule, docPane.DocumentElement, portalId, tabId, moduleDefinition.ModuleDefID); @@ -192,7 +192,7 @@ public static void DeserializeModule(IBusinessControllerProvider businessControl else { // Add instance - module.ModuleID = Convert.ToInt32(hModules[templateModuleId]); + module.ModuleID = Convert.ToInt32(hModules[templateModuleId], CultureInfo.InvariantCulture); intModuleId = Instance.AddModule(module); } @@ -802,7 +802,7 @@ public int DeLocalizeModule(ModuleInfo sourceModule) newModule.CultureCode, UserController.Instance.GetCurrentUserInfo().UserID); - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); // Update tab version details of old and new modules var userId = UserController.Instance.GetCurrentUserInfo().UserID; @@ -876,6 +876,7 @@ public ModuleInfo GetModule(int moduleID, int tabID) /// ID of the page. /// flag, if data shall not be taken from cache. /// ModuleInfo object. + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public ModuleInfo GetModule(int moduleID, int tabID, bool ignoreCache) { ModuleInfo modInfo = null; @@ -956,7 +957,7 @@ public ModuleInfo GetModuleByDefinition(int portalId, string definitionName) ModuleInfo module; // format cache key - string key = string.Format(DataCache.ModuleCacheKey, portalId); + string key = string.Format(CultureInfo.InvariantCulture, DataCache.ModuleCacheKey, portalId); // get module dictionary from cache var modules = DataCache.GetCache>(key) ?? new Dictionary(); @@ -988,7 +989,7 @@ public ModuleInfo GetModuleByDefinition(int portalId, string definitionName) clonemodules[module.ModuleDefinition.FriendlyName] = module; // set module caching settings - int timeOut = DataCache.ModuleCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); + int timeOut = DataCache.ModuleCacheTimeOut * (int)Host.Host.PerformanceSetting; // cache module dictionary if (timeOut > 0) @@ -1059,7 +1060,7 @@ public ArrayList GetSearchModules(int portalID) /// An ModuleInfo object. public ModuleInfo GetTabModule(int tabModuleID) { - var cacheKey = string.Format(DataCache.SingleTabModuleCacheKey, tabModuleID); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.SingleTabModuleCacheKey, tabModuleID); return CBO.GetCachedObject( new CacheItemArgs(cacheKey, DataCache.TabModuleCacheTimeOut, DataCache.TabModuleCachePriority), c => CBO.FillObject(DataProvider.GetTabModule(tabModuleID))); @@ -1068,7 +1069,7 @@ public ModuleInfo GetTabModule(int tabModuleID) /// public Dictionary GetTabModules(int tabId) { - var cacheKey = string.Format(DataCache.TabModuleCacheKey, tabId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabModuleCacheKey, tabId); return CBO.GetCachedObject>( new CacheItemArgs( cacheKey, @@ -1192,17 +1193,17 @@ public void LocalizeModule(ModuleInfo sourceModule, Locale locale) } catch (Exception ex) { - Logger.ErrorFormat("Error localizing module, moduleId: {0}, full exception: {1}", sourceModule.ModuleID, ex); + Logger.ErrorFormat(CultureInfo.InvariantCulture, "Error localizing module, moduleId: {0}, full exception: {1}", sourceModule.ModuleID, ex); } } /// - /// MoveModule moes a Module from one Tab to another including all the + /// MoveModule moves a Module from one Tab to another including all the /// TabModule settings. /// - /// The Id of the module to move. - /// The Id of the source tab. - /// The Id of the destination tab. + /// The ID of the module to move. + /// The ID of the source tab. + /// The ID of the destination tab. /// The name of the Pane on the destination tab where the module will end up. public void MoveModule(int moduleId, int fromTabId, int toTabId, string toPaneName) { @@ -1321,7 +1322,7 @@ public void UpdateModule(ModuleInfo module) module.CultureCode, currentUser.UserID); - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, module.TabModuleID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.SingleTabModuleCacheKey, module.TabModuleID)); EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.TABMODULE_UPDATED); @@ -1397,7 +1398,7 @@ public void UpdateModule(ModuleInfo module) targetModule.CultureCode, currentUser.UserID); - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, targetModule.TabModuleID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.SingleTabModuleCacheKey, targetModule.TabModuleID)); this.ClearCache(targetModule.TabID); } } @@ -1432,7 +1433,7 @@ public void UpdateModuleOrder(int tabId, int moduleId, int moduleOrder, string p dr = DataProvider.GetTabModuleOrder(tabId, paneName); while (dr.Read()) { - moduleOrder = Convert.ToInt32(dr["ModuleOrder"]); + moduleOrder = Convert.ToInt32(dr["ModuleOrder"], CultureInfo.InvariantCulture); } } catch (Exception ex) @@ -1475,17 +1476,17 @@ public void UpdateTabModuleOrder(int tabId) while (dr.Read()) { int moduleCounter = 0; - IDataReader dr2 = DataProvider.GetTabModuleOrder(tabId, Convert.ToString(dr["PaneName"])); + IDataReader dr2 = DataProvider.GetTabModuleOrder(tabId, Convert.ToString(dr["PaneName"], CultureInfo.InvariantCulture)); try { while (dr2.Read()) { moduleCounter += 1; - var moduleId = Convert.ToInt32(dr2["ModuleID"]); - var paneName = Convert.ToString(dr["PaneName"]); - var isDeleted = Convert.ToBoolean(dr2["IsDeleted"]); - var existingOrder = Convert.ToInt32(dr2["ModuleOrder"]); + var moduleId = Convert.ToInt32(dr2["ModuleID"], CultureInfo.InvariantCulture); + var paneName = Convert.ToString(dr["PaneName"], CultureInfo.InvariantCulture); + var isDeleted = Convert.ToBoolean(dr2["IsDeleted"], CultureInfo.InvariantCulture); + var existingOrder = Convert.ToInt32(dr2["ModuleOrder"], CultureInfo.InvariantCulture); var newOrder = (moduleCounter * 2) - 1; if (existingOrder == newOrder) @@ -1604,7 +1605,7 @@ public void UpdateTranslationStatus(ModuleInfo localizedModule, bool isTranslate [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Breaking change")] internal Hashtable GetModuleSettings(int moduleId, int tabId) { - string cacheKey = string.Format(DataCache.ModuleSettingsCacheKey, tabId); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.ModuleSettingsCacheKey, tabId); var moduleSettings = CBO.GetCachedObject>( new CacheItemArgs( @@ -1645,7 +1646,7 @@ internal Hashtable GetModuleSettings(int moduleId, int tabId) [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Breaking change")] internal Hashtable GetTabModuleSettings(int tabModuleId, int tabId) { - string cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tabId); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabModuleSettingsCacheKey, tabId); var tabModuleSettings = CBO.GetCachedObject>( new CacheItemArgs( @@ -1782,7 +1783,7 @@ private static void ClearModuleSettingsCache(int moduleId) { foreach (var tab in TabController.Instance.GetTabsByModuleID(moduleId).Values) { - string cacheKey = string.Format(DataCache.ModuleSettingsCacheKey, tab.TabID); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.ModuleSettingsCacheKey, tab.TabID); DataCache.RemoveCache(cacheKey); } } @@ -1792,13 +1793,13 @@ private static void ClearTabModuleSettingsCache(int tabModuleId, string settingN var portalId = -1; foreach (var tab in TabController.Instance.GetTabsByTabModuleID(tabModuleId).Values) { - var cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tab.TabID); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabModuleSettingsCacheKey, tab.TabID); DataCache.RemoveCache(cacheKey); if (portalId != tab.PortalID) { portalId = tab.PortalID; - cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName ?? string.Empty); + cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabModuleSettingsNameCacheKey, portalId, settingName ?? string.Empty); DataCache.RemoveCache(cacheKey); } } @@ -1880,10 +1881,10 @@ private static void DeserializeModulePermissions(XmlNodeList nodeModulePermissio switch (roleName) { case Globals.glbRoleAllUsersName: - roleID = Convert.ToInt32(Globals.glbRoleAllUsers); + roleID = Convert.ToInt32(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture); break; case Globals.glbRoleUnauthUserName: - roleID = Convert.ToInt32(Globals.glbRoleUnauthUser); + roleID = Convert.ToInt32(Globals.glbRoleUnauthUser, CultureInfo.InvariantCulture); break; default: var role = RoleController.Instance.GetRole(portalId, r => r.RoleName == roleName); @@ -2235,7 +2236,7 @@ private void CopyTabModuleSettingsInternal(ModuleInfo fromModule, ModuleInfo toM // Copy each setting to the new TabModule instance foreach (DictionaryEntry setting in fromModule.TabModuleSettings) { - this.UpdateTabModuleSetting(toModule.TabModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); + this.UpdateTabModuleSetting(toModule.TabModuleID, Convert.ToString(setting.Key, CultureInfo.InvariantCulture), Convert.ToString(setting.Value, CultureInfo.InvariantCulture)); } } @@ -2249,33 +2250,33 @@ private int LocalizeModuleInternal(ModuleInfo sourceModule) var newModule = sourceModule.Clone(); newModule.ModuleID = Null.NullInteger; - string translatorRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", sourceModule.CultureCode), sourceModule.PortalID, string.Empty).TrimEnd(';'); + string translatorRoles = PortalController.GetPortalSetting($"DefaultTranslatorRoles-{sourceModule.CultureCode}", sourceModule.PortalID, string.Empty).TrimEnd(';'); // Add the default translators for this language, view and edit permissions var permissionController = new PermissionController(); var viewPermissionsList = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); var editPermissionsList = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "EDIT"); - PermissionInfo viewPermisison = null; - PermissionInfo editPermisison = null; + PermissionInfo viewPermission = null; + PermissionInfo editPermission = null; // View if (viewPermissionsList != null && viewPermissionsList.Count > 0) { - viewPermisison = (PermissionInfo)viewPermissionsList[0]; + viewPermission = (PermissionInfo)viewPermissionsList[0]; } // Edit if (editPermissionsList != null && editPermissionsList.Count > 0) { - editPermisison = (PermissionInfo)editPermissionsList[0]; + editPermission = (PermissionInfo)editPermissionsList[0]; } - if (viewPermisison != null || editPermisison != null) + if (viewPermission != null || editPermission != null) { foreach (string translatorRole in translatorRoles.Split(';')) { - AddModulePermission(ref newModule, sourceModule.PortalID, translatorRole, viewPermisison, "VIEW"); - AddModulePermission(ref newModule, sourceModule.PortalID, translatorRole, editPermisison, "EDIT"); + AddModulePermission(ref newModule, sourceModule.PortalID, translatorRole, viewPermission, "VIEW"); + AddModulePermission(ref newModule, sourceModule.PortalID, translatorRole, editPermission, "EDIT"); } } @@ -2286,7 +2287,7 @@ private int LocalizeModuleInternal(ModuleInfo sourceModule) this.AddModuleInternal(newModule); // copy module settings - DataCache.RemoveCache(string.Format(DataCache.ModuleSettingsCacheKey, sourceModule.TabID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.ModuleSettingsCacheKey, sourceModule.TabID)); var settings = this.GetModuleSettings(sourceModule.ModuleID, sourceModule.TabID); // update tabmodule @@ -2317,12 +2318,12 @@ private int LocalizeModuleInternal(ModuleInfo sourceModule) newModule.CultureCode, currentUser.UserID); - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); // Copy each setting to the new TabModule instance foreach (DictionaryEntry setting in settings) { - this.UpdateModuleSetting(newModule.ModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); + this.UpdateModuleSetting(newModule.ModuleID, Convert.ToString(setting.Key, CultureInfo.InvariantCulture), Convert.ToString(setting.Value, CultureInfo.InvariantCulture)); } try @@ -2431,8 +2432,7 @@ private void UpdateModuleSettings(ModuleInfo updatedModule) { foreach (string key in updatedModule.ModuleSettings.Keys) { - string sKey = key; - this.UpdateModuleSettingInternal(updatedModule.ModuleID, sKey, Convert.ToString(updatedModule.ModuleSettings[sKey]), false); + this.UpdateModuleSettingInternal(updatedModule.ModuleID, key, Convert.ToString(updatedModule.ModuleSettings[key], CultureInfo.InvariantCulture), false); } this.UpdateTabModuleVersionsByModuleID(updatedModule.ModuleID); @@ -2442,7 +2442,7 @@ private void UpdateTabModuleSettings(ModuleInfo updatedTabModule) { foreach (string sKey in updatedTabModule.TabModuleSettings.Keys) { - this.UpdateTabModuleSetting(updatedTabModule.TabModuleID, sKey, Convert.ToString(updatedTabModule.TabModuleSettings[sKey])); + this.UpdateTabModuleSetting(updatedTabModule.TabModuleID, sKey, Convert.ToString(updatedTabModule.TabModuleSettings[sKey], CultureInfo.InvariantCulture)); } } @@ -2502,7 +2502,7 @@ private void DeleteTabModuleInternal(ModuleInfo moduleInfo, bool softDelete, boo this.DeleteModule(moduleInfo.ModuleID); } - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID)); this.ClearCache(moduleInfo.TabID); } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs index 6e3187179ad..32a364e77ac 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Entities.Modules using System.Collections; using System.Collections.Generic; using System.Data; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Xml.Serialization; @@ -617,6 +618,7 @@ public override void Fill(IDataReader dr) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { string outputFormat = string.Empty; diff --git a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs index bea96b5ec17..fe39cb9f66c 100644 --- a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs @@ -132,7 +132,7 @@ public string CacheFileName string strCacheKey = "TabModule:"; strCacheKey += this.TabModuleId + ":"; strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); - return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + "\\" + Globals.CleanFileName(strCacheKey) + ".resources"; + return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + @"\" + Globals.CleanFileName(strCacheKey) + ".resources"; } } @@ -285,7 +285,7 @@ public partial string GetCacheFileName(int tabModuleId) string strCacheKey = "TabModule:"; strCacheKey += tabModuleId + ":"; strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); - return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + "\\" + Globals.CleanFileName(strCacheKey) + ".resources"; + return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + @"\" + Globals.CleanFileName(strCacheKey) + ".resources"; } /// Gets the cache key for the module. diff --git a/DNN Platform/Library/Entities/Modules/Prompt/AddModule.cs b/DNN Platform/Library/Entities/Modules/Prompt/AddModule.cs index 9ffddc3a9ca..6955a109ede 100644 --- a/DNN Platform/Library/Entities/Modules/Prompt/AddModule.cs +++ b/DNN Platform/Library/Entities/Modules/Prompt/AddModule.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Modules.Prompt { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Net; @@ -55,14 +56,14 @@ public override IConsoleResultModel Run() var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(this.ModuleName, this.PortalId); if (desktopModule == null) { - return new ConsoleErrorResultModel(string.Format(this.LocalizeString("Prompt_DesktopModuleNotFound"), this.ModuleName)); + return new ConsoleErrorResultModel(string.Format(CultureInfo.CurrentCulture, this.LocalizeString("Prompt_DesktopModuleNotFound"), this.ModuleName)); } var message = default(KeyValuePair); var page = TabController.Instance.GetTab(this.PageId, this.PortalSettings.PortalId); if (page == null) { - message = new KeyValuePair(HttpStatusCode.NotFound, string.Format(Localization.GetString("Prompt_PageNotFound", this.LocalResourceFile), this.PageId)); + message = new KeyValuePair(HttpStatusCode.NotFound, string.Format(CultureInfo.CurrentCulture, Localization.GetString("Prompt_PageNotFound", this.LocalResourceFile), this.PageId)); return null; } @@ -143,7 +144,7 @@ public override IConsoleResultModel Run() var modules = moduleList.Select(newModule => ModuleController.Instance.GetTabModule(newModule.TabModuleID)).ToList(); - return new ConsoleResultModel(string.Format(this.LocalizeString("Prompt_ModuleAdded"), modules.Count, moduleList.Count == 1 ? string.Empty : "s")) { Data = modules, Records = modules.Count }; + return new ConsoleResultModel(string.Format(CultureInfo.CurrentCulture, this.LocalizeString("Prompt_ModuleAdded"), modules.Count, moduleList.Count == 1 ? string.Empty : "s")) { Data = modules, Records = modules.Count }; } catch (Exception ex) { diff --git a/DNN Platform/Library/Entities/Modules/Prompt/PromptModuleInfo.cs b/DNN Platform/Library/Entities/Modules/Prompt/PromptModuleInfo.cs index bff9429d009..aea352c891b 100644 --- a/DNN Platform/Library/Entities/Modules/Prompt/PromptModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/Prompt/PromptModuleInfo.cs @@ -11,6 +11,7 @@ namespace DotNetNuke.Entities.Modules.Prompt public class PromptModuleInfo { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] #pragma warning disable CS3008 // Identifier beginning with an underscore is not CLS-compliant public string __ModuleId { get; set; } // command link #pragma warning restore CS3008 // Identifier beginning with an underscore is not CLS-compliant @@ -20,6 +21,7 @@ public class PromptModuleInfo public string Title { get; set; } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] #pragma warning disable CS3008 // Identifier beginning with an underscore is not CLS-compliant public string __ModuleName { get; set; } // command link #pragma warning restore CS3008 // Identifier beginning with an underscore is not CLS-compliant diff --git a/DNN Platform/Library/Entities/Modules/Settings/ParameterAttributeBase.cs b/DNN Platform/Library/Entities/Modules/Settings/ParameterAttributeBase.cs index 641dceb888e..9653b7d8e9e 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ParameterAttributeBase.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ParameterAttributeBase.cs @@ -2,40 +2,42 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Settings -{ - using System; +namespace DotNetNuke.Entities.Modules.Settings +{ + using System; + using System.Diagnostics.CodeAnalysis; - /// - /// Base class for attributes that are used to decorate properties (parameters) related to - /// application settings (storage) or parameters (control) like query string parameters. - /// - [Serializable] - public abstract class ParameterAttributeBase : Attribute - { - /// Gets or sets the prefix to use when naming the setting in the settings table. - /// - /// The settings tables are shared by the core platform and the extensions. Extensions - /// should use a unique prefix to ensure that name clashes do not occur with settings - /// defined by the core or other extensions. - /// - public string Prefix { get; set; } - - /// Gets or sets the name of the setting that will be stored in the settings table. - /// - /// If parametername is not defined, then the name of the property will be used. If - /// a prefix is defined, then that will be concatenated with the parametername (or the - /// property name if no parametername is provided). - /// - public string ParameterName { get; set; } - - /// Gets or sets the serializer to use when saving or retrieving the setting value. - /// - /// The serializer must implement the interface. - /// - public string Serializer { get; set; } + /// + /// Base class for attributes that are used to decorate properties (parameters) related to + /// application settings (storage) or parameters (control) like query string parameters. + /// + [Serializable] + [SuppressMessage("Microsoft.Design", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Breaking change")] + public abstract class ParameterAttributeBase : Attribute + { + /// Gets or sets the prefix to use when naming the setting in the settings table. + /// + /// The settings tables are shared by the core platform and the extensions. Extensions + /// should use a unique prefix to ensure that name clashes do not occur with settings + /// defined by the core or other extensions. + /// + public string Prefix { get; set; } + + /// Gets or sets the name of the setting that will be stored in the settings table. + /// + /// If parametername is not defined, then the name of the property will be used. If + /// a prefix is defined, then that will be concatenated with the parametername (or the + /// property name if no parametername is provided). + /// + public string ParameterName { get; set; } + + /// Gets or sets the serializer to use when saving or retrieving the setting value. + /// + /// The serializer must implement the interface. + /// + public string Serializer { get; set; } /// Gets or sets a value indicating whether the settings should be stored securely. This encrypts the value of the parameter. public bool IsSecure { get; set; } - } -} + } +} diff --git a/DNN Platform/Library/Entities/Modules/Settings/SerializationManager.cs b/DNN Platform/Library/Entities/Modules/Settings/SerializationManager.cs index b3cac8f1060..005d6f7243e 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/SerializationManager.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/SerializationManager.cs @@ -62,7 +62,7 @@ void ISerializationManager.DeserializeProperty(T myObject, PropertyInfo prope { // TODO: Localize exception var message = string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, "Could not cast {0} to property {1} of type {2}", propertyValue, property.Name, diff --git a/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs b/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs index 881c7793482..77463c53466 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Modules.Settings { using System; using System.Collections.Generic; + using System.Globalization; using System.Reflection; using System.Web.Caching; @@ -211,7 +212,7 @@ private T Load(CacheItemArgs args) } catch (Exception ex) { - Exceptions.LogException(new ModuleLoadException(string.Format(Localization.GetString("ErrorDecryptingSetting", Localization.SharedResourceFile), mapping.FullParameterName), ex, ctlModule)); + Exceptions.LogException(new ModuleLoadException(string.Format(CultureInfo.CurrentCulture, Localization.GetString("ErrorDecryptingSetting", Localization.SharedResourceFile), mapping.FullParameterName), ex, ctlModule)); } } diff --git a/DNN Platform/Library/Entities/Modules/UserModuleBase.cs b/DNN Platform/Library/Entities/Modules/UserModuleBase.cs index d7c4259227c..96b87115cf2 100644 --- a/DNN Platform/Library/Entities/Modules/UserModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/UserModuleBase.cs @@ -92,7 +92,7 @@ public UserInfo User } else { - userId = Convert.ToInt32(this.ViewState["UserId"]); + userId = Convert.ToInt32(this.ViewState["UserId"], CultureInfo.InvariantCulture); } return userId; @@ -253,13 +253,11 @@ public static void UpdateSetting(int portalId, string key, string setting) /// The settings to update. public static void UpdateSettings(int portalId, Hashtable settings) { - string key; - string setting; - IDictionaryEnumerator settingsEnumerator = settings.GetEnumerator(); + var settingsEnumerator = settings.GetEnumerator(); while (settingsEnumerator.MoveNext()) { - key = Convert.ToString(settingsEnumerator.Key); - setting = Convert.ToString(settingsEnumerator.Value); + var key = Convert.ToString(settingsEnumerator.Key, CultureInfo.InvariantCulture); + var setting = Convert.ToString(settingsEnumerator.Value, CultureInfo.InvariantCulture); UpdateSetting(portalId, key, setting); } } @@ -330,7 +328,7 @@ protected string CompleteUserCreation(UserCreateStatus createStatus, UserInfo ne Localization.SetLanguage(newUser.Profile.PreferredLocale); if (this.IsRegister && message == ModuleMessage.ModuleMessageType.RedError) { - this.AddLocalizedModuleMessage(string.Format(Localization.GetString("SendMail.Error", Localization.SharedResourceFile), strMessage), message, !string.IsNullOrEmpty(strMessage)); + this.AddLocalizedModuleMessage(string.Format(CultureInfo.CurrentCulture, Localization.GetString("SendMail.Error", Localization.SharedResourceFile), strMessage), message, !string.IsNullOrEmpty(strMessage)); } else { @@ -413,16 +411,16 @@ private UserInfo InitialiseUser() newUser.Profile.PreferredLocale = lc; - // Set default countr + // Set default country string country = Null.NullString; country = this.LookupCountry(); if (!string.IsNullOrEmpty(country)) { ListController listController = new ListController(); - var listitem = listController.GetListEntryInfo("Country", country); - if (listitem != null) + var listItem = listController.GetListEntryInfo("Country", country); + if (listItem != null) { - country = listitem.EntryID.ToString(); + country = listItem.EntryID.ToString(CultureInfo.InvariantCulture); } newUser.Profile.Country = country; @@ -432,7 +430,7 @@ private UserInfo InitialiseUser() int affiliateId = Null.NullInteger; if (this.Request.Cookies["AffiliateId"] != null) { - affiliateId = int.Parse(this.Request.Cookies["AffiliateId"].Value); + affiliateId = int.Parse(this.Request.Cookies["AffiliateId"].Value, CultureInfo.InvariantCulture); } newUser.AffiliateID = affiliateId; diff --git a/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs b/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs index ee1c18da6d0..d8f372de12b 100644 --- a/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs +++ b/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs @@ -4,11 +4,13 @@ namespace DotNetNuke.Entities.Modules { using System; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Entities.Users; using DotNetNuke.Security.Membership; /// The UserUserControlBase class defines a custom base class for the User Control. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public class UserUserControlBase : UserModuleBase { public delegate void UserCreatedEventHandler(object sender, UserCreatedEventArgs e); @@ -154,15 +156,16 @@ public void OnUserUpdateError(UserUpdateErrorArgs e) { this.UserUpdateError(this, e); } - } - + } + /// The BaseUserEventArgs class provides a base for User EventArgs classes. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public class BaseUserEventArgs { - /// Gets or sets the Id of the User. + /// Gets or sets the ID of the User. public int UserId { get; set; } - /// Gets or sets the Id of the User. + /// Gets or sets the ID of the User. public string UserName { get; set; } } diff --git a/DNN Platform/Library/Entities/Portals/IPortalAliasController.cs b/DNN Platform/Library/Entities/Portals/IPortalAliasController.cs index d2fb35c2145..f62794dd6f2 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalAliasController.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalAliasController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Portals { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; /// /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should be used as a type and for unit test purposes only. @@ -24,12 +25,14 @@ public interface IPortalAliasController /// Gets the portal alias info. /// The portal alias. /// Portal alias info. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] PortalAliasInfo GetPortalAlias(string alias); /// Gets the portal alias info. /// The portal alias. - /// The Id of the portal in question. + /// The ID of the portal in question. /// Portal alias info. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] PortalAliasInfo GetPortalAlias(string alias, int portalId); PortalAliasInfo GetPortalAliasByPortalAliasID(int portalAliasId); diff --git a/DNN Platform/Library/Entities/Portals/IPortalController.cs b/DNN Platform/Library/Entities/Portals/IPortalController.cs index ae47eeec856..aa50d25cd91 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalController.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Portals using System; using System.Collections; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Abstractions.Portals; using DotNetNuke.Abstractions.Portals.Templates; @@ -40,6 +41,7 @@ public interface IPortalController /// if set to means the portal is child portal. /// Portal id. [Obsolete("Deprecated in DotNetNuke 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo template argument instead. Scheduled removal in v11.0.0.")] + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] int CreatePortal(string portalName, int adminUserId, string description, string keyWords, PortalController.PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal); /// Creates the portal. @@ -54,6 +56,7 @@ public interface IPortalController /// The child path. /// if set to means the portal is child portal. /// Portal id. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] int CreatePortal(string portalName, int adminUserId, string description, string keyWords, IPortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal); /// Creates the portal. @@ -69,6 +72,7 @@ public interface IPortalController /// if set to means the portal is child portal. /// Portal id. [Obsolete("Deprecated in DotNetNuke 9.11.1. Use IPortalTemplateInfo template argument instead. Scheduled removal in v11.0.0.")] + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, PortalController.PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal); /// Creates the portal. @@ -82,7 +86,8 @@ public interface IPortalController /// The server path. /// The child path. /// if set to means the portal is child portal. - /// Portal id. + /// Portal ID. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, IPortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal); /// Get all the available portal templates grouped by culture. @@ -177,6 +182,7 @@ public interface IPortalController /// The roles and settings nodes will only be processed on the portal template file. /// [Obsolete("Deprecated in DotNetNuke 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.ApplyPortalTemplate instead. Scheduled removal in v11.0.0.")] + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void ParseTemplate(int portalId, PortalController.PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal); /// Processes the resource file for the template file selected. diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs index 9dfa2846d13..f4135669de2 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs @@ -6,68 +6,137 @@ namespace DotNetNuke.Entities.Portals { using System; using System.Collections; + using System.Collections.Generic; + using System.Linq; + using DotNetNuke.Common; using DotNetNuke.Internal.SourceGenerators; /// A collection of instances, indexed by . [Serializable] [DnnDeprecated(9, 7, 2, "use IDictionary instead")] - public partial class PortalAliasCollection : DictionaryBase + public partial class PortalAliasCollection : DictionaryBase, IDictionary { /// Gets a value indicating whether the collection contains keys that are not null. - public bool HasKeys + public bool HasKeys => this.Dictionary.Keys.Count > 0; + + public ICollection Keys => this.Dictionary.Keys; + + /// + public bool IsReadOnly => this.Dictionary.IsReadOnly; + + /// + ICollection IDictionary.Values + => this.Dictionary.Values.Cast().ToList(); + + /// + ICollection IDictionary.Keys + => this.Dictionary.Keys.Cast().ToList(); + + public ICollection Values => this.Dictionary.Values; + + /// Gets or sets the value associated with the specified key. + /// The HTTP alias. + public PortalAliasInfo this[string key] { - get - { - return this.Dictionary.Keys.Count > 0; - } + get => (PortalAliasInfo)this.Dictionary[key]; + set => this.Dictionary[key] = value; } - public ICollection Keys + /// + public bool TryGetValue(string key, out PortalAliasInfo value) { - get + if (!this.ContainsKey(key)) { - return this.Dictionary.Keys; + value = null; + return false; } + + value = this[key]; + return true; } - public ICollection Values + /// + [DnnDeprecated(9, 7, 2, "use IDictionary instead")] + public partial bool Contains(string key) => this.Dictionary.Contains(key); + + /// + public bool ContainsKey(string key) => this.Dictionary.Contains(key); + + /// + public bool Remove(string key) { - get + if (!this.ContainsKey(key)) { - return this.Dictionary.Values; + return false; } + + this.Dictionary.Remove(key); + return true; } - /// Gets or sets the value associated with the specified key. - /// The HTTP alias. - public PortalAliasInfo this[string key] + /// + public bool Remove(KeyValuePair item) { - get + return this.Contains(item) && this.Remove(item.Key); + } + + /// Adds an entry to the collection. + /// The to use as the key of the element to add. + /// The to use as the value of the element to add. + [DnnDeprecated(9, 7, 2, "use IDictionary instead")] + public partial void Add(string key, PortalAliasInfo value) => this.Dictionary.Add(key, value); + + /// + public void Add(KeyValuePair item) => this.Dictionary.Add(item.Key, item.Value); + + /// + public bool Contains(KeyValuePair item) => + this.TryGetValue(item.Key, out var value) && EqualityComparer.Default.Equals(value, item.Value); + + /// + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + Requires.NotNull(nameof(array), array); + if (arrayIndex > array.Length) + { + throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "arrayIndex must be less than the length of array"); + } + + if (array.Length - arrayIndex < this.Count) { - return (PortalAliasInfo)this.Dictionary[key]; + throw new ArgumentOutOfRangeException(nameof(array), array, "array length must be large enough to hold contents"); } - set + foreach (DictionaryEntry entry in this.Dictionary) { - this.Dictionary[key] = value; + array[arrayIndex++] = new KeyValuePair((string)entry.Key, (PortalAliasInfo)entry.Value); } } - /// - [DnnDeprecated(9, 7, 2, "use IDictionary instead")] - public partial bool Contains(string key) + /// + IEnumerator> IEnumerable>.GetEnumerator() { - return this.Dictionary.Contains(key); + return new PortalAliasEnumerator(this.Dictionary.GetEnumerator()); } - /// Adds an entry to the collection. - /// The to use as the key of the element to add. - /// The to use as the value of the element to add. - [DnnDeprecated(9, 7, 2, "use IDictionary instead")] - public partial void Add(string key, PortalAliasInfo value) + private class PortalAliasEnumerator(IDictionaryEnumerator enumerator) : IEnumerator> { - this.Dictionary.Add(key, value); + /// + public KeyValuePair Current => + new KeyValuePair((string)enumerator.Key, (PortalAliasInfo)enumerator.Value); + + /// + object IEnumerator.Current => this.Current; + + /// + public void Dispose() => (enumerator as IDisposable)?.Dispose(); + + /// + public bool MoveNext() => enumerator.MoveNext(); + + /// + public void Reset() => enumerator.Reset(); } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasController.cs b/DNN Platform/Library/Entities/Portals/PortalAliasController.cs index 3c558c0d59d..4decc3df412 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasController.cs @@ -56,14 +56,14 @@ string IPortalAliasService.GetPortalAliasByPortal(int portalId, string portalAli // eg. child = 'www.domain.com/child' and parent is 'www.domain.com' // this allows the parent domain name to resolve to the child alias ( the tabid still identifies the child portalid ) IPortalAliasInfo currentAliasInfo = currentAlias.Value; - string httpAlias = currentAliasInfo.HttpAlias.ToLowerInvariant(); + string httpAlias = currentAliasInfo.HttpAlias; if (httpAlias.StartsWith(portalAlias, StringComparison.OrdinalIgnoreCase) && currentAliasInfo.PortalId == portalId) { retValue = currentAliasInfo.HttpAlias; break; } - httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); + httpAlias = httpAlias.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? httpAlias.Substring("www.".Length) : $"www.{httpAlias}"; if (httpAlias.StartsWith(portalAlias, StringComparison.OrdinalIgnoreCase) && currentAliasInfo.PortalId == portalId) { retValue = currentAliasInfo.HttpAlias; diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs b/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs index 8f013e75e58..3cb8603d328 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs @@ -120,7 +120,7 @@ public static PortalAliasInfo GetAliasByPortalIdAndSettings(this IEnumerable public void WriteXml(XmlWriter writer) { - // Write start of main elemenst + // Write start of main elements writer.WriteStartElement("portalAlias"); // write out properties - writer.WriteElementString("portalID", this.ThisAsInterface.PortalId.ToString()); - writer.WriteElementString("portalAliasID", this.ThisAsInterface.PortalAliasId.ToString()); + writer.WriteElementString("portalID", this.ThisAsInterface.PortalId.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("portalAliasID", this.ThisAsInterface.PortalAliasId.ToString(CultureInfo.InvariantCulture)); writer.WriteElementString("HTTPAlias", this.ThisAsInterface.HttpAlias); writer.WriteElementString("skin", this.Skin); writer.WriteElementString("cultureCode", this.CultureCode); diff --git a/DNN Platform/Library/Entities/Portals/PortalController.cs b/DNN Platform/Library/Entities/Portals/PortalController.cs index a324ed2ea54..aab22a0825a 100644 --- a/DNN Platform/Library/Entities/Portals/PortalController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalController.cs @@ -147,9 +147,9 @@ public static string CreateChildPortalFolder(string childPath) } // create the subhost default.aspx file - if (!File.Exists(childPath + "\\" + Globals.glbDefaultPage)) + if (!File.Exists(childPath + @"\" + Globals.glbDefaultPage)) { - File.Copy(Globals.HostMapPath + "subhost.aspx", childPath + "\\" + Globals.glbDefaultPage); + File.Copy(Globals.HostMapPath + "subhost.aspx", childPath + @"\" + Globals.glbDefaultPage); } } catch (Exception exc) @@ -315,7 +315,7 @@ public static partial Dictionary GetPortalDictionary() /// portal dictionary. the dictionary's Key -> Value is: TabId -> PortalId. public static Dictionary GetPortalDictionary(IHostSettings hostSettings, DataProvider dataProvider) { - string cacheKey = string.Format(DataCache.PortalDictionaryCacheKey); + string cacheKey = DataCache.PortalDictionaryCacheKey; return CBO.GetCachedObject>( hostSettings, new CacheItemArgs(cacheKey, DataCache.PortalDictionaryTimeOut, DataCache.PortalDictionaryCachePriority, hostSettings, dataProvider), @@ -803,7 +803,7 @@ public static int GetPortalSettingAsInteger(IPortalController portalController, } else { - retValue = Convert.ToInt32(setting); + retValue = Convert.ToInt32(setting, CultureInfo.InvariantCulture); } } catch (Exception exc) @@ -845,7 +845,7 @@ public static double GetPortalSettingAsDouble(IPortalController portalController } else { - retValue = Convert.ToDouble(setting); + retValue = Convert.ToDouble(setting, CultureInfo.InvariantCulture); } } catch (Exception exc) @@ -885,15 +885,14 @@ public static int GetPortalSettingAsInteger(IHostSettings hostSettings, IApplica int retValue = Null.NullInteger; try { - string setting; - GetPortalSettingsDictionary(hostSettings, appStatus, portalId, cultureCode).TryGetValue(key, out setting); + GetPortalSettingsDictionary(hostSettings, appStatus, portalId, cultureCode).TryGetValue(key, out var setting); if (string.IsNullOrEmpty(setting)) { retValue = defaultValue; } else { - retValue = Convert.ToInt32(setting); + retValue = Convert.ToInt32(setting, CultureInfo.InvariantCulture); } } catch (Exception exc) @@ -1577,7 +1576,7 @@ public ArrayList GetPortals() /// A of instances. public List GetPortalList(string cultureCode) { - string cacheKey = string.Format(DataCache.PortalCacheKey, Null.NullInteger, cultureCode); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PortalCacheKey, Null.NullInteger, cultureCode); return CBO.GetCachedObject>( this.hostSettings, new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, cultureCode), @@ -1631,7 +1630,7 @@ public long GetPortalSpaceUsedBytes(int portalId) { if (dr["SpaceUsed"] != DBNull.Value) { - size = Convert.ToInt64(dr["SpaceUsed"]); + size = Convert.ToInt64(dr["SpaceUsed"], CultureInfo.InvariantCulture); } } } @@ -2056,7 +2055,7 @@ private static int CreatePortal(IHostSettings hostSettings, string portalName, s var hostController = HostController.Instance; var demoPeriod = TimeSpan.FromDays(hostController.GetInteger("DemoPeriod")); var datExpiryDate = demoPeriod > TimeSpan.Zero - ? Convert.ToDateTime(Globals.GetMediumDate(DateTime.Now.Add(demoPeriod).ToString(CultureInfo.InvariantCulture))) + ? Convert.ToDateTime(Globals.GetMediumDate(DateTime.Now.Add(demoPeriod).ToString(CultureInfo.InvariantCulture)), CultureInfo.CurrentCulture) : Null.NullDate; var hostCurrency = hostController.GetString("HostCurrency"); @@ -2102,7 +2101,7 @@ private static void DeletePortalInternal(int portalId) { UserController.DeleteUsers(portalId, false, true); - var portal = Instance.GetPortal(portalId); + IPortalInfo portal = Instance.GetPortal(portalId); DataProvider.Instance().DeletePortalInfo(portalId); @@ -2111,10 +2110,10 @@ private static void DeletePortalInternal(int portalId) var log = new LogInfo { BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.PORTAL_DELETED.ToString(), + LogTypeKey = nameof(EventLogType.PORTAL_DELETED), }; log.LogProperties.Add(new LogDetailInfo("Delete Portal:", portal.PortalName)); - log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString())); + log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalId.ToString(CultureInfo.InvariantCulture))); LogController.Instance.AddLog(log); } catch (Exception exc) @@ -2186,7 +2185,7 @@ private static object GetPortalDictionaryCallback(CacheItemArgs cacheItemArgs) while (dr.Read()) { // add to dictionary - portalDic[Convert.ToInt32(Null.SetNull(dr["TabID"], intField))] = Convert.ToInt32(Null.SetNull(dr["PortalID"], intField)); + portalDic[Convert.ToInt32(Null.SetNull(dr["TabID"], intField), CultureInfo.InvariantCulture)] = Convert.ToInt32(Null.SetNull(dr["PortalID"], intField), CultureInfo.InvariantCulture); } } catch (Exception exc) @@ -2207,7 +2206,7 @@ private static object GetPortalSettingsDictionaryCallback(CacheItemArgs cacheIte return dicSettings; } - var cultureCode = Convert.ToString(cacheItemArgs.ParamList[1]); + var cultureCode = Convert.ToString(cacheItemArgs.ParamList[1], CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(cultureCode)) { var hostSettings = (IHostSettings)cacheItemArgs.ParamList[2]; @@ -2308,7 +2307,7 @@ private static Dictionary GetPortalSettingsDictionary(IHostSetti } // Get PortalSettings from Context or from cache - var dictionaryKey = string.Format(HttpContextKeyPortalSettingsDictionary, portalId, cultureCode); + var dictionaryKey = string.Format(CultureInfo.InvariantCulture, HttpContextKeyPortalSettingsDictionary, portalId, cultureCode); Dictionary dictionary = null; if (httpContext != null) { @@ -2317,7 +2316,7 @@ private static Dictionary GetPortalSettingsDictionary(IHostSetti if (dictionary == null) { - var cacheKey = string.Format(DataCache.PortalSettingsCacheKey, portalId, cultureCode); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PortalSettingsCacheKey, portalId, cultureCode); dictionary = CBO.GetCachedObject>( hostSettings, new CacheItemArgs( @@ -2384,7 +2383,7 @@ private static void UpdatePortalSettingInternal(IHostSettings hostSettings, IApp if (httpContext != null) { var cultureCodeForKey = GetActivePortalLanguageFromHttpContext(hostSettings, appStatus, httpContext, portalId); - var dictionaryKey = string.Format(HttpContextKeyPortalSettingsDictionary, portalId, cultureCodeForKey); + var dictionaryKey = string.Format(CultureInfo.InvariantCulture, HttpContextKeyPortalSettingsDictionary, portalId, cultureCodeForKey); httpContext.Items[dictionaryKey] = null; } } @@ -2429,11 +2428,11 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi homeDirectory = "Portals/" + portalId; } - string mappedHomeDirectory = string.Format($@"{Globals.ApplicationMapPath}\{homeDirectory}\").Replace("/", @"\"); + string mappedHomeDirectory = $@"{Globals.ApplicationMapPath}\{homeDirectory}\".Replace("/", @"\"); if (Directory.Exists(mappedHomeDirectory)) { - message += string.Format(Localization.GetString("CreatePortalHomeFolderExists.Error"), homeDirectory); + message += string.Format(CultureInfo.CurrentCulture, Localization.GetString("CreatePortalHomeFolderExists.Error"), homeDirectory); throw new CreatePortalException(message); } @@ -2483,7 +2482,7 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi } // ensure that the Users folder exists - string usersFolder = string.Format("{0}Users", mappedHomeDirectory); + string usersFolder = $"{mappedHomeDirectory}Users"; if (!Directory.Exists(usersFolder)) { Directory.CreateDirectory(usersFolder); @@ -2776,7 +2775,12 @@ private void UpdatePortalInternal(PortalInfo portal, bool clearCache) UserController.Instance.GetCurrentUserInfo().UserID, portal.CultureCode); - EventLogController.Instance.AddLog("PortalId", portal.PortalID.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); + EventLogController.Instance.AddLog( + "PortalId", + portal.PortalID.ToString(CultureInfo.InvariantCulture), + GetCurrentPortalSettingsInternal(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTALINFO_UPDATED); // ensure a localization item exists (in case a new default language has been set) DataProvider.Instance().EnsureLocalizationExists(portal.PortalID, portal.DefaultLanguage); diff --git a/DNN Platform/Library/Entities/Portals/PortalGroupController.cs b/DNN Platform/Library/Entities/Portals/PortalGroupController.cs index 5a16a8cc45b..a3e3bab5348 100644 --- a/DNN Platform/Library/Entities/Portals/PortalGroupController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalGroupController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Portals { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -367,11 +368,11 @@ private static void LogEvent(EventLogController.EventLogType eventType, PortalGr LogTypeKey = eventType.ToString(), }; log.LogProperties.Add(new LogDetailInfo("PortalGroup:", portalGroup.PortalGroupName)); - log.LogProperties.Add(new LogDetailInfo("PortalGroupID:", portalGroup.PortalGroupId.ToString())); + log.LogProperties.Add(new LogDetailInfo("PortalGroupID:", portalGroup.PortalGroupId.ToString(CultureInfo.InvariantCulture))); if (portal != null) { log.LogProperties.Add(new LogDetailInfo("Portal:", portal.PortalName)); - log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString())); + log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString(CultureInfo.InvariantCulture))); } LogController.Instance.AddLog(log); diff --git a/DNN Platform/Library/Entities/Portals/PortalInfo.cs b/DNN Platform/Library/Entities/Portals/PortalInfo.cs index 67ac7a15802..47d30b543eb 100644 --- a/DNN Platform/Library/Entities/Portals/PortalInfo.cs +++ b/DNN Platform/Library/Entities/Portals/PortalInfo.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Portals { using System; using System.Data; + using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; using System.Xml.Serialization; @@ -87,32 +88,17 @@ public PortalInfo() /// [XmlElement("homesystemdirectory")] - public string HomeSystemDirectory - { - get { return string.Format("{0}-System", this.HomeDirectory); } - } + public string HomeSystemDirectory => $"{this.HomeDirectory}-System"; /// [XmlIgnore] [JsonIgnore] - public string HomeDirectoryMapPath - { - get - { - return string.Format("{0}\\{1}\\", Globals.ApplicationMapPath, this.HomeDirectory.Replace("/", "\\")); - } - } + public string HomeDirectoryMapPath => $@"{Globals.ApplicationMapPath}\{this.HomeDirectory.Replace("/", @"\")}\"; /// [XmlIgnore] [JsonIgnore] - public string HomeSystemDirectoryMapPath - { - get - { - return string.Format("{0}\\{1}\\", Globals.ApplicationMapPath, this.HomeSystemDirectory.Replace("/", "\\")); - } - } + public string HomeSystemDirectoryMapPath => $@"{Globals.ApplicationMapPath}\{this.HomeSystemDirectory.Replace("/", @"\")}\"; /// [XmlElement("administratorid")] @@ -171,6 +157,7 @@ public string HomeSystemDirectoryMapPath /// [XmlIgnore] [JsonIgnore] + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] public Guid GUID { get; set; } /// diff --git a/DNN Platform/Library/Entities/Portals/PortalSettings.cs b/DNN Platform/Library/Entities/Portals/PortalSettings.cs index 7c53759b28e..134fe015c85 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettings.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettings.cs @@ -80,10 +80,11 @@ public PortalSettings(PortalInfo portal) /// The portal info. public PortalSettings(int tabId, PortalInfo portal) { - this.PortalId = portal != null ? portal.PortalID : Null.NullInteger; + this.PortalId = portal?.PortalID ?? Null.NullInteger; this.BuildPortalSettings(tabId, portal); } + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public enum ControlPanelPermission { /// A page editor. @@ -133,30 +134,18 @@ public enum UserDeleteAction HardDelete = 3, } - public static PortalSettings Current - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } + public static PortalSettings Current => PortalController.Instance.GetCurrentPortalSettings(); /// - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } + public CacheLevel Cacheability => CacheLevel.fullyCacheable; /// public bool ControlPanelVisible { get { - var setting = Convert.ToString(Personalization.GetProfile("Usability", "ControlPanelVisible" + this.PortalId)); - return string.IsNullOrEmpty(setting) ? this.DefaultControlPanelVisibility : Convert.ToBoolean(setting); + var setting = Convert.ToString(Personalization.GetProfile("Usability", "ControlPanelVisible" + this.PortalId), CultureInfo.InvariantCulture); + return string.IsNullOrEmpty(setting) ? this.DefaultControlPanelVisibility : Convert.ToBoolean(setting, CultureInfo.InvariantCulture); } } @@ -165,22 +154,16 @@ public string DefaultPortalAlias { get { - foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId).Where(alias => alias.IsPrimary)) + foreach (IPortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId).Where(alias => alias.IsPrimary)) { - return alias.HTTPAlias; + return alias.HttpAlias; } return string.Empty; } } - public PortalAliasMapping PortalAliasMappingMode - { - get - { - return PortalSettingsController.Instance().GetPortalAliasMappingMode(this.PortalId); - } - } + public PortalAliasMapping PortalAliasMappingMode => PortalSettingsController.Instance().GetPortalAliasMappingMode(this.PortalId); /// public int UserId @@ -329,6 +312,7 @@ public bool DisablePrivateMessage public string FooterText { get; set; } /// + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] public Guid GUID { get; set; } /// @@ -646,7 +630,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format break; case "footertext": propertyNotFound = false; - var footerText = this.FooterText.Replace("[year]", DateTime.Now.Year.ToString()); + var footerText = this.FooterText.Replace("[year]", DateTime.Now.Year.ToString(formatProvider)); result = PropertyAccess.FormatString(footerText, format); break; case "expirydate": @@ -813,7 +797,7 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) PortalSettingsController.Instance().LoadPortal(portal, this); - var key = string.Join(":", "ActiveTab", portal.PortalID.ToString(), tabId.ToString()); + var key = string.Join(":", "ActiveTab", portal.PortalID.ToString(CultureInfo.InvariantCulture), tabId.ToString(CultureInfo.InvariantCulture)); var items = HttpContext.Current != null ? HttpContext.Current.Items : null; if (items != null && items.Contains(key)) { diff --git a/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs b/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs index dd3f1a28f41..fb82062673f 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Entities.Portals using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using DotNetNuke.Abstractions.Application; @@ -47,6 +48,7 @@ public static IPortalSettingsController Instance() => Globals.GetCurrentServiceProvider().GetRequiredService(); /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public virtual void ConfigureActiveTab(PortalSettings portalSettings) { var activeTab = portalSettings.ActiveTab; @@ -265,15 +267,15 @@ public virtual void LoadPortalSettings(PortalSettings portalSettings) setting = settings.GetValueOrDefault("DataConsentTermsLastChange", string.Empty); if (!string.IsNullOrEmpty(setting)) { - portalSettings.DataConsentTermsLastChange = DateTime.Parse(setting, System.Globalization.CultureInfo.InvariantCulture); + portalSettings.DataConsentTermsLastChange = DateTime.Parse(setting, CultureInfo.InvariantCulture); } setting = settings.GetValueOrDefault("DataConsentConsentRedirect", "-1"); - portalSettings.DataConsentConsentRedirect = int.Parse(setting); + portalSettings.DataConsentConsentRedirect = int.Parse(setting, CultureInfo.InvariantCulture); setting = settings.GetValueOrDefault("DataConsentUserDeleteAction", "0"); - portalSettings.DataConsentUserDeleteAction = (PortalSettings.UserDeleteAction)int.Parse(setting); + portalSettings.DataConsentUserDeleteAction = (PortalSettings.UserDeleteAction)int.Parse(setting, CultureInfo.InvariantCulture); setting = settings.GetValueOrDefault("DataConsentDelay", "1"); - portalSettings.DataConsentDelay = int.Parse(setting); + portalSettings.DataConsentDelay = int.Parse(setting, CultureInfo.InvariantCulture); setting = settings.GetValueOrDefault("DataConsentDelayMeasurement", "d"); portalSettings.DataConsentDelayMeasurement = setting; setting = settings.GetValueOrDefault("AllowedExtensionsWhitelist", this.hostSettingsService.GetString("DefaultEndUserExtensionWhitelist")); diff --git a/DNN Platform/Library/Entities/Portals/PortalStyles.cs b/DNN Platform/Library/Entities/Portals/PortalStyles.cs index 9ed01a0b7d3..4d7a1f7c7f2 100644 --- a/DNN Platform/Library/Entities/Portals/PortalStyles.cs +++ b/DNN Platform/Library/Entities/Portals/PortalStyles.cs @@ -323,17 +323,26 @@ public override string ToString() private static string GetRed(string hexValue) { - return int.Parse(hexValue.Substring(0, 2), NumberStyles.AllowHexSpecifier).ToString(CultureInfo.InvariantCulture); + return GetColorValue(hexValue, 0); } private static string GetGreen(string hexValue) { - return int.Parse(hexValue.Substring(2, 2), NumberStyles.AllowHexSpecifier).ToString(CultureInfo.InvariantCulture); + return GetColorValue(hexValue, 2); } private static string GetBlue(string hexValue) { - return int.Parse(hexValue.Substring(4, 2), NumberStyles.AllowHexSpecifier).ToString(CultureInfo.InvariantCulture); + return GetColorValue(hexValue, 4); + } + + private static string GetColorValue(string hexValue, int startIndex) + { + return int.Parse( + hexValue.Substring(startIndex, 2), + NumberStyles.AllowHexSpecifier, + CultureInfo.InvariantCulture) + .ToString(CultureInfo.InvariantCulture); } } } diff --git a/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateExporter.cs b/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateExporter.cs index 6acc1da59ae..590c612d393 100644 --- a/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateExporter.cs +++ b/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateExporter.cs @@ -116,7 +116,7 @@ internal class PortalTemplateExporter TemplatePath = filename, }); - return (true, string.Format(Localization.GetString("ExportedMessage", LocalResourcesFile), filename)); + return (true, string.Format(CultureInfo.CurrentCulture, Localization.GetString("ExportedMessage", LocalResourcesFile), filename)); } private static void SerializePortalSettings(XmlWriter writer, PortalInfo portal, bool isMultilanguage) @@ -363,25 +363,25 @@ private static void SerializeExtensionUrlProviders(XmlWriter writer, int portalI writer.WriteEndElement(); } - private static void SerializeFolders(XmlWriter writer, PortalInfo objportal, ref ZipArchive zipFile) + private static void SerializeFolders(XmlWriter writer, IPortalInfo portal, ref ZipArchive zipFile) { // Sync db and filesystem before exporting so all required files are found var folderManager = FolderManager.Instance; - folderManager.Synchronize(objportal.PortalID); + folderManager.Synchronize(portal.PortalId); writer.WriteStartElement("folders"); - foreach (var folder in folderManager.GetFolders(objportal.PortalID)) + foreach (var folder in folderManager.GetFolders(portal.PortalId)) { writer.WriteStartElement("folder"); writer.WriteElementString("folderpath", folder.FolderPath); - writer.WriteElementString("storagelocation", folder.StorageLocation.ToString()); + writer.WriteElementString("storagelocation", folder.StorageLocation.ToString(CultureInfo.InvariantCulture)); // Serialize Folder Permissions - SerializeFolderPermissions(writer, objportal, folder.FolderPath); + SerializeFolderPermissions(writer, portal, folder.FolderPath); // Serialize files - SerializeFiles(writer, objportal, folder.FolderPath, ref zipFile); + SerializeFiles(writer, portal, folder.FolderPath, ref zipFile); writer.WriteEndElement(); } @@ -432,9 +432,9 @@ private static string GetActualFileName(Services.FileSystem.FileInfo objFile) : objFile.FileName; } - private static void SerializeFolderPermissions(XmlWriter writer, PortalInfo objportal, string folderPath) + private static void SerializeFolderPermissions(XmlWriter writer, IPortalInfo portal, string folderPath) { - var permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(objportal.PortalID, folderPath); + var permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portal.PortalId, folderPath); writer.WriteStartElement("folderpermissions"); @@ -453,13 +453,13 @@ private static void SerializeFolderPermissions(XmlWriter writer, PortalInfo objp writer.WriteEndElement(); } - private static void SerializeProfileDefinitions(XmlWriter writer, PortalInfo objportal) + private static void SerializeProfileDefinitions(XmlWriter writer, IPortalInfo portal) { var objListController = new ListController(); writer.WriteStartElement("profiledefinitions"); foreach (ProfilePropertyDefinition objProfileProperty in - ProfileController.GetPropertyDefinitionsByPortal(objportal.PortalID, false, false)) + ProfileController.GetPropertyDefinitionsByPortal(portal.PortalId, false, false)) { writer.WriteStartElement("profiledefinition"); @@ -469,7 +469,7 @@ private static void SerializeProfileDefinitions(XmlWriter writer, PortalInfo obj var objList = objListController.GetListEntryInfo("DataType", objProfileProperty.DataType); writer.WriteElementString("datatype", objList == null ? "Unknown" : objList.Value); writer.WriteElementString("length", objProfileProperty.Length.ToString(CultureInfo.InvariantCulture)); - writer.WriteElementString("defaultvisibility", Convert.ToInt32(objProfileProperty.DefaultVisibility).ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("defaultvisibility", ((int)objProfileProperty.DefaultVisibility).ToString(CultureInfo.InvariantCulture)); writer.WriteEndElement(); } diff --git a/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateImporter.cs b/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateImporter.cs index 70e8d8c5676..a4dd27d6b2c 100644 --- a/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateImporter.cs +++ b/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateImporter.cs @@ -67,7 +67,7 @@ internal PortalTemplateImporter(IPortalTemplateInfo templateToLoad) { string value = valueElement.Value; - buffer = buffer.Replace(string.Format("[{0}]", name), value); + buffer = buffer.Replace($"[{name}]", value); } } } @@ -430,10 +430,10 @@ private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, in switch (roleName) { case Globals.glbRoleAllUsersName: - roleId = Convert.ToInt32(Globals.glbRoleAllUsers); + roleId = Convert.ToInt32(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture); break; case Globals.glbRoleUnauthUserName: - roleId = Convert.ToInt32(Globals.glbRoleUnauthUser); + roleId = Convert.ToInt32(Globals.glbRoleUnauthUser, CultureInfo.InvariantCulture); break; default: RoleInfo objRole = RoleController.Instance.GetRole(portalId, r => r.RoleName == roleName); @@ -1063,15 +1063,15 @@ private static void ParseTab(IBusinessControllerProvider businessControllerProvi if (!isNewPortal) { // running from wizard: try to find the tab by path - string parenttabname = string.Empty; + string parentTabName = string.Empty; if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent"))) { - parenttabname = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent") + "/"; + parentTabName = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent") + "/"; } - if (hTabs[parenttabname + strName] != null) + if (hTabs[parentTabName + strName] != null) { - tab = TabController.Instance.GetTab(Convert.ToInt32(hTabs[parenttabname + strName]), portalId, false); + tab = TabController.Instance.GetTab(Convert.ToInt32(hTabs[parentTabName + strName], CultureInfo.InvariantCulture), portalId, false); } } @@ -1147,7 +1147,7 @@ private static void ParseTab(IBusinessControllerProvider businessControllerProvi PortalController.GetActivePortalLanguage(portalId)); EventLogController.Instance.AddLog( logType, - tab.TabID.ToString(), + tab.TabID.ToString(CultureInfo.InvariantCulture), PortalSettings.Current, UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_UPDATED); @@ -1158,28 +1158,29 @@ private static void ParseTabs(IBusinessControllerProvider businessControllerProv { // used to control if modules are true modules or instances // will hold module ID from template / new module ID so new instances can reference right moduleid - // only first one from the template will be create as a true module, + // only first one from the template will be created as a true module, // others will be moduleinstances (tabmodules) Hashtable hModules = new Hashtable(); Hashtable hTabs = new Hashtable(); - // if running from wizard we need to pre populate htabs with existing tabs so ParseTab + // if running from wizard we need to pre-populate htabs with existing tabs so ParseTab // can find all existing ones if (!isNewPortal) { Hashtable hTabNames = new Hashtable(); - foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(portalId)) + foreach (var tabPair in TabController.Instance.GetTabsByPortal(portalId)) { TabInfo objTab = tabPair.Value; if (!objTab.IsDeleted) { - var tabname = objTab.TabName; + var tabName = objTab.TabName; if (!Null.IsNull(objTab.ParentId)) { - tabname = Convert.ToString(hTabNames[objTab.ParentId]) + "/" + objTab.TabName; + tabName = + $"{Convert.ToString(hTabNames[objTab.ParentId], CultureInfo.InvariantCulture)}/{objTab.TabName}"; } - hTabNames.Add(objTab.TabID, tabname); + hTabNames.Add(objTab.TabID, tabName); } } @@ -1210,7 +1211,7 @@ private static void ParseTabs(IBusinessControllerProvider businessControllerProv if (tabId > Null.NullInteger) { TabInfo objTab = TabController.Instance.GetTab(tabId, portalId, false); - objTab.Url = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString).ToString(); + objTab.Url = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString).ToString(CultureInfo.InvariantCulture); TabController.Instance.UpdateTab(objTab); } } @@ -1230,7 +1231,7 @@ private static void ParseTabs(IBusinessControllerProvider businessControllerProv var fileName = Path.GetFileName(filePath); - var folderPath = filePath.Substring(0, filePath.LastIndexOf(fileName)); + var folderPath = filePath.Substring(0, filePath.LastIndexOf(fileName, StringComparison.OrdinalIgnoreCase)); var folder = folderManager.GetFolder(portalId, folderPath); var file = fileManager.GetFile(folder, fileName); @@ -1323,7 +1324,7 @@ private static void ParseExtensionUrlProviders(XPathNavigator providersNavigator private static FolderMappingInfo GetFolderMappingFromStorageLocation(int portalId, XmlNode folderNode) { - var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0")); + var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0"), CultureInfo.InvariantCulture); switch (storageLocation) { @@ -1355,7 +1356,7 @@ private static void UpdatePortalSetup(int portalId, int administratorId, int adm privacyTabId, adminTabId, cultureCode); - EventLogController.Instance.AddLog("PortalId", portalId.ToString(), PortalSettings.Current, UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); + EventLogController.Instance.AddLog("PortalId", portalId.ToString(CultureInfo.InvariantCulture), PortalSettings.Current, UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); DataCache.ClearHostCache(true); } diff --git a/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs b/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs index 4814e923c02..cf509af9909 100644 --- a/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs +++ b/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs @@ -2,22 +2,25 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Portals -{ - public class UserCopiedEventArgs - { - public bool Cancel { get; set; } - - public string PortalName { get; set; } - - public float TotalUsers { get; set; } - - public string UserName { get; set; } - - public float UserNo { get; set; } - - public string Stage { get; set; } - - public int PortalGroupId { get; set; } - } -} +namespace DotNetNuke.Entities.Portals +{ + using System.Diagnostics.CodeAnalysis; + + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public class UserCopiedEventArgs + { + public bool Cancel { get; set; } + + public string PortalName { get; set; } + + public float TotalUsers { get; set; } + + public string UserName { get; set; } + + public float UserNo { get; set; } + + public string Stage { get; set; } + + public int PortalGroupId { get; set; } + } +} diff --git a/DNN Platform/Library/Entities/Profile/ProfileController.cs b/DNN Platform/Library/Entities/Profile/ProfileController.cs index 52fba3ad043..578d24b22de 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileController.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Profile using System; using System.Collections.Generic; using System.Data; + using System.Globalization; using System.IO; using DotNetNuke.Abstractions.Application; @@ -128,8 +129,8 @@ public static void DeletePropertyDefinition(ProfilePropertyDefinition definition /// The portal ID. public static void ClearAllUsersInfoProfileCacheByPortal(int portalId) { - DataCache.ClearCache(string.Format(DataCache.UserCacheKey, portalId, string.Empty)); - DataCache.ClearCache(string.Format(DataCache.UserProfileCacheKey, portalId, string.Empty)); + DataCache.ClearCache(string.Format(CultureInfo.InvariantCulture, DataCache.UserCacheKey, portalId, string.Empty)); + DataCache.ClearCache(string.Format(CultureInfo.InvariantCulture, DataCache.UserProfileCacheKey, portalId, string.Empty)); } /// Gets a Property Definition from the Data Store by id. @@ -383,9 +384,9 @@ public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitio { try { - if (!string.IsNullOrEmpty(user.Profile.Photo) && int.Parse(user.Profile.Photo) > 0) + if (!string.IsNullOrEmpty(user.Profile.Photo) && int.Parse(user.Profile.Photo, CultureInfo.InvariantCulture) > 0) { - CreateThumbnails(int.Parse(user.Profile.Photo)); + CreateThumbnails(int.Parse(user.Profile.Photo, CultureInfo.InvariantCulture)); } } catch (Exception ex) @@ -434,10 +435,10 @@ public static List SearchProfilePropertyValues(int portalId, string prop return res; } - using IDataReader ir = Data.DataProvider.Instance().SearchProfilePropertyValues(portalId, propertyName, searchString); - while (ir.Read()) + using var reader = Data.DataProvider.Instance().SearchProfilePropertyValues(portalId, propertyName, searchString); + while (reader.Read()) { - res.Add(Convert.ToString(ir[0])); + res.Add(Convert.ToString(reader[0], CultureInfo.InvariantCulture)); } return res; @@ -510,31 +511,31 @@ private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader return null; } - int portalid = 0; - portalid = Convert.ToInt32(Null.SetNull(dr["PortalId"], portalid)); - definition = new ProfilePropertyDefinition(portalid); - definition.PropertyDefinitionId = Convert.ToInt32(Null.SetNull(dr["PropertyDefinitionId"], definition.PropertyDefinitionId)); - definition.ModuleDefId = Convert.ToInt32(Null.SetNull(dr["ModuleDefId"], definition.ModuleDefId)); - definition.DataType = Convert.ToInt32(Null.SetNull(dr["DataType"], definition.DataType)); - definition.DefaultValue = Convert.ToString(Null.SetNull(dr["DefaultValue"], definition.DefaultValue)); - definition.PropertyCategory = Convert.ToString(Null.SetNull(dr["PropertyCategory"], definition.PropertyCategory)); - definition.PropertyName = Convert.ToString(Null.SetNull(dr["PropertyName"], definition.PropertyName)); - definition.Length = Convert.ToInt32(Null.SetNull(dr["Length"], definition.Length)); + var portalId = 0; + portalId = Convert.ToInt32(Null.SetNull(dr["PortalId"], portalId), CultureInfo.InvariantCulture); + definition = new ProfilePropertyDefinition(portalId); + definition.PropertyDefinitionId = Convert.ToInt32(Null.SetNull(dr["PropertyDefinitionId"], definition.PropertyDefinitionId), CultureInfo.InvariantCulture); + definition.ModuleDefId = Convert.ToInt32(Null.SetNull(dr["ModuleDefId"], definition.ModuleDefId), CultureInfo.InvariantCulture); + definition.DataType = Convert.ToInt32(Null.SetNull(dr["DataType"], definition.DataType), CultureInfo.InvariantCulture); + definition.DefaultValue = Convert.ToString(Null.SetNull(dr["DefaultValue"], definition.DefaultValue), CultureInfo.InvariantCulture); + definition.PropertyCategory = Convert.ToString(Null.SetNull(dr["PropertyCategory"], definition.PropertyCategory), CultureInfo.InvariantCulture); + definition.PropertyName = Convert.ToString(Null.SetNull(dr["PropertyName"], definition.PropertyName), CultureInfo.InvariantCulture); + definition.Length = Convert.ToInt32(Null.SetNull(dr["Length"], definition.Length), CultureInfo.InvariantCulture); if (dr.GetSchemaTable().Select("ColumnName = 'ReadOnly'").Length > 0) { - definition.ReadOnly = Convert.ToBoolean(Null.SetNull(dr["ReadOnly"], definition.ReadOnly)); + definition.ReadOnly = Convert.ToBoolean(Null.SetNull(dr["ReadOnly"], definition.ReadOnly), CultureInfo.InvariantCulture); } - definition.Required = Convert.ToBoolean(Null.SetNull(dr["Required"], definition.Required)); - definition.ValidationExpression = Convert.ToString(Null.SetNull(dr["ValidationExpression"], definition.ValidationExpression)); - definition.ViewOrder = Convert.ToInt32(Null.SetNull(dr["ViewOrder"], definition.ViewOrder)); - definition.Visible = Convert.ToBoolean(Null.SetNull(dr["Visible"], definition.Visible)); - definition.DefaultVisibility = (UserVisibilityMode)Convert.ToInt32(Null.SetNull(dr["DefaultVisibility"], definition.DefaultVisibility)); + definition.Required = Convert.ToBoolean(Null.SetNull(dr["Required"], definition.Required), CultureInfo.InvariantCulture); + definition.ValidationExpression = Convert.ToString(Null.SetNull(dr["ValidationExpression"], definition.ValidationExpression), CultureInfo.InvariantCulture); + definition.ViewOrder = Convert.ToInt32(Null.SetNull(dr["ViewOrder"], definition.ViewOrder), CultureInfo.InvariantCulture); + definition.Visible = Convert.ToBoolean(Null.SetNull(dr["Visible"], definition.Visible), CultureInfo.InvariantCulture); + definition.DefaultVisibility = (UserVisibilityMode)Convert.ToInt32(Null.SetNull(dr["DefaultVisibility"], definition.DefaultVisibility), CultureInfo.InvariantCulture); definition.ProfileVisibility = new ProfileVisibility { VisibilityMode = definition.DefaultVisibility, }; - definition.Deleted = Convert.ToBoolean(Null.SetNull(dr["Deleted"], definition.Deleted)); + definition.Deleted = Convert.ToBoolean(Null.SetNull(dr["Deleted"], definition.Deleted), CultureInfo.InvariantCulture); return definition; } @@ -574,7 +575,7 @@ private static int GetEffectivePortalId(int portalId) private static List GetPropertyDefinitions(IHostSettings hostSettings, int portalId) { // Get the Cache Key - string key = string.Format(DataCache.ProfileDefinitionsCacheKey, portalId); + string key = string.Format(CultureInfo.InvariantCulture, DataCache.ProfileDefinitionsCacheKey, portalId); // Try fetching the List from the Cache var definitions = (List)DataCache.GetCache(key); @@ -584,7 +585,7 @@ private static List GetPropertyDefinitions(IHostSetti } // definitions caching settings - int timeOut = DataCache.ProfileDefinitionsCacheTimeOut * Convert.ToInt32(hostSettings.PerformanceSetting); + int timeOut = DataCache.ProfileDefinitionsCacheTimeOut * (int)hostSettings.PerformanceSetting; // Get the List from the database definitions = FillPropertyDefinitionInfoCollection(DataProvider.GetPropertyDefinitionsByPortal(portalId)); diff --git a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs index 4a698e1f846..f5a0c366aaf 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs @@ -6,35 +6,25 @@ namespace DotNetNuke.Entities.Profile using System; using System.Collections; - /// - /// The ProfilePropertyDefinitionCollection class provides Business Layer methods for - /// a collection of property Definitions. - /// + using DotNetNuke.Collections; + + /// The ProfilePropertyDefinitionCollection class provides Business Layer methods for a collection of property Definitions. [Serializable] - public class ProfilePropertyDefinitionCollection : CollectionBase + public class ProfilePropertyDefinitionCollection : GenericCollectionBase { - /// - /// Initializes a new instance of the class. - /// Constructs a new default collection. - /// + /// Initializes a new instance of the class. public ProfilePropertyDefinitionCollection() { } - /// - /// Initializes a new instance of the class. - /// Constructs a new Collection from an ArrayList of ProfilePropertyDefinition objects. - /// + /// Initializes a new instance of the class from an ArrayList of ProfilePropertyDefinition objects. /// An ArrayList of ProfilePropertyDefinition objects. public ProfilePropertyDefinitionCollection(ArrayList definitionsList) { this.AddRange(definitionsList); } - /// - /// Initializes a new instance of the class. - /// Constructs a new Collection from a ProfilePropertyDefinitionCollection. - /// + /// Initializes a new instance of the class from a ProfilePropertyDefinitionCollection. /// A ProfilePropertyDefinitionCollection. public ProfilePropertyDefinitionCollection(ProfilePropertyDefinitionCollection collection) { @@ -45,38 +35,7 @@ public ProfilePropertyDefinitionCollection(ProfilePropertyDefinitionCollection c /// This overload returns the item by its name. /// The name of the Property to get. /// A ProfilePropertyDefinition object. - public ProfilePropertyDefinition this[string name] - { - get - { - return this.GetByName(name); - } - } - - /// Gets and sets an item in the collection. - /// This overload returns the item by its index. - /// The index to get. - /// A ProfilePropertyDefinition object. - public ProfilePropertyDefinition this[int index] - { - get - { - return (ProfilePropertyDefinition)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - /// Adds a property Definition to the collectio. - /// A ProfilePropertyDefinition object. - /// The index of the property Definition in the collection. - public int Add(ProfilePropertyDefinition value) - { - return this.List.Add(value); - } + public ProfilePropertyDefinition this[string name] => this.GetByName(name); /// Add an ArrayList of ProfilePropertyDefinition objects. /// An ArrayList of ProfilePropertyDefinition objects. @@ -98,14 +57,6 @@ public void AddRange(ProfilePropertyDefinitionCollection collection) } } - /// Determines whether the collection contains a property definition. - /// A ProfilePropertyDefinition object. - /// A Boolean True/False. - public bool Contains(ProfilePropertyDefinition value) - { - return this.List.Contains(value); - } - /// Gets a sub-collection of items in the collection by category. /// The category to get. /// A ProfilePropertyDefinitionCollection object. @@ -123,7 +74,7 @@ public ProfilePropertyDefinitionCollection GetByCategory(string category) return collection; } - /// Gets an item in the collection by Id. + /// Gets an item in the collection by ID. /// The id of the Property to get. /// A ProfilePropertyDefinition object. public ProfilePropertyDefinition GetById(int id) @@ -158,29 +109,6 @@ public ProfilePropertyDefinition GetByName(string name) return profileItem; } - /// Gets the index of a property Definition. - /// A ProfilePropertyDefinition object. - /// The index of the property Definition in the collection. - public int IndexOf(ProfilePropertyDefinition value) - { - return this.List.IndexOf(value); - } - - /// Inserts a property Definition into the collection. - /// The index to insert the item at. - /// A ProfilePropertyDefinition object. - public void Insert(int index, ProfilePropertyDefinition value) - { - this.List.Insert(index, value); - } - - /// Removes a property definition from the collection. - /// The ProfilePropertyDefinition object to remove. - public void Remove(ProfilePropertyDefinition value) - { - this.List.Remove(value); - } - /// Sorts the collection using the ProfilePropertyDefinitionComparer (ie by ViewOrder). public void Sort() { diff --git a/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs b/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs index 21827a45231..97c3003b80a 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs @@ -40,7 +40,7 @@ public ProfileVisibility(int portalId, string extendedVisibility) var roles = lists[0].Substring(2).TrimEnd(',').Split(','); foreach (var role in roles) { - int roleId = int.Parse(role); + int roleId = int.Parse(role, CultureInfo.InvariantCulture); RoleInfo userRole = RoleController.Instance.GetRole(portalId, r => r.RoleID == roleId); this.RoleVisibilities.Add(userRole); } @@ -51,7 +51,7 @@ public ProfileVisibility(int portalId, string extendedVisibility) var relationships = lists[1].Substring(2).TrimEnd(',').Split(','); foreach (var relationship in relationships) { - Relationship userRelationship = RelationshipController.Instance.GetRelationship(int.Parse(relationship)); + Relationship userRelationship = RelationshipController.Instance.GetRelationship(int.Parse(relationship, CultureInfo.InvariantCulture)); this.RelationshipVisibilities.Add(userRelationship); } } diff --git a/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs b/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs index 7f8baeda5b4..e3ca4e31036 100644 --- a/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs +++ b/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs @@ -2,20 +2,23 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs.Actions -{ - public interface ITabEventHandler - { - void TabCreated(object sender, TabEventArgs args); - - void TabUpdated(object sender, TabEventArgs args); - - void TabRemoved(object sender, TabEventArgs args); - - void TabDeleted(object sender, TabEventArgs args); - - void TabRestored(object sender, TabEventArgs args); - - void TabMarkedAsPublished(object sender, TabEventArgs args); - } -} +namespace DotNetNuke.Entities.Tabs.Actions +{ + using System.Diagnostics.CodeAnalysis; + + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public interface ITabEventHandler + { + void TabCreated(object sender, TabEventArgs args); + + void TabUpdated(object sender, TabEventArgs args); + + void TabRemoved(object sender, TabEventArgs args); + + void TabDeleted(object sender, TabEventArgs args); + + void TabRestored(object sender, TabEventArgs args); + + void TabMarkedAsPublished(object sender, TabEventArgs args); + } +} diff --git a/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs b/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs index 7088c7c754b..673d51e38d0 100644 --- a/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs +++ b/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs @@ -2,12 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs.Actions -{ - public interface ITabSyncEventHandler - { - void TabSerialize(object sender, TabSyncEventArgs args); - - void TabDeserialize(object sender, TabSyncEventArgs args); - } -} +namespace DotNetNuke.Entities.Tabs.Actions +{ + using System.Diagnostics.CodeAnalysis; + + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public interface ITabSyncEventHandler + { + void TabSerialize(object sender, TabSyncEventArgs args); + + void TabDeserialize(object sender, TabSyncEventArgs args); + } +} diff --git a/DNN Platform/Library/Entities/Tabs/ITabChangeTracker.cs b/DNN Platform/Library/Entities/Tabs/ITabChangeTracker.cs index 897d8b2a467..56d675a743e 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabChangeTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabChangeTracker.cs @@ -2,42 +2,49 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs -{ - using DotNetNuke.Entities.Modules; +namespace DotNetNuke.Entities.Tabs +{ + using System.Diagnostics.CodeAnalysis; - public interface ITabChangeTracker - { - /// Tracks a change when a module is added to a page. - /// Module which tracks the change. - /// Version number corresponding to the change. - /// User Id who provokes the change. - void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId); - - /// Tracks a change when a module is modified on a page. - /// Module which tracks the change. - /// Version number corresponding to the change. - /// User Id who provokes the change. - void TrackModuleModification(ModuleInfo module, int moduleVersion, int userId); - - /// Tracks a change when a module is deleted from a page. - /// Module which tracks the change. - /// Version number corresponding to the change. - /// User Id who provokes the change. - void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId); - - /// Tracks a change when a module is copied from an exisitng page. - /// Module which tracks the change. - /// Version number corresponding to the change. - /// Tab Id where the module originally is. - /// User Id who provokes the change. - void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId); - - /// Tracks a change when a copied module is deleted from an exisitng page. - /// Module which tracks the change. - /// Version number corresponding to the change. - /// Tab Id where the module originally is. - /// User Id who provokes the change. - void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId); - } -} + using DotNetNuke.Entities.Modules; + + public interface ITabChangeTracker + { + /// Tracks a change when a module is added to a page. + /// Module which tracks the change. + /// Version number corresponding to the change. + /// User ID who provokes the change. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId); + + /// Tracks a change when a module is modified on a page. + /// Module which tracks the change. + /// Version number corresponding to the change. + /// User ID who provokes the change. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + void TrackModuleModification(ModuleInfo module, int moduleVersion, int userId); + + /// Tracks a change when a module is deleted from a page. + /// Module which tracks the change. + /// Version number corresponding to the change. + /// User ID who provokes the change. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId); + + /// Tracks a change when a module is copied from an existing page. + /// Module which tracks the change. + /// Version number corresponding to the change. + /// Tab ID where the module originally is. + /// User ID who provokes the change. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId); + + /// Tracks a change when a copied module is deleted from an existing page. + /// Module which tracks the change. + /// Version number corresponding to the change. + /// Tab ID where the module originally is. + /// User ID who provokes the change. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId); + } +} diff --git a/DNN Platform/Library/Entities/Tabs/TabController.cs b/DNN Platform/Library/Entities/Tabs/TabController.cs index ab5f3bdd6a3..84a0c8812ca 100644 --- a/DNN Platform/Library/Entities/Tabs/TabController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabController.cs @@ -1,2995 +1,3001 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Data; - using System.Globalization; - using System.Linq; - using System.Text.RegularExpressions; - using System.Web; - using System.Xml; - - using DotNetNuke.Abstractions.Modules; - using DotNetNuke.Common; - using DotNetNuke.Common.Internal; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Entities.Content; - using DotNetNuke.Entities.Content.Common; - using DotNetNuke.Entities.Content.Taxonomy; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Tabs.Actions; - using DotNetNuke.Entities.Tabs.TabVersions; - using DotNetNuke.Entities.Urls; - using DotNetNuke.Entities.Users; - using DotNetNuke.Framework; - using DotNetNuke.Instrumentation; - using DotNetNuke.Internal.SourceGenerators; - using DotNetNuke.Security.Permissions; - using DotNetNuke.Security.Roles; - using DotNetNuke.Services.Exceptions; - using DotNetNuke.Services.FileSystem; - using DotNetNuke.Services.Localization; - using DotNetNuke.Services.Log.EventLog; - using DotNetNuke.Services.Search.Entities; - - using Microsoft.Extensions.DependencyInjection; - - /// TabController provides all operation to . - /// - /// Tab is equal to page in DotNetNuke. - /// Tabs will be a sitemap for a portal, and every request at first need to check whether there is valid tab information - /// include in the url, if not it will use default tab to display information. - /// - public partial class TabController : ServiceLocator, ITabController - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabController)); - private static readonly Regex TabNameCheck1 = new Regex("^LPT[1-9]$|^COM[1-9]$", RegexOptions.IgnoreCase); - private static readonly Regex TabNameCheck2 = new Regex("^AUX$|^CON$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$|^LOGIN$|^REGISTER$", RegexOptions.IgnoreCase); - - private readonly DataProvider dataProvider = DataProvider.Instance(); - - /// Gets the current page in current http request. - /// Current Page Info. - public static TabInfo CurrentPage => PortalSettings.Current?.ActiveTab; - - /// Copies the design to children. - /// The parent tab. - /// The skin SRC. - /// The container SRC. - public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc) - { - CopyDesignToChildren(parentTab, skinSrc, containerSrc, PortalController.GetActivePortalLanguage(parentTab.PortalID)); - } - - /// Copies the design to children. - /// The parent tab. - /// The skin SRC. - /// The container SRC. - /// The culture code. - public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc, string cultureCode) - { - bool clearCache = Null.NullBoolean; - List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); - foreach (TabInfo tab in childTabs) - { - if (TabPermissionController.CanAdminPage(tab)) - { - // Update ContentItem If necessary - if (tab.ContentItemId == Null.NullInteger && tab.TabID != Null.NullInteger) - { - Instance.CreateContentItem(tab); - } - - DataProvider.Instance().UpdateTab( - tab.TabID, - tab.ContentItemId, - tab.PortalID, - tab.VersionGuid, - tab.DefaultLanguageGuid, - tab.LocalizedVersionGuid, - tab.TabName, - tab.IsVisible, - tab.DisableLink, - tab.ParentId, - tab.IconFileRaw, - tab.IconFileLargeRaw, - tab.Title, - tab.Description, - tab.KeyWords, - tab.IsDeleted, - tab.Url, - skinSrc, - containerSrc, - tab.StartDate, - tab.EndDate, - tab.RefreshInterval, - tab.PageHeadText, - tab.IsSecure, - tab.PermanentRedirect, - tab.SiteMapPriority, - UserController.Instance.GetCurrentUserInfo().UserID, - tab.CultureCode, - tab.IsSystem); - - UpdateTabVersion(tab.TabID); - - EventLogController.Instance.AddLog( - tab, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - string.Empty, - EventLogController.EventLogType.TAB_UPDATED); - clearCache = true; - } - } - - if (clearCache) - { - DataCache.ClearTabsCache(childTabs[0].PortalID); - } - } - - /// Copies the permissions to children. - /// The parent tab. - /// The new permissions. - public static void CopyPermissionsToChildren(TabInfo parentTab, TabPermissionCollection newPermissions) - { - bool clearCache = Null.NullBoolean; - List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); - foreach (TabInfo tab in childTabs) - { - if (TabPermissionController.CanAdminPage(tab)) - { - tab.TabPermissions.Clear(); - tab.TabPermissions.AddRange(newPermissions); - TabPermissionController.SaveTabPermissions(tab); - UpdateTabVersion(tab.TabID); - clearCache = true; - } - } - - if (clearCache) - { - DataCache.ClearTabsCache(childTabs[0].PortalID); - } - } - - /// Processes all panes and modules in the template file. - /// The business controller provider. - /// Template file node for the panes is current tab. - /// PortalId of the new portal. - /// Tab being processed. - /// Tabs need to merge. - /// Modules Hashtable. - public static void DeserializePanes(IBusinessControllerProvider businessControllerProvider, XmlNode nodePanes, int portalId, int tabId, PortalTemplateModuleAction mergeTabs, Hashtable hModules) - { - Dictionary dicModules = ModuleController.Instance.GetTabModules(tabId); - - // If Mode is Replace remove all the modules already on this Tab - if (mergeTabs == PortalTemplateModuleAction.Replace) - { - foreach (KeyValuePair kvp in dicModules) - { - var module = kvp.Value; - - // when the modules show on all pages are included by the same import process, it need removed. - if (!module.AllTabs || hModules.ContainsValue(module.ModuleID)) - { - ModuleController.Instance.DeleteTabModule(tabId, kvp.Value.ModuleID, false); - } - } - } - - // iterate through the panes - foreach (XmlNode nodePane in nodePanes.ChildNodes) - { - // iterate through the modules - if (nodePane.SelectSingleNode("modules") != null) - { - XmlNode selectSingleNode = nodePane.SelectSingleNode("modules"); - if (selectSingleNode != null) - { - foreach (XmlNode nodeModule in selectSingleNode) - { - ModuleController.DeserializeModule(businessControllerProvider, nodeModule, nodePane, portalId, tabId, mergeTabs, hModules); - } - } - } - } - - // if deserialize tab from install wizard, we need parse deserialize handlers first. - var installFromWizard = HttpContext.Current != null && HttpContext.Current.Items.Contains("InstallFromWizard"); - if (installFromWizard) - { - HttpContext.Current.Items.Remove("InstallFromWizard"); - EventManager.Instance.RefreshTabSyncHandlers(); - } - - EventManager.Instance.OnTabDeserialize(new TabSyncEventArgs { Tab = Instance.GetTab(tabId, portalId), TabNode = nodePanes.ParentNode }); - } - - /// Deserializes the tab. - /// The business controller provider. - /// The node tab. - /// The obj tab. - /// The portal id. - /// The merge tabs. - /// The deserialized instance. - public static TabInfo DeserializeTab(IBusinessControllerProvider businessControllerProvider, XmlNode tabNode, TabInfo tab, int portalId, PortalTemplateModuleAction mergeTabs) - { - return DeserializeTab(businessControllerProvider, tabNode, tab, new Hashtable(), portalId, false, mergeTabs, new Hashtable()); - } - - /// Deserializes the tab. - /// The business controller provider. - /// The node tab. - /// The obj tab. - /// The h tabs. - /// The portal id. - /// if set to [is admin template]. - /// The merge tabs. - /// The h modules. - /// The deserialized instance. - public static TabInfo DeserializeTab(IBusinessControllerProvider businessControllerProvider, XmlNode tabNode, TabInfo tab, Hashtable tabs, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, Hashtable modules) - { - string tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "name"); - if (!string.IsNullOrEmpty(tabName)) - { - if (tab == null) - { - tab = new TabInfo { TabID = Null.NullInteger, ParentId = Null.NullInteger, TabName = tabName }; - } - - tab.PortalID = portalId; - if (string.IsNullOrEmpty(tab.Title)) - { - tab.Title = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "title"); - } - - if (string.IsNullOrEmpty(tab.Description)) - { - tab.Description = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "description"); - } - - tab.KeyWords = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "keywords"); - tab.IsVisible = XmlUtils.GetNodeValueBoolean(tabNode, "visible", true); - tab.DisableLink = XmlUtils.GetNodeValueBoolean(tabNode, "disabled"); - tab.IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfile")); - tab.IconFileLarge = Globals.ImportFile( - portalId, - XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfilelarge")); - tab.Url = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "url"); - tab.StartDate = XmlUtils.GetNodeValueDate(tabNode, "startdate", Null.NullDate); - tab.EndDate = XmlUtils.GetNodeValueDate(tabNode, "enddate", Null.NullDate); - tab.RefreshInterval = XmlUtils.GetNodeValueInt(tabNode, "refreshinterval", Null.NullInteger); - tab.PageHeadText = XmlUtils.GetNodeValue(tabNode, "pageheadtext", Null.NullString); - tab.IsSecure = XmlUtils.GetNodeValueBoolean(tabNode, "issecure", false); - tab.SiteMapPriority = XmlUtils.GetNodeValueSingle(tabNode, "sitemappriority", 0.5F); - tab.CultureCode = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "cultureCode"); - - // objTab.UniqueId = New Guid(XmlUtils.GetNodeValue(nodeTab, "guid", Guid.NewGuid.ToString())); - // objTab.VersionGuid = New Guid(XmlUtils.GetNodeValue(nodeTab, "versionGuid", Guid.NewGuid.ToString())); - tab.UseBaseFriendlyUrls = XmlUtils.GetNodeValueBoolean(tabNode, "UseBaseFriendlyUrls", false); - - tab.TabPermissions.Clear(); - DeserializeTabPermissions(tabNode.SelectNodes("tabpermissions/permission"), tab, isAdminTemplate); - - DeserializeTabSettings(tabNode.SelectNodes("tabsettings/tabsetting"), tab); - - // set tab skin and container - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty))) - { - tab.SkinSrc = XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty); - } - - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty))) - { - tab.ContainerSrc = XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty); - } - - tabName = tab.TabName; - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"))) - { - if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")] != null) - { - // parent node specifies the path (tab1/tab2/tab3), use saved tabid - tab.ParentId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")]); - tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent") + "/" + tab.TabName; - } - else - { - // Parent node doesn't spcecify the path, search by name. - // Possible incoherence if tabname not unique - TabInfo objParent = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"), portalId); - if (objParent != null) - { - tab.ParentId = objParent.TabID; - tabName = objParent.TabName + "/" + tab.TabName; - } - else - { - // parent tab not found! - tab.ParentId = Null.NullInteger; - tabName = tab.TabName; - } - } - } - - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"))) - { - if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")] != null) - { - // parent node specifies the path (tab1/tab2/tab3), use saved tabid - int defaultLanguageTabId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")]); - TabInfo defaultLanguageTab = Instance.GetTab(defaultLanguageTabId, portalId, false); - if (defaultLanguageTab != null) - { - tab.DefaultLanguageGuid = defaultLanguageTab.UniqueId; - } - } - else - { - // Parent node doesn't spcecify the path, search by name. - // Possible incoherence if tabname not unique - TabInfo defaultLanguageTab = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"), portalId); - if (defaultLanguageTab != null) - { - tab.DefaultLanguageGuid = defaultLanguageTab.UniqueId; - } - } - } - - // create/update tab - if (tab.TabID == Null.NullInteger) - { - tab.TabID = TabController.Instance.AddTab(tab); - } - else - { - Instance.UpdateTab(tab); - } - - // UpdateTabUrls - foreach (XmlNode oTabUrlNode in tabNode.SelectNodes("tabUrls/tabUrl")) - { - var tabUrl = new TabUrlInfo(); - DeserializeTabUrls(oTabUrlNode, tabUrl); - DataProvider.Instance().SaveTabUrl(tab.TabID, tabUrl.SeqNum, tabUrl.PortalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.Instance.GetCurrentUserInfo().UserID); - } - - // extra check for duplicate tabs in same level - if (tabs[tabName] == null) - { - tabs.Add(tabName, tab.TabID); - } - } - - // Parse Panes - if (tabNode.SelectSingleNode("panes") != null) - { - DeserializePanes(businessControllerProvider, tabNode.SelectSingleNode("panes"), portalId, tab.TabID, mergeTabs, modules); - } - - // Finally add "tabid" to node - tabNode.AppendChild(XmlUtils.CreateElement(tabNode.OwnerDocument, "tabid", tab.TabID.ToString())); - return tab; - } - - /// Gets the portal tabs. - /// The portal id. - /// The exclude tab id. - /// if set to [include none specified]. - /// if set to [include hidden]. - /// A or instances. - public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, bool includeHidden) - { - return GetPortalTabs( - GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - "<" + Localization.GetString("None_Specified") + ">", - includeHidden, - false, - false, - false, - false, - true); - } - - /// Gets the portal tabs. - /// The portal id. - /// The exclude tab id. - /// if set to [include none specified]. - /// if set to [include hidden]. - /// if set to [include deleted]. - /// if set to [include URL]. - /// A or instances. - public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, bool includeHidden, bool includeDeleted, bool includeURL) - { - return GetPortalTabs( - GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - "<" + Localization.GetString("None_Specified") + ">", - includeHidden, - includeDeleted, - includeURL, - false, - false, - true); - } - - /// Gets the portal tabs. - /// The portal id. - /// The exclude tab id. - /// if set to [include none specified]. - /// The none specified text. - /// if set to [include hidden]. - /// if set to [include deleted]. - /// if set to [include URL]. - /// if set to [check view permission]. - /// if set to [check edit permission]. - /// A or instances. - public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, bool checkViewPermisison, bool checkEditPermission) - { - return GetPortalTabs( - GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - noneSpecifiedText, - includeHidden, - includeDeleted, - includeURL, - checkViewPermisison, - checkEditPermission, - true); - } - - /// Gets the portal tabs. - /// The tabs. - /// The exclude tab id. - /// if set to [include none specified]. - /// The none specified text. - /// if set to [include hidden]. - /// if set to [include deleted]. - /// if set to [include URL]. - /// if set to [check view permission]. - /// if set to [check edit permission]. - /// A or instances. - public static List GetPortalTabs(List tabs, int excludeTabId, bool includeNoneSpecified, string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, bool checkViewPermisison, bool checkEditPermission) - { - return GetPortalTabs( - tabs, - excludeTabId, - includeNoneSpecified, - noneSpecifiedText, - includeHidden, - includeDeleted, - includeURL, - checkViewPermisison, - checkEditPermission, - true); - } - - /// Gets the portal tabs. - /// The tabs. - /// The exclude tab id. - /// if set to [include none specified]. - /// The none specified text. - /// if set to [include hidden]. - /// if set to [include deleted]. - /// if set to [include URL]. - /// if set to [check view permission]. - /// if set to [check edit permission]. - /// The value of this parameter affects property. - /// A or instances. - public static List GetPortalTabs( - List tabs, - int excludeTabId, - bool includeNoneSpecified, - string noneSpecifiedText, - bool includeHidden, - bool includeDeleted, - bool includeURL, - bool checkViewPermisison, - bool checkEditPermission, - bool includeDeletedChildren) - { - var listTabs = new List(); - if (includeNoneSpecified) - { - var tab = new TabInfo { TabID = -1, TabName = noneSpecifiedText, TabOrder = 0, ParentId = -2 }; - listTabs.Add(tab); - } - - foreach (TabInfo tab in tabs) - { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - if (((excludeTabId < 0) || (tab.TabID != excludeTabId)) && - (!tab.IsSuperTab || objUserInfo.IsSuperUser)) - { - if ((tab.IsVisible || includeHidden) && tab.HasAVisibleVersion && (tab.IsDeleted == false || includeDeleted) && - (tab.TabType == TabType.Normal || includeURL)) - { - // Check if User has View/Edit Permission for this tab - if (checkEditPermission || checkViewPermisison) - { - const string permissionList = "ADD,COPY,EDIT,MANAGE"; - if (checkEditPermission && - TabPermissionController.HasTabPermission(tab.TabPermissions, permissionList)) - { - listTabs.Add(tab); - } - else if (checkViewPermisison && TabPermissionController.CanViewPage(tab)) - { - listTabs.Add(tab); - } - } - else - { - // Add Tab to List - listTabs.Add(tab); - } - } - - // HasChildren should be true in case there is at least one not deleted child - tab.HasChildren = tab.HasChildren && (includeDeletedChildren || GetTabsByParent(tab.TabID, tab.PortalID).Any(a => !a.IsDeleted)); - } - } - - return listTabs; - } - - /// Gets the tab by tab path. - /// The portal id. - /// The tab path. - /// The culture code. - /// The tab ID or -1. - public static int GetTabByTabPath(int portalId, string tabPath, string cultureCode) - { - var tabPathDictionary = GetTabPathDictionary(portalId, cultureCode); - if (tabPathDictionary.TryGetValue(tabPath, out var tabId)) - { - return tabId; - } - - return -1; - } - - /// Gets the tab path dictionary. - /// The portal id. - /// The culture code. - /// A mapping tab path to tab ID. - public static Dictionary GetTabPathDictionary(int portalId, string cultureCode) - { - string cacheKey = string.Format(DataCache.TabPathCacheKey, cultureCode, portalId); - return - CBO.GetCachedObject>( - new CacheItemArgs(cacheKey, DataCache.TabPathCacheTimeOut, DataCache.TabPathCachePriority, cultureCode, portalId), - GetTabPathDictionaryCallback); - } - - /// Gets the tabs by parent. - /// The parent id. - /// The portal id. - /// A or instances. - public static List GetTabsByParent(int parentId, int portalId) - { - return Instance.GetTabsByPortal(portalId).WithParentId(parentId); - } - - /// Gets the tabs by sort order. - /// The portal id. - /// The culture code. - /// if set to [include neutral]. - /// A or instances. - public static List GetTabsBySortOrder(int portalId, string cultureCode, bool includeNeutral) - { - return Instance.GetTabsByPortal(portalId).WithCulture(cultureCode, includeNeutral).AsList(); - } - - /// Get all TabInfo for the current culture in SortOrder. - /// The portal ID to load tabs for. - /// List of TabInfo ordered by default SortOrder. - /// - /// This method uses the Active culture. There is an overload - /// which allows the culture information to be specified. - /// - public static List GetTabsBySortOrder(int portalId) - { - return GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true); - } - - /// Determines whether is special tab. - /// The tab id. - /// The portal id. - /// if the page is special, otherwise . - public static bool IsSpecialTab(int tabId, int portalId) - { - Dictionary locales = LocaleController.Instance.GetLocales(portalId); - bool isSpecial = false; - foreach (Locale locale in locales.Values) - { - PortalInfo portal = PortalController.Instance.GetPortal(portalId, locale.Code); - var portalSettings = new PortalSettings(portal); - isSpecial = IsSpecialTab(tabId, portalSettings); - - if (isSpecial) - { - break; - } - } - - return isSpecial; - } - - /// Determines whether is special tab. - /// The tab id. - /// The portal settings. - /// if is special tab; otherwise, . - public static bool IsSpecialTab(int tabId, PortalSettings portalSettings) - { - return tabId == portalSettings.SplashTabId || tabId == portalSettings.HomeTabId || - tabId == portalSettings.LoginTabId || tabId == portalSettings.UserTabId || - tabId == portalSettings.AdminTabId || tabId == portalSettings.SuperTabId; - } - - /// Serializes the metadata of a page and its modules (and optionally the modules' contents) to an XML node. - /// The DI container. - /// The Xml Document to use for the Tab. - /// The TabInfo object to serialize. - /// A flag used to determine if the Module content is included. - /// An representing the page's data. - public static XmlNode SerializeTab(IBusinessControllerProvider businessControllerProvider, XmlDocument tabXml, TabInfo objTab, bool includeContent) - { - return SerializeTab(businessControllerProvider, tabXml, null, objTab, null, includeContent); - } - - /// Serializes the metadata of a page and its modules (and optionally the modules' contents) to an XML node. - /// The business controller provider. - /// The Xml Document to use for the Tab. - /// A Hashtable used to store the names of the tabs. - /// The TabInfo object to serialize. - /// The Portal object to which the tab belongs. - /// A flag used to determine if the Module content is included. - /// An representing the page's data. - public static XmlNode SerializeTab(IBusinessControllerProvider businessControllerProvider, XmlDocument tabXml, Hashtable tabs, TabInfo tab, PortalInfo portal, bool includeContent) - { - XmlElement newElement; - CBO.SerializeObject(tab, tabXml); - - var tabNode = tabXml.SelectSingleNode("tab"); - if (tabNode != null) - { - if (tabNode.Attributes != null) - { - tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsd"]); - tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsi"]); - } - - // remove unwanted elements - // ReSharper disable AssignNullToNotNullAttribute - tabNode.RemoveChildNode("tabid"); - tabNode.RemoveChildNode("moduleID"); - tabNode.RemoveChildNode("taborder"); - tabNode.RemoveChildNode("portalid"); - tabNode.RemoveChildNode("parentid"); - tabNode.RemoveChildNode("isdeleted"); - tabNode.RemoveChildNode("tabpath"); - tabNode.RemoveChildNode("haschildren"); - tabNode.RemoveChildNode("skindoctype"); - tabNode.RemoveChildNode("uniqueid"); - tabNode.RemoveChildNode("versionguid"); - tabNode.RemoveChildNode("defaultLanguageGuid"); - tabNode.RemoveChildNode("localizedVersionGuid"); - var xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); - if (xmlNodeList is { Count: 0, }) - { - // for some reason serialization of permissions did not work - // we are using a different method here to make sure that - // permissions are included in the tabinfo xml - var tabPermissions = new XmlDocument { XmlResolver = null, }; - CBO.SerializeObject(tab.TabPermissions, tabPermissions); - - var permissionsNode = tabXml.CreateElement("tabpermissions"); - var tabPermissionsNodeList = tabPermissions.SelectNodes("tabpermissions/TabPermissionInfo"); - if (tabPermissionsNodeList != null) - { - foreach (XmlNode nodePermission in tabPermissionsNodeList) - { - var newNode = tabXml.CreateElement("permission"); - newNode.InnerXml = nodePermission.InnerXml; - permissionsNode.AppendChild(newNode); - } - } - - tabNode.AppendChild(permissionsNode); - - // re-select the permissions node - xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); - } - - if (xmlNodeList != null) - { - foreach (XmlNode nodePermission in xmlNodeList) - { - nodePermission.RemoveChildNode("tabpermissionid"); - nodePermission.RemoveChildNode("permissionid"); - nodePermission.RemoveChildNode("tabid"); - nodePermission.RemoveChildNode("roleid"); - nodePermission.RemoveChildNode("userid"); - nodePermission.RemoveChildNode("username"); - nodePermission.RemoveChildNode("displayname"); - } - } - - // ReSharper restore AssignNullToNotNullAttribute - } - - // Manage Url - XmlNode urlNode = tabXml.SelectSingleNode("tab/url"); - switch (tab.TabType) - { - case TabType.Normal: - urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Normal")); - break; - case TabType.Tab: - urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Tab")); - - // Get the tab being linked to - TabInfo tempTab = TabController.Instance.GetTab(int.Parse(tab.Url), tab.PortalID, false); - if (tempTab != null) - { - urlNode.InnerXml = tempTab.TabPath; - } - - break; - case TabType.File: - urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "File")); - IFileInfo file = FileManager.Instance.GetFile(int.Parse(tab.Url.Substring(7))); - urlNode.InnerXml = file.RelativePath; - break; - case TabType.Url: - urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Url")); - break; - } - - // serialize TabSettings - XmlUtils.SerializeHashtable(tab.TabSettings, tabXml, tabNode, "tabsetting", "settingname", "settingvalue"); - if (portal != null) - { - if (tab.TabID == portal.SplashTabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "splashtab"; - tabNode.AppendChild(newElement); - } - else if (tab.TabID == portal.HomeTabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "hometab"; - tabNode.AppendChild(newElement); - } - else if (tab.TabID == portal.UserTabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "usertab"; - tabNode.AppendChild(newElement); - } - else if (tab.TabID == portal.LoginTabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "logintab"; - tabNode.AppendChild(newElement); - } - else if (tab.TabID == portal.SearchTabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "searchtab"; - tabNode.AppendChild(newElement); - } - else if (tab.TabID == portal.Custom404TabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "404tab"; - tabNode.AppendChild(newElement); - } - else if (tab.TabID == portal.Custom500TabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "500tab"; - tabNode.AppendChild(newElement); - } - else if (tab.TabID == portal.TermsTabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "termstab"; - tabNode.AppendChild(newElement); - } - else if (tab.TabID == portal.PrivacyTabId) - { - newElement = tabXml.CreateElement("tabtype"); - newElement.InnerXml = "privacytab"; - tabNode.AppendChild(newElement); - } - } - - if (tabs != null) - { - // Manage Parent Tab - if (!Null.IsNull(tab.ParentId)) - { - newElement = tabXml.CreateElement("parent"); - newElement.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.ParentId].ToString()); - tabNode.AppendChild(newElement); - - // save tab as: ParentTabName/CurrentTabName - tabs.Add(tab.TabID, tabs[tab.ParentId] + "/" + tab.TabName); - } - else - { - // save tab as: CurrentTabName - tabs.Add(tab.TabID, tab.TabName); - } - } - - // Manage Content Localization - if (tab.DefaultLanguageTab != null) - { - try - { - newElement = tabXml.CreateElement("defaultLanguageTab"); - newElement.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.DefaultLanguageTab.TabID].ToString()); - tabNode.AppendChild(newElement); - } - catch - { - // ignore - } - } - - // Serialize modules - var panesNode = tabNode.AppendChild(tabXml.CreateElement("panes")); - foreach (var kvp in ModuleController.Instance.GetTabModules(tab.TabID)) - { - var module = kvp.Value; - if (!module.IsDeleted) - { - var moduleXml = new XmlDocument { XmlResolver = null }; - var moduleNode = ModuleController.SerializeModule(businessControllerProvider, moduleXml, module, includeContent); - if (panesNode.SelectSingleNode($"descendant::pane[name='{module.PaneName}']") == null) - { - // new pane found - var paneNode = moduleXml.CreateElement("pane"); - var nameNode = paneNode.AppendChild(moduleXml.CreateElement("name")); - nameNode.InnerText = module.PaneName; - paneNode.AppendChild(moduleXml.CreateElement("modules")); - panesNode.AppendChild(tabXml.ImportNode(paneNode, true)); - } - - var modulesNode = panesNode.SelectSingleNode($"descendant::pane[name='{module.PaneName}']/modules"); - modulesNode.AppendChild(tabXml.ImportNode(moduleNode, true)); - } - } - - // Serialize TabUrls - var tabUrlsNode = tabNode.AppendChild(tabXml.CreateElement("tabUrls")); - foreach (var tabUrl in TabController.Instance.GetTabUrls(tab.TabID, tab.PortalID)) - { - var tabUrlXml = new XmlDocument { XmlResolver = null }; - XmlNode tabUrlNode = tabUrlXml.CreateElement("tabUrl"); - tabUrlNode.AddAttribute("SeqNum", tabUrl.SeqNum.ToString(CultureInfo.InvariantCulture)); - tabUrlNode.AddAttribute("Url", tabUrl.Url); - tabUrlNode.AddAttribute("QueryString", tabUrl.QueryString); - tabUrlNode.AddAttribute("HttpStatus", tabUrl.HttpStatus); - tabUrlNode.AddAttribute("CultureCode", tabUrl.CultureCode); - tabUrlNode.AddAttribute("IsSystem", tabUrl.IsSystem.ToString()); - tabUrlsNode.AppendChild(tabXml.ImportNode(tabUrlNode, true)); - } - - EventManager.Instance.OnTabSerialize(new TabSyncEventArgs { Tab = tab, TabNode = tabNode }); - - return tabNode; - } - - /// check whether have conflict between tab path and portal alias. - /// portal id. - /// tab path. - /// if the tab path is a duplicate of a portal alias, otherwise . - public static bool IsDuplicateWithPortalAlias(int portalId, string tabPath) - { - var aliasLookup = PortalAliasController.Instance.GetPortalAliases(); - - foreach (PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId)) - { - string checkAlias = string.Format("{0}{1}", alias.HTTPAlias, tabPath.Replace("//", "/")); - - foreach (PortalAliasInfo a in aliasLookup.Values) - { - if (a.HTTPAlias.Equals(checkAlias, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - } - - return false; - } - - public static bool IsValidTabName(string tabName, out string invalidType) - { - invalidType = string.Empty; - - if (string.IsNullOrEmpty(tabName.Trim())) - { - invalidType = "EmptyTabName"; - return false; - } - - var cleanTabName = HtmlUtils.StripNonWord(tabName, false); - if (TabNameCheck1.IsMatch(tabName) || TabNameCheck2.IsMatch(cleanTabName)) - { - invalidType = "InvalidTabName"; - return false; - } - - if (Config.GetFriendlyUrlProvider() == "advanced" && PortalSettings.Current != null) - { - var doNotRewriteRegex = new FriendlyUrlSettings(PortalSettings.Current.PortalId).DoNotRewriteRegex; - if (!string.IsNullOrEmpty(doNotRewriteRegex) && - (Regex.IsMatch(cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) - || Regex.IsMatch("/" + cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) - || Regex.IsMatch("/" + cleanTabName + "/", doNotRewriteRegex, RegexOptions.IgnoreCase))) - { - invalidType = "InvalidTabName"; - return false; - } - } - - return true; - } - - /// - public bool AddMissingLanguagesWithWarnings(int portalId, int tabId) - { - var addedAllMissingLanguages = true; - var currentTab = this.GetTab(tabId, portalId, false); - if (currentTab.CultureCode != null) - { - var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalId); - var workingTab = currentTab; - if (workingTab.CultureCode != defaultLocale.Code && workingTab.DefaultLanguageTab == null) - { - // we are adding missing languages to a single culture page that is not in the default language - // so we must first add a page in the default culture - this.CreateLocalizedCopyInternal(workingTab, defaultLocale, false, true, insertAfterOriginal: true); - } - - if (currentTab.DefaultLanguageTab != null) - { - workingTab = currentTab.DefaultLanguageTab; - } - - foreach (Locale locale in LocaleController.Instance.GetLocales(portalId).Values) - { - if (!LocaleController.Instance.IsDefaultLanguage(locale.Code)) - { - bool missing = true; - foreach (var localizedTab in workingTab.LocalizedTabs.Values.Where(localizedTab => localizedTab.CultureCode == locale.Code)) - { - missing = false; - } - - if (missing) - { - bool isRootOrLocalizedParentExists = this.CanLocalizeTabToLocale(workingTab, locale); - if (isRootOrLocalizedParentExists) - { - this.CreateLocalizedCopyInternal(workingTab, locale, false, true, insertAfterOriginal: true); - } - else - { - addedAllMissingLanguages = false; - } - } - } - } - - // For newly localized parent tabs, its localized children need to be updated to point at their corresponding localized parents - this.UpdateChildTabLocalizedParents(portalId, tabId); - } - - return addedAllMissingLanguages; - } - - /// Adds a tab. - /// The tab to be added. - /// The tab is added to the end of the current Level. - /// The new tab ID. - public int AddTab(TabInfo tab) - { - return this.AddTab(tab, true); - } - - /// Adds a tab. - /// The tab to be added. - /// Flag that indicates whether to add the "AllTabs" Modules. - /// The tab is added to the end of the current Level. - /// The new tab ID. - public int AddTab(TabInfo tab, bool includeAllTabsModules) - { - // Add tab to store - int tabID = this.AddTabInternal(tab, -1, -1, includeAllTabsModules); - - // Clear the Cache - this.ClearCache(tab.PortalID); - - return tabID; - } - - /// Adds a tab after the specified tab. - /// The tab to be added. - /// Id of the tab after which this tab is added. - /// The new tab ID. - public int AddTabAfter(TabInfo tab, int afterTabId) - { - // Add tab to store - int tabID = this.AddTabInternal(tab, afterTabId, -1, true); - - // Clear the Cache - this.ClearCache(tab.PortalID); - - return tabID; - } - - /// Adds a tab before the specified tab. - /// The tab to be added. - /// Id of the tab before which this tab is added. - /// The new tab ID. - public int AddTabBefore(TabInfo objTab, int beforeTabId) - { - // Add tab to store - int tabID = this.AddTabInternal(objTab, -1, beforeTabId, true); - - // Clear the Cache - this.ClearCache(objTab.PortalID); - - return tabID; - } - - /// Clears tabs and portal cache for the specific portal. - /// The portal id. - public void ClearCache(int portalId) - { - DataCache.ClearTabsCache(portalId); - - // Clear the Portal cache so the Pages count is correct - DataCache.ClearPortalCache(portalId, false); - - DataCache.RemoveCache(DataCache.PortalDictionaryCacheKey); - - CacheController.FlushPageIndexFromCache(); - } - - /// - public void RefreshCache(int portalId, int tabId) - { - var portalTabs = this.GetTabsByPortal(portalId); - if (portalTabs.WithTabId(tabId) != null) - { - var updateTab = this.GetTab(tabId, portalId, true); - portalTabs.RefreshCache(tabId, updateTab); - } - } - - /// - public void ConvertTabToNeutralLanguage(int portalId, int tabId, string cultureCode, bool clearCache) - { - // parent tabs can not be deleted - if (this.GetTabsByPortal(portalId).WithParentId(tabId).Count == 0) - { - // delete all translated / localized tabs for this tab - var tab = this.GetTab(tabId, portalId, true); - foreach (var localizedTab in tab.LocalizedTabs.Values) - { - this.HardDeleteTabInternal(localizedTab.TabID, portalId); - } - - // reset culture of current tab back to neutral - this.dataProvider.ConvertTabToNeutralLanguage(portalId, tabId, cultureCode); - if (clearCache) - { - this.ClearCache(portalId); - } - } - } - - /// Creates content item for the tab.. - /// The updated tab. - public void CreateContentItem(TabInfo tab) - { - // First create ContentItem as we need the ContentItemID - ContentType contentType = ContentType.Tab; - - IContentController contentController = Util.GetContentController(); - tab.Content = string.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; - if (contentType != null) - { - tab.ContentTypeId = contentType.ContentTypeId; - } - - tab.Indexed = false; - contentController.AddContentItem(tab); - } - - /// Creates the localized copies. - /// The original tab. - public void CreateLocalizedCopies(TabInfo originalTab) - { - Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(originalTab.PortalID); - foreach (Locale subLocale in LocaleController.Instance.GetLocales(originalTab.PortalID).Values) - { - if (subLocale.Code != defaultLocale.Code) - { - this.CreateLocalizedCopyInternal(originalTab, subLocale, false, true); - } - } - - // For newly localized parent tabs, its localized children need to be updated to point at their corresponding localized parents - this.UpdateChildTabLocalizedParents(originalTab.PortalID, originalTab.TabID); - } - - /// Creates the localized copy. - /// The original tab. - /// The locale. - /// Clear the cache?. - public void CreateLocalizedCopy(TabInfo originalTab, Locale locale, bool clearCache) - { - this.CreateLocalizedCopyInternal(originalTab, locale, true, clearCache); - - // For newly localized parent tabs, its localized children need to be updated to point at their corresponding localized parents - this.UpdateChildTabLocalizedParents(originalTab.PortalID, originalTab.TabID); - } - - /// Deletes a tab permanently from the database. - /// TabId of the tab to be deleted. - /// PortalId of the portal. - /// - /// The tab will not delete if it has child tab(s). - /// - public void DeleteTab(int tabId, int portalId) - { - // parent tabs can not be deleted - if (this.GetTabsByPortal(portalId).WithParentId(tabId).Count == 0) - { - this.HardDeleteTabInternal(tabId, portalId); - } - - this.ClearCache(portalId); - } - - /// Deletes a tab permanently from the database. - /// The tab id. - /// The portal id. - /// if set to will delete all child tabs. - public void DeleteTab(int tabId, int portalId, bool deleteDescendants) - { - List descendantList = this.GetTabsByPortal(portalId).DescendentsOf(tabId); - if (deleteDescendants && descendantList.Count > 0) - { - // Iterate through descendants from bottom - which will remove children first - for (int i = descendantList.Count - 1; i >= 0; i += -1) - { - this.HardDeleteTabInternal(descendantList[i].TabID, portalId); - } - } - - this.HardDeleteTabInternal(tabId, portalId); - this.ClearCache(portalId); - } - - /// Delete a Setting of a tab instance. - /// ID of the affected tab. - /// Name of the setting to be deleted. - public void DeleteTabSetting(int tabId, string settingName) - { - this.dataProvider.DeleteTabSetting(tabId, settingName); - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.TAB_SETTING_DELETED.ToString() }; - log.LogProperties.Add(new LogDetailInfo("TabID", tabId.ToString())); - log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); - LogController.Instance.AddLog(log); - - UpdateTabVersion(tabId); - this.ClearTabSettingsCache(tabId); - } - - /// Delete all Settings of a tab instance. - /// ID of the affected tab. - public void DeleteTabSettings(int tabId) - { - this.dataProvider.DeleteTabSettings(tabId); - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.TAB_SETTING_DELETED.ToString() }; - log.LogProperties.Add(new LogDetailInfo("TabId", tabId.ToString())); - LogController.Instance.AddLog(log); - UpdateTabVersion(tabId); - this.ClearTabSettingsCache(tabId); - } - - /// Delete a taburl. - /// the taburl. - /// the portal. - /// whether to clear the cache. - public void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) - { - DataProvider.Instance().DeleteTabUrl(tabUrl.TabId, tabUrl.SeqNum); - - EventLogController.Instance.AddLog( - "tabUrl.TabId", - tabUrl.TabId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.TABURL_DELETED); - if (clearCache) - { - DataCache.RemoveCache(string.Format(DataCache.TabUrlCacheKey, portalId)); - CacheController.ClearCustomAliasesCache(); - var tab = this.GetTab(tabUrl.TabId, portalId); - tab.ClearTabUrls(); - } - } - - /// - public bool DeleteTranslatedTabs(int portalId, string cultureCode, bool clearCache) - { - if (PortalController.Instance.GetCurrentPortalSettings() != null) - { - var defaultLanguage = PortalController.Instance.GetCurrentPortalSettings().DefaultLanguage; - if (cultureCode != defaultLanguage) - { - this.dataProvider.DeleteTranslatedTabs(portalId, cultureCode); - - if (clearCache) - { - this.ClearCache(portalId); - } - } - } - - return true; - } - - /// - public void EnsureNeutralLanguage(int portalId, string cultureCode, bool clearCache) - { - this.dataProvider.EnsureNeutralLanguage(portalId, cultureCode); - if (clearCache) - { - this.ClearCache(portalId); - } - } - - /// Get the list of skins per alias at tab level. - /// the tab id. - /// the portal id. - /// list of TabAliasSkinInfo. - public List GetAliasSkins(int tabId, int portalId) - { - // Get the Portal AliasSkin Dictionary - Dictionary> dicTabAliases = this.GetAliasSkins(portalId); - - // Get the Collection from the Dictionary - List tabAliases; - bool bFound = dicTabAliases.TryGetValue(tabId, out tabAliases); - if (!bFound) - { - // Return empty collection - tabAliases = new List(); - } - - return tabAliases; - } - - /// Get the list of custom aliases associated with a page (tab). - /// the tab id. - /// the portal id. - /// dictionary of tabid and aliases. - public Dictionary GetCustomAliases(int tabId, int portalId) - { - // Get the Portal CustomAlias Dictionary - Dictionary> dicCustomAliases = this.GetCustomAliases(portalId); - - // Get the Collection from the Dictionary - Dictionary customAliases; - bool bFound = dicCustomAliases.TryGetValue(tabId, out customAliases); - if (!bFound) - { - // Return empty collection - customAliases = new Dictionary(); - } - - return customAliases; - } - - /// Gets the tab. - /// The tab id. - /// The portal id or . - /// tab info. - public TabInfo GetTab(int tabId, int portalId) - { - return this.GetTab(tabId, portalId, false); - } - - /// Gets the tab. - /// The tab id. - /// The portal id or . - /// if set to will get tab info directly from database. - /// tab info. - public TabInfo GetTab(int tabId, int portalId, bool ignoreCache) - { - TabInfo tab = null; - - if (tabId <= 0) - { - Logger.WarnFormat("Invalid tabId {0} of portal {1}", tabId, portalId); - } - else if (ignoreCache || Host.Host.PerformanceSetting == Globals.PerformanceSettings.NoCaching) - { - // if we are using the cache - tab = CBO.FillObject(this.dataProvider.GetTab(tabId)); - } - else - { - // if we do not know the PortalId then try to find it in the Portals Dictionary using the TabId - portalId = GetPortalId(tabId, portalId); - - // if we have the PortalId then try to get the TabInfo object - tab = this.GetTabsByPortal(portalId).WithTabId(tabId) ?? - this.GetTabsByPortal(GetPortalId(tabId, Null.NullInteger)).WithTabId(tabId); - - if (tab == null) - { - // recheck the info directly from database to make sure we can avoid error if the cache doesn't update - // correctly, this may occurred when install is set up in web farm. - tab = CBO.FillObject(this.dataProvider.GetTab(tabId)); - - // if tab is not null, and it is for "portalId", that means that the cache doesn't update correctly, - // we need to clear the cache and let it rebuild cache when request next time. - if (tab != null && tab.PortalID == portalId) - { - this.ClearCache(tab.PortalID); - } - else - { - Logger.WarnFormat("Unable to find tabId {0} of portal {1}", tabId, portalId); - } - } - } - - return tab; - } - - /// Gets the tab by culture. - /// The tab id. - /// The portal id. - /// The locale. - /// tab info. - public TabInfo GetTabByCulture(int tabId, int portalId, Locale locale) - { - TabInfo localizedTab = null; - TabCollection tabs = this.GetTabsByPortal(portalId); - - // Get Tab specified by Id - TabInfo originalTab = tabs.WithTabId(tabId); - - if (locale != null && originalTab != null) - { - // Check if tab is in the requested culture - if (string.IsNullOrEmpty(originalTab.CultureCode) || originalTab.CultureCode == locale.Code) - { - localizedTab = originalTab; - } - else - { - // See if tab exists for culture - if (originalTab.IsDefaultLanguage) - { - originalTab.LocalizedTabs.TryGetValue(locale.Code, out localizedTab); - } - else - { - if (originalTab.DefaultLanguageTab != null) - { - if (originalTab.DefaultLanguageTab.CultureCode == locale.Code) - { - localizedTab = originalTab.DefaultLanguageTab; - } - else - { - if ( - !originalTab.DefaultLanguageTab.LocalizedTabs.TryGetValue( - locale.Code, - out localizedTab)) - { - localizedTab = originalTab.DefaultLanguageTab; - } - } - } - } - } - } - - return localizedTab; - } - - /// Gets the name of the tab by name. - /// Name of the tab. - /// The portal id. - /// tab info. - public TabInfo GetTabByName(string tabName, int portalId) - { - return this.GetTabsByPortal(portalId).WithTabName(tabName); - } - - /// Gets the name of the tab by name and parent id. - /// Name of the tab. - /// The portal id. - /// The parent id. - /// tab info. - public TabInfo GetTabByName(string tabName, int portalId, int parentId) - { - return this.GetTabsByPortal(portalId).WithTabNameAndParentId(tabName, parentId); - } - - /// Gets the tabs which use the module. - /// The module ID. - /// tab collection. - public IDictionary GetTabsByModuleID(int moduleID) - { - return CBO.FillDictionary("TabID", this.dataProvider.GetTabsByModuleID(moduleID)); - } - - /// Gets the tabs which use the module. - /// The tabmodule ID. - /// tab collection. - public IDictionary GetTabsByTabModuleID(int tabModuleId) - { - return CBO.FillDictionary("TabID", this.dataProvider.GetTabsByTabModuleID(tabModuleId)); - } - - /// Gets the tabs which use the package. - /// The portal ID. - /// The package ID. - /// if set to [for host]. - /// tab collection. - public IDictionary GetTabsByPackageID(int portalID, int packageID, bool forHost) - { - return CBO.FillDictionary("TabID", this.dataProvider.GetTabsByPackageID(portalID, packageID, forHost)); - } - - /// Gets the tabs by portal. - /// The portal id. - /// tab collection. - public TabCollection GetTabsByPortal(int portalId) - { - string cacheKey = string.Format(DataCache.TabCacheKey, portalId); - return CBO.GetCachedObject( - new CacheItemArgs( - cacheKey, - DataCache.TabCacheTimeOut, - DataCache.TabCachePriority), - c => - { - List tabs = CBO.FillCollection(this.dataProvider.GetTabs(portalId)); - return new TabCollection(tabs); - }); - } - - /// - public TabCollection GetUserTabsByPortal(int portalId) - { - var tabs = this.GetTabsByPortal(portalId); - var portal = PortalController.Instance.GetPortal(portalId); - - IEnumerable filteredList = from tab in tabs - where - !tab.Value.IsSystem - && tab.Value.TabID != portal.AdminTabId - && tab.Value.ParentId != portal.AdminTabId - select tab.Value; - return new TabCollection(filteredList); - } - - /// read all settings for a tab from TabSettings table. - /// ID of the Tab to query. - /// - /// (cached) hashtable containing all settings. - /// - public Hashtable GetTabSettings(int tabId) - { - var portalId = GetPortalId(tabId, -1); - Hashtable settings; - if (!this.GetTabSettingsByPortal(portalId).TryGetValue(tabId, out settings)) - { - settings = new Hashtable(); - } - - return settings; - } - - /// Get the list of url's associated with a page (tab). - /// the tab id. - /// the portal id. - /// list of urls associated with a tab. - public List GetTabUrls(int tabId, int portalId) - { - // Get the Portal TabUrl Dictionary - Dictionary> dicTabUrls = this.GetTabUrls(portalId); - - // Get the Collection from the Dictionary - List tabRedirects; - bool bFound = dicTabUrls.TryGetValue(tabId, out tabRedirects); - if (!bFound) - { - // Return empty collection - tabRedirects = new List(); - } - - return tabRedirects; - } - - /// Gives the translator role edit rights. - /// The localized tab. - /// The users. - public void GiveTranslatorRoleEditRights(TabInfo localizedTab, Dictionary users) - { - var permissionCtrl = new PermissionController(); - ArrayList permissionsList = permissionCtrl.GetPermissionByCodeAndKey("SYSTEM_TAB", "EDIT"); - - string translatorRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", localizedTab.CultureCode), localizedTab.PortalID, string.Empty); - foreach (string translatorRole in translatorRoles.Split(';')) - { - if (users != null) - { - foreach (UserInfo translator in RoleController.Instance.GetUsersByRole(localizedTab.PortalID, translatorRole)) - { - users[translator.UserID] = translator; - } - } - - if (permissionsList != null && permissionsList.Count > 0) - { - var translatePermisison = (PermissionInfo)permissionsList[0]; - string roleName = translatorRole; - RoleInfo role = RoleController.Instance.GetRole( - localizedTab.PortalID, - r => r.RoleName == roleName); - if (role != null) - { - TabPermissionInfo perm = - localizedTab.TabPermissions.Where( - tp => tp.RoleID == role.RoleID && tp.PermissionKey == "EDIT").SingleOrDefault(); - if (perm == null) - { - // Create Permission - var tabTranslatePermission = new TabPermissionInfo(translatePermisison) - { - RoleID = role.RoleID, - AllowAccess = true, - RoleName = roleName, - }; - localizedTab.TabPermissions.Add(tabTranslatePermission); - this.UpdateTab(localizedTab); - } - } - } - } - } - - /// - public bool HasMissingLanguages(int portalId, int tabId) - { - var currentTab = this.GetTab(tabId, portalId, false); - var workingTab = currentTab; - var locales = LocaleController.Instance.GetLocales(portalId); - var localeCount = locales.Count; - if (currentTab.DefaultLanguageTab != null) - { - workingTab = currentTab.DefaultLanguageTab; - } - - var localizedCount = 1 + - locales.Values.Where(locale => !LocaleController.Instance.IsDefaultLanguage(locale.Code)) - .Count(locale => workingTab.LocalizedTabs.Values.Any(localizedTab => localizedTab.CultureCode == locale.Code)); - - return (localeCount - localizedCount) != 0; - } - - /// Checks whether the tab is published. Published means: view permissions of tab are identical to the DefaultLanguageTab. - /// The tab that is checked. - /// true if tab is published. - public bool IsTabPublished(TabInfo publishTab) - { - bool returnValue = true; - - // To publish a subsidiary language tab we need to enable the View Permissions - if (publishTab != null && publishTab.DefaultLanguageTab != null) - { - foreach (TabPermissionInfo perm in - publishTab.DefaultLanguageTab.TabPermissions.Where(p => p.PermissionKey == "VIEW")) - { - TabPermissionInfo sourcePerm = perm; - TabPermissionInfo targetPerm = - publishTab.TabPermissions.Where( - p => - p.PermissionKey == sourcePerm.PermissionKey && p.RoleID == sourcePerm.RoleID && - p.UserID == sourcePerm.UserID).SingleOrDefault(); - - if (targetPerm == null) - { - returnValue = false; - break; - } - } - } - - return returnValue; - } - - /// Localizes the tab. - /// The original tab. - /// The locale. - public void LocalizeTab(TabInfo originalTab, Locale locale) - { - this.LocalizeTab(originalTab, locale, true); - } - - /// - public void LocalizeTab(TabInfo originalTab, Locale locale, bool clearCache) - { - this.dataProvider.LocalizeTab(originalTab.TabID, locale.Code, UserController.Instance.GetCurrentUserInfo().UserID); - if (clearCache) - { - DataCache.ClearTabsCache(originalTab.PortalID); - DataCache.ClearModuleCache(originalTab.TabID); - } - } - - /// Moves the tab after a specific tab. - /// The tab want to move. - /// will move objTab after this tab. - public void MoveTabAfter(TabInfo tab, int afterTabId) - { - // Get AfterTab - var afterTab = this.GetTab(afterTabId, tab.PortalID, false); - - // Create Tab Redirects - if (afterTab.ParentId != tab.ParentId) - { - this.CreateTabRedirects(tab); - } - - // Move Tab - this.dataProvider.MoveTabAfter(tab.TabID, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); - - // Clear the Cache - this.ClearCache(tab.PortalID); - - var portalId = GetPortalId(tab.TabID, -1); - var updatedTab = this.GetTab(tab.TabID, portalId, true); - EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); - } - - /// Moves the tab before a specific tab. - /// The tab want to move. - /// will move objTab before this tab. - public void MoveTabBefore(TabInfo tab, int beforeTabId) - { - // Get AfterTab - var beforeTab = this.GetTab(beforeTabId, tab.PortalID, false); - - // Create Tab Redirects - if (beforeTab.ParentId != tab.ParentId) - { - this.CreateTabRedirects(tab); - } - - // Move Tab - this.dataProvider.MoveTabBefore(tab.TabID, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID); - - // Clear the Cache - this.ClearCache(tab.PortalID); - - var portalId = GetPortalId(tab.TabID, -1); - var updatedTab = this.GetTab(tab.TabID, portalId, true); - EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); - } - - /// Moves the tab to a new parent. - /// The tab want to move. - /// will move tab to this parent. - public void MoveTabToParent(TabInfo tab, int parentId) - { - // Create Tab Redirects - if (parentId != tab.ParentId) - { - this.CreateTabRedirects(tab); - } - - // Move Tab - this.dataProvider.MoveTabToParent(tab.TabID, parentId, UserController.Instance.GetCurrentUserInfo().UserID); - - // Clear the Cache - this.ClearCache(tab.PortalID); - - var portalId = GetPortalId(tab.TabID, -1); - var updatedTab = this.GetTab(tab.TabID, portalId, true); - EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); - } - - /// Populates the bread crumbs. - /// The tab. - public void PopulateBreadCrumbs(ref TabInfo tab) - { - if (tab.BreadCrumbs == null) - { - var crumbs = new ArrayList(); - this.PopulateBreadCrumbs(tab.PortalID, ref crumbs, tab.TabID); - tab.BreadCrumbs = crumbs; - } - } - - /// Populates the bread crumbs. - /// The portal ID. - /// The bread crumbs. - /// The tab ID. - public void PopulateBreadCrumbs(int portalID, ref ArrayList breadCrumbs, int tabID) - { - // find the tab in the tabs collection - TabInfo tab; - TabCollection portalTabs = this.GetTabsByPortal(portalID); - TabCollection hostTabs = this.GetTabsByPortal(Null.NullInteger); - bool found = portalTabs.TryGetValue(tabID, out tab); - if (!found) - { - found = hostTabs.TryGetValue(tabID, out tab); - } - - // if tab was found - if (found) - { - breadCrumbs.Insert(0, tab.Clone()); - - // get the tab parent - if (!Null.IsNull(tab.ParentId)) - { - this.PopulateBreadCrumbs(portalID, ref breadCrumbs, tab.ParentId); - } - } - } - - /// Publishes the tab. Set the VIEW permission. - /// The publish tab. - public void PublishTab(TabInfo publishTab) - { - // To publish a subsidiary language tab we need to enable the View Permissions - if (publishTab != null && publishTab.DefaultLanguageTab != null) - { - foreach (TabPermissionInfo perm in - publishTab.DefaultLanguageTab.TabPermissions.Where(p => p.PermissionKey == "VIEW")) - { - TabPermissionInfo sourcePerm = perm; - TabPermissionInfo targetPerm = - publishTab.TabPermissions.Where( - p => - p.PermissionKey == sourcePerm.PermissionKey && p.RoleID == sourcePerm.RoleID && - p.UserID == sourcePerm.UserID).SingleOrDefault(); - - if (targetPerm == null) - { - publishTab.TabPermissions.Add(sourcePerm); - } - - TabPermissionController.SaveTabPermissions(publishTab); - } - } - } - - /// Publishes the tabs. - /// The tabs. - public void PublishTabs(List tabs) - { - foreach (TabInfo t in tabs) - { - if (t.IsTranslated) - { - this.PublishTab(t); - } - } - } - - /// Restores the tab. - /// The obj tab. - /// The portal settings. - public void RestoreTab(TabInfo tab, PortalSettings portalSettings) - { - if (tab.DefaultLanguageTab != null) - { - // We are trying to restore the child, so recall this function with the master language's tab id - this.RestoreTab(tab.DefaultLanguageTab, portalSettings); - return; - } - - tab.IsDeleted = false; - this.UpdateTab(tab); - - // Restore any localized children - foreach (TabInfo localizedtab in tab.LocalizedTabs.Values) - { - localizedtab.IsDeleted = false; - this.UpdateTab(localizedtab); - } - - EventLogController.Instance.AddLog(tab, portalSettings, portalSettings.UserId, string.Empty, EventLogController.EventLogType.TAB_RESTORED); - - ArrayList allTabsModules = ModuleController.Instance.GetAllTabsModules(tab.PortalID, true); - var tabModules = ModuleController.Instance.GetTabModules(tab.TabID); - foreach (ModuleInfo objModule in allTabsModules) - { - if (!tabModules.ContainsKey(objModule.ModuleID)) - { - ModuleController.Instance.CopyModule(objModule, tab, Null.NullString, true); - } - } - - this.ClearCache(tab.PortalID); - - EventManager.Instance.OnTabRestored(new TabEventArgs { Tab = tab }); - } - - /// Save url information for a page (tab). - /// the tab url. - /// the portal id. - /// whether to clear the cache. - public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) - { - var portalAliasId = (tabUrl.PortalAliasUsage == PortalAliasUsageType.Default) - ? Null.NullInteger - : tabUrl.PortalAliasId; - - var saveLog = EventLogController.EventLogType.TABURL_CREATED; - - if (tabUrl.HttpStatus == "200") - { - saveLog = EventLogController.EventLogType.TABURL_CREATED; - } - else - { - // need to see if sequence number exists to decide if insert or update - List t = this.GetTabUrls(portalId, tabUrl.TabId); - var existingSeq = t.FirstOrDefault(r => r.SeqNum == tabUrl.SeqNum); - if (existingSeq == null) - { - saveLog = EventLogController.EventLogType.TABURL_CREATED; - } - } - - DataProvider.Instance().SaveTabUrl(tabUrl.TabId, tabUrl.SeqNum, portalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.Instance.GetCurrentUserInfo().UserID); - - EventLogController.Instance.AddLog( - "tabUrl", - tabUrl.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - saveLog); - - if (clearCache) - { - DataCache.RemoveCache(string.Format(DataCache.TabUrlCacheKey, portalId)); - CacheController.ClearCustomAliasesCache(); - this.ClearCache(portalId); - var tab = this.GetTab(tabUrl.TabId, portalId); - tab.ClearTabUrls(); - } - } - - /// - public bool SoftDeleteTab(int tabId, PortalSettings portalSettings) - { - bool deleted; - TabInfo tab = this.GetTab(tabId, portalSettings.PortalId, false); - if (tab != null) - { - if (tab.DefaultLanguageTab != null && LocaleController.Instance.GetLocales(portalSettings.PortalId).ContainsKey(tab.CultureCode)) - { - // We are trying to delete the child, so recall this function with the master language's tab id - return this.SoftDeleteTab(tab.DefaultLanguageTab.TabID, portalSettings); - } - - // Delete the Tab - deleted = this.SoftDeleteTabInternal(tab, portalSettings); - - // Delete any localized children - if (deleted) - { - foreach (TabInfo localizedtab in tab.LocalizedTabs.Values) - { - this.SoftDeleteTabInternal(localizedtab, portalSettings); - } - } - } - else - { - deleted = false; - } - - return deleted; - } - - /// Updates the tab to database. - /// The updated tab. - public void UpdateTab(TabInfo updatedTab) - { - TabInfo originalTab = this.GetTab(updatedTab.TabID, updatedTab.PortalID, true); - - // Update ContentItem If neccessary - if (updatedTab.TabID != Null.NullInteger) - { - if (updatedTab.ContentItemId == Null.NullInteger) - { - this.CreateContentItem(updatedTab); - } - else - { - UpdateContentItem(updatedTab); - } - } - - // Create Tab Redirects - if (originalTab.ParentId != updatedTab.ParentId || originalTab.TabName != updatedTab.TabName) - { - this.CreateTabRedirects(updatedTab); - } - - // Update Tab to DataStore - this.dataProvider.UpdateTab( - updatedTab.TabID, - updatedTab.ContentItemId, - updatedTab.PortalID, - updatedTab.VersionGuid, - updatedTab.DefaultLanguageGuid, - updatedTab.LocalizedVersionGuid, - updatedTab.TabName, - updatedTab.IsVisible, - updatedTab.DisableLink, - updatedTab.ParentId, - updatedTab.IconFileRaw, - updatedTab.IconFileLargeRaw, - updatedTab.Title, - updatedTab.Description, - updatedTab.KeyWords, - updatedTab.IsDeleted, - updatedTab.Url, - updatedTab.SkinSrc, - updatedTab.ContainerSrc, - updatedTab.StartDate, - updatedTab.EndDate, - updatedTab.RefreshInterval, - updatedTab.PageHeadText, - updatedTab.IsSecure, - updatedTab.PermanentRedirect, - updatedTab.SiteMapPriority, - UserController.Instance.GetCurrentUserInfo().UserID, - updatedTab.CultureCode, - updatedTab.IsSystem); - - // Update Tags - List terms = updatedTab.Terms; - ITermController termController = Util.GetTermController(); - termController.RemoveTermsFromContent(updatedTab); - foreach (Term term in terms) - { - termController.AddTermToContent(term, updatedTab); - } - - EventLogController.Instance.AddLog( - updatedTab, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - string.Empty, - EventLogController.EventLogType.TAB_UPDATED); - - // Update Tab permissions - TabPermissionController.SaveTabPermissions(updatedTab); - - // Update TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist - try - { - this.UpdateTabSettings(ref updatedTab); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - - // Update Tab Version - UpdateTabVersion(updatedTab.TabID); - - // Clear Tab Caches - this.ClearCache(updatedTab.PortalID); - if (updatedTab.PortalID != originalTab.PortalID) - { - this.ClearCache(originalTab.PortalID); - } - - EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); - } - - /// Adds or updates a tab's setting value. - /// ID of the tab to update. - /// name of the setting property. - /// value of the setting (String). - /// empty SettingValue will remove the setting, if not preserveIfEmpty is true. - public void UpdateTabSetting(int tabId, string settingName, string settingValue) - { - this.UpdateTabSettingInternal(tabId, settingName, settingValue, true); - } - - /// Updates the translation status. - /// The localized tab. - /// if set to means the tab has already been translated. - public void UpdateTranslationStatus(TabInfo localizedTab, bool isTranslated) - { - if (isTranslated && (localizedTab.DefaultLanguageTab != null)) - { - localizedTab.LocalizedVersionGuid = localizedTab.DefaultLanguageTab.LocalizedVersionGuid; - } - else - { - localizedTab.LocalizedVersionGuid = Guid.NewGuid(); - } - - DataProvider.Instance() - .UpdateTabTranslationStatus( - localizedTab.TabID, - localizedTab.LocalizedVersionGuid, - UserController.Instance.GetCurrentUserInfo().UserID); - - // Clear Tab Caches - this.ClearCache(localizedTab.PortalID); - } - - /// It marks a page as published at least once. - /// The Tab to be marked. - public void MarkAsPublished(TabInfo tab) - { - this.dataProvider.MarkAsPublished(tab.TabID); - - // Clear Tab Caches - this.ClearCache(tab.PortalID); - - EventManager.Instance.OnTabMarkedAsPublished(new TabEventArgs { Tab = tab }); - } - - /// - public bool IsHostOrAdminPage(TabInfo tab) - { - return IsHostTab(tab) || this.IsAdminTab(tab); - } - - internal Dictionary> GetTabUrls(int portalId) - { - string cacheKey = string.Format(DataCache.TabUrlCacheKey, portalId); - return CBO.GetCachedObject>>( - new CacheItemArgs( - cacheKey, - DataCache.TabUrlCacheTimeOut, - DataCache.TabUrlCachePriority, - portalId), - this.GetTabUrlsCallback); - } - - /// - protected override Func GetFactory() - { - return () => new TabController(); - } - - private static void AddAllTabsModules(TabInfo tab) - { - var portalSettings = new PortalSettings(tab.TabID, tab.PortalID); - foreach (ModuleInfo allTabsModule in ModuleController.Instance.GetAllTabsModules(tab.PortalID, true)) - { - // [DNN-6276]We need to check that the Module is not implicitly deleted. ie If all instances are on Pages - // that are all "deleted" then even if the Module itself is not deleted, we would not expect the - // Module to be added - var canAdd = - (from ModuleInfo allTabsInstance in ModuleController.Instance.GetTabModulesByModule(allTabsModule.ModuleID) select Instance.GetTab(allTabsInstance.TabID, tab.PortalID, false)).Any( - t => !t.IsDeleted) && (!portalSettings.ContentLocalizationEnabled || allTabsModule.CultureCode == tab.CultureCode); - if (canAdd) - { - ModuleController.Instance.CopyModule(allTabsModule, tab, Null.NullString, true); - } - } - } - - private static void DeserializeTabSettings(XmlNodeList nodeTabSettings, TabInfo objTab) - { - foreach (XmlNode oTabSettingNode in nodeTabSettings) - { - string sKey = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingname"); - string sValue = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingvalue"); - objTab.TabSettings[sKey] = sValue; - } - } - - private static void DeserializeTabPermissions(XmlNodeList nodeTabPermissions, TabInfo tab, bool isAdminTemplate) - { - var permissionController = new PermissionController(); - int permissionID = 0; - foreach (XmlNode tabPermissionNode in nodeTabPermissions) - { - string permissionKey = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "permissionkey"); - string permissionCode = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "permissioncode"); - string roleName = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "rolename"); - bool allowAccess = XmlUtils.GetNodeValueBoolean(tabPermissionNode, "allowaccess"); - ArrayList arrPermissions = permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey); - int i; - for (i = 0; i <= arrPermissions.Count - 1; i++) - { - var permission = (PermissionInfo)arrPermissions[i]; - permissionID = permission.PermissionID; - } - - int roleID = int.MinValue; - switch (roleName) - { - case Globals.glbRoleAllUsersName: - roleID = Convert.ToInt32(Globals.glbRoleAllUsers); - break; - case Globals.glbRoleUnauthUserName: - roleID = Convert.ToInt32(Globals.glbRoleUnauthUser); - break; - default: - var portal = PortalController.Instance.GetPortal(tab.PortalID); - var role = RoleController.Instance.GetRole( - portal.PortalID, - r => r.RoleName == roleName); - if (role != null) - { - roleID = role.RoleID; - } - else - { - if (isAdminTemplate && roleName.Equals("Administrators", StringComparison.OrdinalIgnoreCase)) - { - roleID = portal.AdministratorRoleId; - } - } - - break; - } - - if (roleID != int.MinValue) - { - var tabPermission = new TabPermissionInfo - { - TabID = tab.TabID, - PermissionID = permissionID, - RoleID = roleID, - UserID = Null.NullInteger, - AllowAccess = allowAccess, - }; - - bool canAdd = !tab.TabPermissions.Cast() - .Any(tp => tp.TabID == tabPermission.TabID - && tp.PermissionID == tabPermission.PermissionID - && tp.RoleID == tabPermission.RoleID - && tp.UserID == tabPermission.UserID); - if (canAdd) - { - tab.TabPermissions.Add(tabPermission); - } - } - } - } - - private static void DeserializeTabUrls(XmlNode nodeTabUrl, TabUrlInfo objTabUrl) - { - objTabUrl.SeqNum = XmlUtils.GetAttributeValueAsInteger(nodeTabUrl.CreateNavigator(), "SeqNum", 0); - objTabUrl.Url = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url")) ? "/" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url"); - objTabUrl.QueryString = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "QueryString"); - objTabUrl.CultureCode = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "CultureCode"); - objTabUrl.HttpStatus = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus")) ? "200" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus"); - objTabUrl.IsSystem = XmlUtils.GetAttributeValueAsBoolean(nodeTabUrl.CreateNavigator(), "IsSystem", true); - objTabUrl.PortalAliasId = Null.NullInteger; - objTabUrl.PortalAliasUsage = PortalAliasUsageType.Default; - } - - private static int GetIndexOfTab(TabInfo objTab, IEnumerable tabs) - { - return Null.NullInteger + tabs.TakeWhile(tab => tab.TabID != objTab.TabID).Count(); - } - - private static int GetPortalId(int tabId, int portalId) - { - if (Null.IsNull(portalId)) - { - var portalDic = PortalController.GetPortalDictionary(); - if (portalDic != null && portalDic.TryGetValue(tabId, out var pid)) - { - portalId = pid; - } - } - - return portalId; - } - - private static object GetTabPathDictionaryCallback(CacheItemArgs cacheItemArgs) - { - string cultureCode = Convert.ToString(cacheItemArgs.ParamList[0]); - var portalId = (int)cacheItemArgs.ParamList[1]; - var tabPathDictionary = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - IDataReader dr = DataProvider.Instance().GetTabPaths(portalId, cultureCode); - try - { - while (dr.Read()) - { - tabPathDictionary[Null.SetNullString(dr["TabPath"])] = Null.SetNullInteger(dr["TabID"]); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return tabPathDictionary; - } - - private static void UpdateTabVersion(int tabId) - { - DataProvider.Instance().UpdateTabVersion(tabId, Guid.NewGuid()); - } - - private static void ValidateTabPath(TabInfo tab) - { - string tabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); - int tabId = GetTabByTabPath(tab.PortalID, tabPath, tab.CultureCode); - if (tabId > Null.NullInteger) - { - // Tab exists so Throw - throw new TabExistsException( - tabId, - $"Page Exists in portal: {tab.PortalID}, path: {tab.TabPath}, culture: {tab.CultureCode}"); - } - } - - private static void EnableTabVersioningAndWorkflow(TabInfo tab) - { - if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) - { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, true); - } - - if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) - { - TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, true); - } - } - - private static void DisableTabVersioningAndWorkflow(TabInfo tab) - { - if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) - { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); - } - - if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) - { - TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); - } - } - - private static bool IsHostTab(TabInfo tab) - { - return tab.PortalID == Null.NullInteger; - } - - /// update content item for the tab when tab name changed. - /// The updated tab. - private static void UpdateContentItem(TabInfo tab) - { - IContentController contentController = Util.GetContentController(); - var newContent = string.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; - if (tab.Content != newContent) - { - tab.Content = newContent; - contentController.UpdateContentItem(tab); - } - } - - /// - /// Checks if the page is root or has a localized parent. - /// If neither is true, then we cannot create localized version of the page for the given locale. - /// - /// The tab to be checked. - /// The locale to be checked. - /// Whether the tab can be localized to the locale. - private bool CanLocalizeTabToLocale(TabInfo tab, Locale locale) - { - // If root page, can be localized - if (Null.IsNull(tab.ParentId)) - { - return true; - } - - // Otherwise can be localized only if localized parent is found - TabInfo parent = this.GetTab(tab.ParentId, tab.PortalID, false); - TabInfo localizedParent = this.GetTabByCulture(parent.TabID, parent.PortalID, locale); - return localizedParent != null; - } - - private bool IsAdminTab(TabInfo tab) - { - var portal = PortalController.Instance.GetPortal(tab.PortalID); - return portal.AdminTabId == tab.TabID || this.IsAdminTabRecursive(tab, portal.AdminTabId); - } - - private bool IsAdminTabRecursive(TabInfo tab, int adminTabId) - { - if (tab.ParentId == Null.NullInteger) - { - return false; - } - - if (tab.ParentId == adminTabId) - { - return true; - } - - var parentTab = this.GetTab(tab.ParentId, tab.PortalID); - return this.IsAdminTabRecursive(parentTab, adminTabId); - } - - private int AddTabInternal(TabInfo tab, int afterTabId, int beforeTabId, bool includeAllTabsModules) - { - ValidateTabPath(tab); - - // First create ContentItem as we need the ContentItemID - this.CreateContentItem(tab); - - // Add Tab - if (afterTabId > 0) - { - tab.TabID = this.dataProvider.AddTabAfter(tab, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); - } - else - { - tab.TabID = beforeTabId > 0 - ? this.dataProvider.AddTabBefore(tab, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID) - : this.dataProvider.AddTabToEnd(tab, UserController.Instance.GetCurrentUserInfo().UserID); - } - - // Clear the Cache - this.ClearCache(tab.PortalID); - - ITermController termController = Util.GetTermController(); - termController.RemoveTermsFromContent(tab); - foreach (Term term in tab.Terms) - { - termController.AddTermToContent(term, tab); - } - - EventLogController.Instance.AddLog( - tab, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - string.Empty, - EventLogController.EventLogType.TAB_CREATED); - - // Add Tab Permissions - TabPermissionController.SaveTabPermissions(tab); - - // Add TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist - try - { - this.UpdateTabSettings(ref tab); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - - // Add AllTabs Modules - if (includeAllTabsModules && tab.PortalID != Null.NullInteger) - { - AddAllTabsModules(tab); - } - - // Check Tab Versioning - if (tab.PortalID == Null.NullInteger || !TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID, tab.TabID)) - { - this.MarkAsPublished(tab); - } - - EventManager.Instance.OnTabCreated(new TabEventArgs { Tab = tab }); - - return tab.TabID; - } - - private void CreateLocalizedCopyInternal(TabInfo originalTab, Locale locale, bool allTabsModulesFromDefault, bool clearCache, bool insertAfterOriginal = false) - { - try - { - Logger.TraceFormat("Localizing TabId: {0}, TabPath: {1}, Locale: {2}", originalTab.TabID, originalTab.TabPath, locale.Code); - var defaultLocale = LocaleController.Instance.GetDefaultLocale(originalTab.PortalID); - - // First Clone the Tab - TabInfo localizedCopy = originalTab.Clone(); - localizedCopy.TabID = Null.NullInteger; - localizedCopy.StateID = Null.NullInteger; - localizedCopy.ContentItemId = Null.NullInteger; - - // Set Guids and Culture Code - localizedCopy.UniqueId = Guid.NewGuid(); - localizedCopy.VersionGuid = Guid.NewGuid(); - localizedCopy.LocalizedVersionGuid = Guid.NewGuid(); - localizedCopy.CultureCode = locale.Code; - localizedCopy.TabName = localizedCopy.TabName + " (" + locale.Code + ")"; - - // copy page tags - foreach (var term in originalTab.Terms) - { - localizedCopy.Terms.Add(term); - } - - if (locale == defaultLocale) - { - originalTab.DefaultLanguageGuid = localizedCopy.UniqueId; - this.UpdateTab(originalTab); - } - else - { - localizedCopy.DefaultLanguageGuid = originalTab.UniqueId; - } - - // Copy Permissions from original Tab for Admins only - // If original tab is user tab or its parent tab is user tab, then copy full permission - // from original tab. - PortalInfo portal = PortalController.Instance.GetPortal(originalTab.PortalID); - if (originalTab.TabID == portal.UserTabId || originalTab.ParentId == portal.UserTabId) - { - localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions); - } - else - { - localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions.Where(p => p.RoleID == portal.AdministratorRoleId)); - } - - // Get the original Tabs Parent - // check the original whether have parent. - if (!Null.IsNull(originalTab.ParentId)) - { - TabInfo originalParent = this.GetTab(originalTab.ParentId, originalTab.PortalID, false); - - // Get the localized parent - TabInfo localizedParent = this.GetTabByCulture(originalParent.TabID, originalParent.PortalID, locale); - localizedCopy.ParentId = localizedParent.TabID; - } - - // Save Tab - var afterTabId = insertAfterOriginal ? originalTab.TabID : -1; - const int beforeTabId = -1; - const bool includeAllModules = false; - this.AddTabInternal(localizedCopy, afterTabId, beforeTabId, includeAllModules); // not include modules show on all page, it will handled in copy modules action. - - // if the tab has custom stylesheet defined, then also copy the stylesheet to the localized version. - if (originalTab.TabSettings.ContainsKey("CustomStylesheet")) - { - this.UpdateTabSetting(localizedCopy.TabID, "CustomStylesheet", originalTab.TabSettings["CustomStylesheet"].ToString()); - } - - /* Tab versioning and workflow is disabled - * during the creation of the Localized copy - */ - DisableTabVersioningAndWorkflow(localizedCopy); - - // Make shallow copies of all modules - ModuleController.Instance.CopyModules(originalTab, localizedCopy, true, allTabsModulesFromDefault); - - // Convert these shallow copies to deep copies - foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(localizedCopy.TabID)) - { - ModuleController.Instance.LocalizeModule(kvp.Value, locale); - } - - // if not copy modules which show on all pages from default language, we need add all modules in current culture. - if (!allTabsModulesFromDefault) - { - AddAllTabsModules(localizedCopy); - } - - // Add Translator Role - this.GiveTranslatorRoleEditRights(localizedCopy, null); - - /* Tab versioning and workflow is re-enabled - * when the Localized copy is created - */ - EnableTabVersioningAndWorkflow(localizedCopy); - this.MarkAsPublished(localizedCopy); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - throw; - } - - // Clear the Cache - if (clearCache) - { - this.ClearCache(originalTab.PortalID); - } - } - - /// If a parent tab is localized, its localized children need to be updated to point at their corresponding localized parents. - /// The portal ID. - /// The parent tab ID. - private void UpdateChildTabLocalizedParents(int portalId, int parentTabId) - { - var childTabs = GetTabsByParent(parentTabId, portalId); - - foreach (var childTab in childTabs) - { - if (childTab.CultureCode == null) - { - continue; - } - - var locale = LocaleController.Instance.GetLocale(portalId, childTab.CultureCode); - - if (locale == null) - { - continue; - } - - TabInfo localizedParent = this.GetTabByCulture(parentTabId, portalId, locale); - if (childTab.ParentId != localizedParent.TabID) - { - childTab.ParentId = localizedParent.TabID; - - this.UpdateTab(childTab); - - this.UpdateChildTabLocalizedParents(portalId, childTab.TabID); - } - } - } - - private void ClearTabSettingsCache(int tabId) - { - var portalId = GetPortalId(tabId, -1); - string cacheKey = string.Format(DataCache.TabSettingsCacheKey, portalId); - DataCache.RemoveCache(cacheKey); - - // also clear the settings from tab object in cache. - var tab = this.GetTab(tabId, portalId, false); - tab?.ClearSettingsCache(); - } - - private void CreateTabRedirect(TabInfo tab) - { - var settings = PortalController.Instance.GetCurrentPortalSettings(); - - if (settings != null && tab.TabID != settings.HomeTabId && tab.TabUrls.All(u => u.HttpStatus != "200")) - { - var domainRoot = TestableGlobals.Instance.AddHTTP(settings.PortalAlias.HTTPAlias); - - if (!string.IsNullOrEmpty(domainRoot)) - { - var url = TestableGlobals.Instance.NavigateURL(tab.TabID); - - url = url.Replace(domainRoot, string.Empty); - - var seqNum = (tab.TabUrls.Count > 0) ? tab.TabUrls.Max(t => t.SeqNum) + 1 : 1; - var tabUrl = new TabUrlInfo - { - TabId = tab.TabID, - SeqNum = seqNum, - PortalAliasId = -1, - PortalAliasUsage = PortalAliasUsageType.Default, - Url = url, - QueryString = string.Empty, - CultureCode = tab.CultureCode, - HttpStatus = "301", - IsSystem = true, - }; - - this.SaveTabUrl(tabUrl, tab.PortalID, false); - } - } - } - - private void CreateTabRedirects(TabInfo tab) - { - this.CreateTabRedirect(tab); - - var descendants = this.GetTabsByPortal(tab.PortalID).DescendentsOf(tab.TabID); - - // Create Redirect for descendant tabs - foreach (TabInfo descendantTab in descendants) - { - this.CreateTabRedirect(descendantTab); - } - } - - private Dictionary> GetAliasSkins(int portalId) - { - string cacheKey = string.Format(DataCache.TabAliasSkinCacheKey, portalId); - return CBO.GetCachedObject>>( - new CacheItemArgs( - cacheKey, - DataCache.TabAliasSkinCacheTimeOut, - DataCache.TabAliasSkinCachePriority, - portalId), - this.GetAliasSkinsCallback); - } - - private object GetAliasSkinsCallback(CacheItemArgs cacheItemArgs) - { - var portalId = (int)cacheItemArgs.ParamList[0]; - var dic = new Dictionary>(); - if (portalId > -1) - { - IDataReader dr = DataProvider.Instance().GetTabAliasSkins(portalId); - try - { - while (dr.Read()) - { - // fill business object - var tabAliasSkin = CBO.FillObject(dr, false); - - // add Tab Alias Skin to dictionary - if (dic.TryGetValue(tabAliasSkin.TabId, out var tabAliasSkins)) +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Entities.Tabs +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Data; + using System.Globalization; + using System.Linq; + using System.Text.RegularExpressions; + using System.Web; + using System.Xml; + + using DotNetNuke.Abstractions.Logging; + using DotNetNuke.Abstractions.Modules; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Abstractions.Security.Permissions; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Content; + using DotNetNuke.Entities.Content.Common; + using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs.Actions; + using DotNetNuke.Entities.Tabs.TabVersions; + using DotNetNuke.Entities.Urls; + using DotNetNuke.Entities.Users; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Security.Permissions; + using DotNetNuke.Security.Roles; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Search.Entities; + + using Microsoft.Extensions.DependencyInjection; + + /// TabController provides all operation to . + /// + /// Tab is equal to page in DotNetNuke. + /// Tabs will be a sitemap for a portal, and every request at first need to check whether there is valid tab information + /// include in the url, if not it will use default tab to display information. + /// + public partial class TabController : ServiceLocator, ITabController + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabController)); + private static readonly Regex TabNameCheck1 = new Regex("^LPT[1-9]$|^COM[1-9]$", RegexOptions.IgnoreCase); + private static readonly Regex TabNameCheck2 = new Regex("^AUX$|^CON$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$|^LOGIN$|^REGISTER$", RegexOptions.IgnoreCase); + + private readonly DataProvider dataProvider = DataProvider.Instance(); + + /// Gets the current page in current http request. + /// Current Page Info. + public static TabInfo CurrentPage => PortalSettings.Current?.ActiveTab; + + /// Copies the design to children. + /// The parent tab. + /// The skin SRC. + /// The container SRC. + public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc) + { + CopyDesignToChildren(parentTab, skinSrc, containerSrc, PortalController.GetActivePortalLanguage(parentTab.PortalID)); + } + + /// Copies the design to children. + /// The parent tab. + /// The skin SRC. + /// The container SRC. + /// The culture code. + public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc, string cultureCode) + { + bool clearCache = Null.NullBoolean; + List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); + foreach (TabInfo tab in childTabs) + { + if (TabPermissionController.CanAdminPage(tab)) + { + // Update ContentItem If necessary + if (tab.ContentItemId == Null.NullInteger && tab.TabID != Null.NullInteger) + { + Instance.CreateContentItem(tab); + } + + DataProvider.Instance().UpdateTab( + tab.TabID, + tab.ContentItemId, + tab.PortalID, + tab.VersionGuid, + tab.DefaultLanguageGuid, + tab.LocalizedVersionGuid, + tab.TabName, + tab.IsVisible, + tab.DisableLink, + tab.ParentId, + tab.IconFileRaw, + tab.IconFileLargeRaw, + tab.Title, + tab.Description, + tab.KeyWords, + tab.IsDeleted, + tab.Url, + skinSrc, + containerSrc, + tab.StartDate, + tab.EndDate, + tab.RefreshInterval, + tab.PageHeadText, + tab.IsSecure, + tab.PermanentRedirect, + tab.SiteMapPriority, + UserController.Instance.GetCurrentUserInfo().UserID, + tab.CultureCode, + tab.IsSystem); + + UpdateTabVersion(tab.TabID); + + EventLogController.Instance.AddLog( + tab, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + EventLogController.EventLogType.TAB_UPDATED); + clearCache = true; + } + } + + if (clearCache) + { + DataCache.ClearTabsCache(childTabs[0].PortalID); + } + } + + /// Copies the permissions to children. + /// The parent tab. + /// The new permissions. + public static void CopyPermissionsToChildren(TabInfo parentTab, TabPermissionCollection newPermissions) + { + bool clearCache = Null.NullBoolean; + List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); + foreach (TabInfo tab in childTabs) + { + if (TabPermissionController.CanAdminPage(tab)) + { + tab.TabPermissions.Clear(); + tab.TabPermissions.AddRange(newPermissions); + TabPermissionController.SaveTabPermissions(tab); + UpdateTabVersion(tab.TabID); + clearCache = true; + } + } + + if (clearCache) + { + DataCache.ClearTabsCache(childTabs[0].PortalID); + } + } + + /// Processes all panes and modules in the template file. + /// The business controller provider. + /// Template file node for the panes is current tab. + /// PortalId of the new portal. + /// Tab being processed. + /// Tabs need to merge. + /// Modules Hashtable. + public static void DeserializePanes(IBusinessControllerProvider businessControllerProvider, XmlNode nodePanes, int portalId, int tabId, PortalTemplateModuleAction mergeTabs, Hashtable hModules) + { + Dictionary dicModules = ModuleController.Instance.GetTabModules(tabId); + + // If Mode is Replace remove all the modules already on this Tab + if (mergeTabs == PortalTemplateModuleAction.Replace) + { + foreach (KeyValuePair kvp in dicModules) + { + var module = kvp.Value; + + // when the modules show on all pages are included by the same import process, it need removed. + if (!module.AllTabs || hModules.ContainsValue(module.ModuleID)) + { + ModuleController.Instance.DeleteTabModule(tabId, kvp.Value.ModuleID, false); + } + } + } + + // iterate through the panes + foreach (XmlNode nodePane in nodePanes.ChildNodes) + { + // iterate through the modules + if (nodePane.SelectSingleNode("modules") != null) + { + XmlNode selectSingleNode = nodePane.SelectSingleNode("modules"); + if (selectSingleNode != null) + { + foreach (XmlNode nodeModule in selectSingleNode) { - tabAliasSkins.Add(tabAliasSkin); - } - else - { - // Create new Tab Alias Skin Collection for TabId - var collection = new List { tabAliasSkin, }; - - // Add Collection to Dictionary - dic.Add(tabAliasSkin.TabId, collection); - } - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); - } - } - - return dic; - } - - private Dictionary> GetCustomAliases(int portalId) - { - string cacheKey = string.Format(DataCache.TabCustomAliasCacheKey, portalId); - return CBO.GetCachedObject>>( - new CacheItemArgs( - cacheKey, - DataCache.TabCustomAliasCacheTimeOut, - DataCache.TabCustomAliasCachePriority, - portalId), - this.GetCustomAliasesCallback); - } - - private object GetCustomAliasesCallback(CacheItemArgs cacheItemArgs) - { - var portalID = (int)cacheItemArgs.ParamList[0]; - var dic = new Dictionary>(); - if (portalID > -1) - { - IDataReader dr = DataProvider.Instance().GetTabCustomAliases(portalID); - try - { - while (dr.Read()) - { - // fill business object - var tabId = (int)dr["TabId"]; - var customAlias = (string)dr["httpAlias"]; - var cultureCode = (string)dr["cultureCode"]; - - // add Custom Alias to dictionary - if (dic.TryGetValue(tabId, out var aliases)) + ModuleController.DeserializeModule(businessControllerProvider, nodeModule, nodePane, portalId, tabId, mergeTabs, hModules); + } + } + } + } + + // if deserialize tab from install wizard, we need parse deserialize handlers first. + var installFromWizard = HttpContext.Current != null && HttpContext.Current.Items.Contains("InstallFromWizard"); + if (installFromWizard) + { + HttpContext.Current.Items.Remove("InstallFromWizard"); + EventManager.Instance.RefreshTabSyncHandlers(); + } + + EventManager.Instance.OnTabDeserialize(new TabSyncEventArgs { Tab = Instance.GetTab(tabId, portalId), TabNode = nodePanes.ParentNode }); + } + + /// Deserializes the tab. + /// The business controller provider. + /// The node tab. + /// The obj tab. + /// The portal id. + /// The merge tabs. + /// The deserialized instance. + public static TabInfo DeserializeTab(IBusinessControllerProvider businessControllerProvider, XmlNode tabNode, TabInfo tab, int portalId, PortalTemplateModuleAction mergeTabs) + { + return DeserializeTab(businessControllerProvider, tabNode, tab, new Hashtable(), portalId, false, mergeTabs, new Hashtable()); + } + + /// Deserializes the tab. + /// The business controller provider. + /// The node tab. + /// The obj tab. + /// The h tabs. + /// The portal id. + /// if set to [is admin template]. + /// The merge tabs. + /// The h modules. + /// The deserialized instance. + public static TabInfo DeserializeTab(IBusinessControllerProvider businessControllerProvider, XmlNode tabNode, TabInfo tab, Hashtable tabs, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, Hashtable modules) + { + string tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "name"); + if (!string.IsNullOrEmpty(tabName)) + { + if (tab == null) + { + tab = new TabInfo { TabID = Null.NullInteger, ParentId = Null.NullInteger, TabName = tabName }; + } + + tab.PortalID = portalId; + if (string.IsNullOrEmpty(tab.Title)) + { + tab.Title = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "title"); + } + + if (string.IsNullOrEmpty(tab.Description)) + { + tab.Description = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "description"); + } + + tab.KeyWords = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "keywords"); + tab.IsVisible = XmlUtils.GetNodeValueBoolean(tabNode, "visible", true); + tab.DisableLink = XmlUtils.GetNodeValueBoolean(tabNode, "disabled"); + tab.IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfile")); + tab.IconFileLarge = Globals.ImportFile( + portalId, + XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfilelarge")); + tab.Url = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "url"); + tab.StartDate = XmlUtils.GetNodeValueDate(tabNode, "startdate", Null.NullDate); + tab.EndDate = XmlUtils.GetNodeValueDate(tabNode, "enddate", Null.NullDate); + tab.RefreshInterval = XmlUtils.GetNodeValueInt(tabNode, "refreshinterval", Null.NullInteger); + tab.PageHeadText = XmlUtils.GetNodeValue(tabNode, "pageheadtext", Null.NullString); + tab.IsSecure = XmlUtils.GetNodeValueBoolean(tabNode, "issecure", false); + tab.SiteMapPriority = XmlUtils.GetNodeValueSingle(tabNode, "sitemappriority", 0.5F); + tab.CultureCode = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "cultureCode"); + + // objTab.UniqueId = New Guid(XmlUtils.GetNodeValue(nodeTab, "guid", Guid.NewGuid.ToString())); + // objTab.VersionGuid = New Guid(XmlUtils.GetNodeValue(nodeTab, "versionGuid", Guid.NewGuid.ToString())); + tab.UseBaseFriendlyUrls = XmlUtils.GetNodeValueBoolean(tabNode, "UseBaseFriendlyUrls", false); + + tab.TabPermissions.Clear(); + DeserializeTabPermissions(tabNode.SelectNodes("tabpermissions/permission"), tab, isAdminTemplate); + + DeserializeTabSettings(tabNode.SelectNodes("tabsettings/tabsetting"), tab); + + // set tab skin and container + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty))) + { + tab.SkinSrc = XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty))) + { + tab.ContainerSrc = XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty); + } + + tabName = tab.TabName; + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"))) + { + if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")] != null) + { + // parent node specifies the path (tab1/tab2/tab3), use saved tabid + tab.ParentId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")], CultureInfo.InvariantCulture); + tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent") + "/" + tab.TabName; + } + else + { + // Parent node doesn't specify the path, search by name. + // Possible incoherence if tabname not unique + TabInfo objParent = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"), portalId); + if (objParent != null) { - aliases[cultureCode] = customAlias; - } - else - { - // Create new Custom Alias Collection for TabId - var collection = new Dictionary { { cultureCode, customAlias } }; - - // Add Collection to Dictionary - dic.Add(tabId, collection); - } - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); - } - } - - return dic; - } - - private List GetSiblingTabs(TabInfo objTab) - { - return this.GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, true).WithParentId(objTab.ParentId); - } - - private Dictionary GetTabSettingsByPortal(int portalId) - { - string cacheKey = string.Format(DataCache.TabSettingsCacheKey, portalId); - return CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - DataCache.TabCacheTimeOut, - DataCache.TabCachePriority), - c => - { - var tabSettings = new Dictionary(); - using (var dr = this.dataProvider.GetTabSettings(portalId)) - { - while (dr.Read()) - { - int tabId = dr.GetInt32(0); - Hashtable settings; - if (!tabSettings.TryGetValue(tabId, out settings)) - { - settings = new Hashtable(); - tabSettings[tabId] = settings; - } - - if (!dr.IsDBNull(2)) - { - settings[dr.GetString(1)] = dr.GetString(2); - } - else - { - settings[dr.GetString(1)] = string.Empty; - } - } - } - - return tabSettings; - }); - } - - private object GetTabUrlsCallback(CacheItemArgs cacheItemArgs) - { - var portalId = (int)cacheItemArgs.ParamList[0]; - var dic = new Dictionary>(); - - if (portalId > -1) - { - IDataReader dr = DataProvider.Instance().GetTabUrls(portalId); - try - { - while (dr.Read()) - { - // fill business object - var tabRedirect = CBO.FillObject(dr, false); - - // add Tab Redirect to dictionary - if (dic.TryGetValue(tabRedirect.TabId, out var tabUrls)) + tab.ParentId = objParent.TabID; + tabName = objParent.TabName + "/" + tab.TabName; + } + else { - tabUrls.Add(tabRedirect); - } - else - { - // Create new Tab Redirect Collection for TabId - var collection = new List { tabRedirect, }; - - // Add Collection to Dictionary - dic.Add(tabRedirect.TabId, collection); - } - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); - } - } - - return dic; - } - - private void HardDeleteTabInternal(int tabId, int portalId) - { - // Delete all tabModule Instances - foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabId).Values) - { - ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, false); - } - - var tab = this.GetTab(tabId, portalId, false); - - // Delete Tab - this.dataProvider.DeleteTab(tabId); - - // Log deletion - EventLogController.Instance.AddLog( - "TabID", - tabId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.TAB_DELETED); - - // queue remove tab/page from search index - var document = new SearchDocumentToDelete - { - TabId = tabId, - }; - - DataProvider.Instance().AddSearchDeletedItems(document); - - // Remove the Content Item - if (tab != null && tab.ContentItemId > Null.NullInteger) - { - IContentController contentController = Util.GetContentController(); - contentController.DeleteContentItem(tab); - } - - if (tab != null) - { - EventManager.Instance.OnTabDeleted(new TabEventArgs { Tab = tab }); - } - } - - private bool SoftDeleteChildTabs(int intTabid, PortalSettings portalSettings) - { - bool bDeleted = true; - foreach (TabInfo objtab in GetTabsByParent(intTabid, portalSettings.PortalId)) - { - bDeleted = this.SoftDeleteTabInternal(objtab, portalSettings); - if (!bDeleted) - { - break; - } - } - - return bDeleted; - } - - private bool SoftDeleteTabInternal(TabInfo tabToDelete, PortalSettings portalSettings) - { - Dto.ChangeControlState changeControlStateForTab = null; - if (tabToDelete.PortalID > -1) - { - changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState( - tabToDelete.PortalID, - tabToDelete.TabID); - if (changeControlStateForTab.IsChangeControlEnabledForTab) - { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tabToDelete.TabID, false); - TabWorkflowSettings.Instance.SetWorkflowEnabled(tabToDelete.PortalID, tabToDelete.TabID, false); - } - } - - var deleted = false; - if (!IsSpecialTab(tabToDelete.TabID, portalSettings)) - { - if (this.SoftDeleteChildTabs(tabToDelete.TabID, portalSettings)) - { - tabToDelete.IsDeleted = true; - this.UpdateTab(tabToDelete); - - foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabToDelete.TabID).Values) - { - ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, true); - } - - EventLogController.Instance.AddLog( - tabToDelete, - portalSettings, - portalSettings.UserId, - string.Empty, - EventLogController.EventLogType.TAB_SENT_TO_RECYCLE_BIN); - deleted = true; - - EventManager.Instance.OnTabRemoved(new TabEventArgs { Tab = tabToDelete }); - } - } - - if (changeControlStateForTab != null && changeControlStateForTab.IsChangeControlEnabledForTab) - { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tabToDelete.TabID, changeControlStateForTab.IsVersioningEnabledForTab); - TabWorkflowSettings.Instance.SetWorkflowEnabled(tabToDelete.PortalID, tabToDelete.TabID, changeControlStateForTab.IsWorkflowEnabledForTab); - } - - return deleted; - } - - private void UpdateTabSettingInternal(int tabId, string settingName, string settingValue, bool clearCache) - { - using (var dr = this.dataProvider.GetTabSetting(tabId, settingName)) - { - if (dr.Read()) - { - if (dr.GetString(0) != settingValue) - { - this.dataProvider.UpdateTabSetting( - tabId, - settingName, - settingValue, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.AddSettingLog( - EventLogController.EventLogType.TAB_SETTING_UPDATED, - "TabId", - tabId, - settingName, - settingValue, - UserController.Instance.GetCurrentUserInfo().UserID); - } - } - else - { - this.dataProvider.UpdateTabSetting( - tabId, - settingName, - settingValue, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.AddSettingLog( - EventLogController.EventLogType.TAB_SETTING_CREATED, - "TabId", - tabId, - settingName, - settingValue, - UserController.Instance.GetCurrentUserInfo().UserID); - } - - dr.Close(); - } - - UpdateTabVersion(tabId); - if (clearCache) - { - this.ClearTabSettingsCache(tabId); - } - } - - private void UpdateTabSettings(ref TabInfo updatedTab) - { - foreach (string sKeyLoopVariable in updatedTab.TabSettings.Keys) - { - string sKey = sKeyLoopVariable; - this.UpdateTabSettingInternal(updatedTab.TabID, sKey, Convert.ToString(updatedTab.TabSettings[sKey]), false); - } - } - } -} + // parent tab not found! + tab.ParentId = Null.NullInteger; + tabName = tab.TabName; + } + } + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"))) + { + if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")] != null) + { + // parent node specifies the path (tab1/tab2/tab3), use saved tabid + int defaultLanguageTabId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")], CultureInfo.InvariantCulture); + TabInfo defaultLanguageTab = Instance.GetTab(defaultLanguageTabId, portalId, false); + if (defaultLanguageTab != null) + { + tab.DefaultLanguageGuid = defaultLanguageTab.UniqueId; + } + } + else + { + // Parent node doesn't spcecify the path, search by name. + // Possible incoherence if tabname not unique + TabInfo defaultLanguageTab = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"), portalId); + if (defaultLanguageTab != null) + { + tab.DefaultLanguageGuid = defaultLanguageTab.UniqueId; + } + } + } + + // create/update tab + if (tab.TabID == Null.NullInteger) + { + tab.TabID = TabController.Instance.AddTab(tab); + } + else + { + Instance.UpdateTab(tab); + } + + // UpdateTabUrls + foreach (XmlNode oTabUrlNode in tabNode.SelectNodes("tabUrls/tabUrl")) + { + var tabUrl = new TabUrlInfo(); + DeserializeTabUrls(oTabUrlNode, tabUrl); + DataProvider.Instance().SaveTabUrl(tab.TabID, tabUrl.SeqNum, tabUrl.PortalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.Instance.GetCurrentUserInfo().UserID); + } + + // extra check for duplicate tabs in same level + if (tabs[tabName] == null) + { + tabs.Add(tabName, tab.TabID); + } + } + + // Parse Panes + if (tabNode.SelectSingleNode("panes") != null) + { + DeserializePanes(businessControllerProvider, tabNode.SelectSingleNode("panes"), portalId, tab.TabID, mergeTabs, modules); + } + + // Finally add "tabid" to node + tabNode.AppendChild(XmlUtils.CreateElement(tabNode.OwnerDocument, "tabid", tab.TabID.ToString(CultureInfo.InvariantCulture))); + return tab; + } + + /// Gets the portal tabs. + /// The portal id. + /// The exclude tab id. + /// if set to [include none specified]. + /// if set to [include hidden]. + /// A or instances. + public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, bool includeHidden) + { + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + "<" + Localization.GetString("None_Specified") + ">", + includeHidden, + false, + false, + false, + false, + true); + } + + /// Gets the portal tabs. + /// The portal id. + /// The exclude tab id. + /// if set to [include none specified]. + /// if set to [include hidden]. + /// if set to [include deleted]. + /// if set to [include URL]. + /// A or instances. + public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, bool includeHidden, bool includeDeleted, bool includeURL) + { + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + "<" + Localization.GetString("None_Specified") + ">", + includeHidden, + includeDeleted, + includeURL, + false, + false, + true); + } + + /// Gets the portal tabs. + /// The portal id. + /// The exclude tab id. + /// if set to [include none specified]. + /// The none specified text. + /// if set to [include hidden]. + /// if set to [include deleted]. + /// if set to [include URL]. + /// if set to [check view permission]. + /// if set to [check edit permission]. + /// A or instances. + public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, bool checkViewPermisison, bool checkEditPermission) + { + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + noneSpecifiedText, + includeHidden, + includeDeleted, + includeURL, + checkViewPermisison, + checkEditPermission, + true); + } + + /// Gets the portal tabs. + /// The tabs. + /// The exclude tab id. + /// if set to [include none specified]. + /// The none specified text. + /// if set to [include hidden]. + /// if set to [include deleted]. + /// if set to [include URL]. + /// if set to [check view permission]. + /// if set to [check edit permission]. + /// A or instances. + public static List GetPortalTabs(List tabs, int excludeTabId, bool includeNoneSpecified, string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, bool checkViewPermisison, bool checkEditPermission) + { + return GetPortalTabs( + tabs, + excludeTabId, + includeNoneSpecified, + noneSpecifiedText, + includeHidden, + includeDeleted, + includeURL, + checkViewPermisison, + checkEditPermission, + true); + } + + /// Gets the portal tabs. + /// The tabs. + /// The exclude tab id. + /// if set to [include none specified]. + /// The none specified text. + /// if set to [include hidden]. + /// if set to [include deleted]. + /// if set to [include URL]. + /// if set to [check view permission]. + /// if set to [check edit permission]. + /// The value of this parameter affects property. + /// A or instances. + public static List GetPortalTabs( + List tabs, + int excludeTabId, + bool includeNoneSpecified, + string noneSpecifiedText, + bool includeHidden, + bool includeDeleted, + bool includeURL, + bool checkViewPermisison, + bool checkEditPermission, + bool includeDeletedChildren) + { + var listTabs = new List(); + if (includeNoneSpecified) + { + var tab = new TabInfo { TabID = -1, TabName = noneSpecifiedText, TabOrder = 0, ParentId = -2 }; + listTabs.Add(tab); + } + + foreach (TabInfo tab in tabs) + { + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + if (((excludeTabId < 0) || (tab.TabID != excludeTabId)) && + (!tab.IsSuperTab || objUserInfo.IsSuperUser)) + { + if ((tab.IsVisible || includeHidden) && tab.HasAVisibleVersion && (tab.IsDeleted == false || includeDeleted) && + (tab.TabType == TabType.Normal || includeURL)) + { + // Check if User has View/Edit Permission for this tab + if (checkEditPermission || checkViewPermisison) + { + const string permissionList = "ADD,COPY,EDIT,MANAGE"; + if (checkEditPermission && + TabPermissionController.HasTabPermission(tab.TabPermissions, permissionList)) + { + listTabs.Add(tab); + } + else if (checkViewPermisison && TabPermissionController.CanViewPage(tab)) + { + listTabs.Add(tab); + } + } + else + { + // Add Tab to List + listTabs.Add(tab); + } + } + + // HasChildren should be true in case there is at least one not deleted child + tab.HasChildren = tab.HasChildren && (includeDeletedChildren || GetTabsByParent(tab.TabID, tab.PortalID).Any(a => !a.IsDeleted)); + } + } + + return listTabs; + } + + /// Gets the tab by tab path. + /// The portal id. + /// The tab path. + /// The culture code. + /// The tab ID or -1. + public static int GetTabByTabPath(int portalId, string tabPath, string cultureCode) + { + var tabPathDictionary = GetTabPathDictionary(portalId, cultureCode); + if (tabPathDictionary.TryGetValue(tabPath, out var tabId)) + { + return tabId; + } + + return -1; + } + + /// Gets the tab path dictionary. + /// The portal id. + /// The culture code. + /// A mapping tab path to tab ID. + public static Dictionary GetTabPathDictionary(int portalId, string cultureCode) + { + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabPathCacheKey, cultureCode, portalId); + return + CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, DataCache.TabPathCacheTimeOut, DataCache.TabPathCachePriority, cultureCode, portalId), + GetTabPathDictionaryCallback); + } + + /// Gets the tabs by parent. + /// The parent id. + /// The portal id. + /// A or instances. + public static List GetTabsByParent(int parentId, int portalId) + { + return Instance.GetTabsByPortal(portalId).WithParentId(parentId); + } + + /// Gets the tabs by sort order. + /// The portal id. + /// The culture code. + /// if set to [include neutral]. + /// A or instances. + public static List GetTabsBySortOrder(int portalId, string cultureCode, bool includeNeutral) + { + return Instance.GetTabsByPortal(portalId).WithCulture(cultureCode, includeNeutral).AsList(); + } + + /// Get all TabInfo for the current culture in SortOrder. + /// The portal ID to load tabs for. + /// List of TabInfo ordered by default SortOrder. + /// + /// This method uses the Active culture. There is an overload + /// which allows the culture information to be specified. + /// + public static List GetTabsBySortOrder(int portalId) + { + return GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true); + } + + /// Determines whether is special tab. + /// The tab id. + /// The portal id. + /// if the page is special, otherwise . + public static bool IsSpecialTab(int tabId, int portalId) + { + Dictionary locales = LocaleController.Instance.GetLocales(portalId); + bool isSpecial = false; + foreach (Locale locale in locales.Values) + { + PortalInfo portal = PortalController.Instance.GetPortal(portalId, locale.Code); + var portalSettings = new PortalSettings(portal); + isSpecial = IsSpecialTab(tabId, portalSettings); + + if (isSpecial) + { + break; + } + } + + return isSpecial; + } + + /// Determines whether is special tab. + /// The tab id. + /// The portal settings. + /// if is special tab; otherwise, . + public static bool IsSpecialTab(int tabId, PortalSettings portalSettings) + { + return tabId == portalSettings.SplashTabId || tabId == portalSettings.HomeTabId || + tabId == portalSettings.LoginTabId || tabId == portalSettings.UserTabId || + tabId == portalSettings.AdminTabId || tabId == portalSettings.SuperTabId; + } + + /// Serializes the metadata of a page and its modules (and optionally the modules' contents) to an XML node. + /// The DI container. + /// The Xml Document to use for the Tab. + /// The TabInfo object to serialize. + /// A flag used to determine if the Module content is included. + /// An representing the page's data. + public static XmlNode SerializeTab(IBusinessControllerProvider businessControllerProvider, XmlDocument tabXml, TabInfo objTab, bool includeContent) + { + return SerializeTab(businessControllerProvider, tabXml, null, objTab, null, includeContent); + } + + /// Serializes the metadata of a page and its modules (and optionally the modules' contents) to an XML node. + /// The business controller provider. + /// The Xml Document to use for the Tab. + /// A Hashtable used to store the names of the tabs. + /// The TabInfo object to serialize. + /// The Portal object to which the tab belongs. + /// A flag used to determine if the Module content is included. + /// An representing the page's data. + public static XmlNode SerializeTab(IBusinessControllerProvider businessControllerProvider, XmlDocument tabXml, Hashtable tabs, TabInfo tab, PortalInfo portal, bool includeContent) + { + XmlElement newElement; + CBO.SerializeObject(tab, tabXml); + + var tabNode = tabXml.SelectSingleNode("tab"); + if (tabNode != null) + { + if (tabNode.Attributes != null) + { + tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsd"]); + tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsi"]); + } + + // remove unwanted elements + // ReSharper disable AssignNullToNotNullAttribute + tabNode.RemoveChildNode("tabid"); + tabNode.RemoveChildNode("moduleID"); + tabNode.RemoveChildNode("taborder"); + tabNode.RemoveChildNode("portalid"); + tabNode.RemoveChildNode("parentid"); + tabNode.RemoveChildNode("isdeleted"); + tabNode.RemoveChildNode("tabpath"); + tabNode.RemoveChildNode("haschildren"); + tabNode.RemoveChildNode("skindoctype"); + tabNode.RemoveChildNode("uniqueid"); + tabNode.RemoveChildNode("versionguid"); + tabNode.RemoveChildNode("defaultLanguageGuid"); + tabNode.RemoveChildNode("localizedVersionGuid"); + var xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); + if (xmlNodeList is { Count: 0, }) + { + // for some reason serialization of permissions did not work + // we are using a different method here to make sure that + // permissions are included in the tabinfo xml + var tabPermissions = new XmlDocument { XmlResolver = null, }; + CBO.SerializeObject(tab.TabPermissions, tabPermissions); + + var permissionsNode = tabXml.CreateElement("tabpermissions"); + var tabPermissionsNodeList = tabPermissions.SelectNodes("tabpermissions/TabPermissionInfo"); + if (tabPermissionsNodeList != null) + { + foreach (XmlNode nodePermission in tabPermissionsNodeList) + { + var newNode = tabXml.CreateElement("permission"); + newNode.InnerXml = nodePermission.InnerXml; + permissionsNode.AppendChild(newNode); + } + } + + tabNode.AppendChild(permissionsNode); + + // re-select the permissions node + xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); + } + + if (xmlNodeList != null) + { + foreach (XmlNode nodePermission in xmlNodeList) + { + nodePermission.RemoveChildNode("tabpermissionid"); + nodePermission.RemoveChildNode("permissionid"); + nodePermission.RemoveChildNode("tabid"); + nodePermission.RemoveChildNode("roleid"); + nodePermission.RemoveChildNode("userid"); + nodePermission.RemoveChildNode("username"); + nodePermission.RemoveChildNode("displayname"); + } + } + + // ReSharper restore AssignNullToNotNullAttribute + } + + // Manage Url + XmlNode urlNode = tabXml.SelectSingleNode("tab/url"); + switch (tab.TabType) + { + case TabType.Normal: + urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Normal")); + break; + case TabType.Tab: + urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Tab")); + + // Get the tab being linked to + TabInfo tempTab = TabController.Instance.GetTab(int.Parse(tab.Url, CultureInfo.InvariantCulture), tab.PortalID, false); + if (tempTab != null) + { + urlNode.InnerXml = tempTab.TabPath; + } + + break; + case TabType.File: + urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "File")); + IFileInfo file = FileManager.Instance.GetFile(int.Parse(tab.Url.Substring(7), CultureInfo.InvariantCulture)); + urlNode.InnerXml = file.RelativePath; + break; + case TabType.Url: + urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Url")); + break; + } + + // serialize TabSettings + XmlUtils.SerializeHashtable(tab.TabSettings, tabXml, tabNode, "tabsetting", "settingname", "settingvalue"); + if (portal != null) + { + if (tab.TabID == portal.SplashTabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "splashtab"; + tabNode.AppendChild(newElement); + } + else if (tab.TabID == portal.HomeTabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "hometab"; + tabNode.AppendChild(newElement); + } + else if (tab.TabID == portal.UserTabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "usertab"; + tabNode.AppendChild(newElement); + } + else if (tab.TabID == portal.LoginTabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "logintab"; + tabNode.AppendChild(newElement); + } + else if (tab.TabID == portal.SearchTabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "searchtab"; + tabNode.AppendChild(newElement); + } + else if (tab.TabID == portal.Custom404TabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "404tab"; + tabNode.AppendChild(newElement); + } + else if (tab.TabID == portal.Custom500TabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "500tab"; + tabNode.AppendChild(newElement); + } + else if (tab.TabID == portal.TermsTabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "termstab"; + tabNode.AppendChild(newElement); + } + else if (tab.TabID == portal.PrivacyTabId) + { + newElement = tabXml.CreateElement("tabtype"); + newElement.InnerXml = "privacytab"; + tabNode.AppendChild(newElement); + } + } + + if (tabs != null) + { + // Manage Parent Tab + if (!Null.IsNull(tab.ParentId)) + { + newElement = tabXml.CreateElement("parent"); + newElement.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.ParentId].ToString()); + tabNode.AppendChild(newElement); + + // save tab as: ParentTabName/CurrentTabName + tabs.Add(tab.TabID, tabs[tab.ParentId] + "/" + tab.TabName); + } + else + { + // save tab as: CurrentTabName + tabs.Add(tab.TabID, tab.TabName); + } + } + + // Manage Content Localization + if (tab.DefaultLanguageTab != null) + { + try + { + newElement = tabXml.CreateElement("defaultLanguageTab"); + newElement.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.DefaultLanguageTab.TabID].ToString()); + tabNode.AppendChild(newElement); + } + catch + { + // ignore + } + } + + // Serialize modules + var panesNode = tabNode.AppendChild(tabXml.CreateElement("panes")); + foreach (var kvp in ModuleController.Instance.GetTabModules(tab.TabID)) + { + var module = kvp.Value; + if (!module.IsDeleted) + { + var moduleXml = new XmlDocument { XmlResolver = null }; + var moduleNode = ModuleController.SerializeModule(businessControllerProvider, moduleXml, module, includeContent); + if (panesNode.SelectSingleNode($"descendant::pane[name='{module.PaneName}']") == null) + { + // new pane found + var paneNode = moduleXml.CreateElement("pane"); + var nameNode = paneNode.AppendChild(moduleXml.CreateElement("name")); + nameNode.InnerText = module.PaneName; + paneNode.AppendChild(moduleXml.CreateElement("modules")); + panesNode.AppendChild(tabXml.ImportNode(paneNode, true)); + } + + var modulesNode = panesNode.SelectSingleNode($"descendant::pane[name='{module.PaneName}']/modules"); + modulesNode.AppendChild(tabXml.ImportNode(moduleNode, true)); + } + } + + // Serialize TabUrls + var tabUrlsNode = tabNode.AppendChild(tabXml.CreateElement("tabUrls")); + foreach (var tabUrl in TabController.Instance.GetTabUrls(tab.TabID, tab.PortalID)) + { + var tabUrlXml = new XmlDocument { XmlResolver = null }; + XmlNode tabUrlNode = tabUrlXml.CreateElement("tabUrl"); + tabUrlNode.AddAttribute("SeqNum", tabUrl.SeqNum.ToString(CultureInfo.InvariantCulture)); + tabUrlNode.AddAttribute("Url", tabUrl.Url); + tabUrlNode.AddAttribute("QueryString", tabUrl.QueryString); + tabUrlNode.AddAttribute("HttpStatus", tabUrl.HttpStatus); + tabUrlNode.AddAttribute("CultureCode", tabUrl.CultureCode); + tabUrlNode.AddAttribute("IsSystem", tabUrl.IsSystem.ToString()); + tabUrlsNode.AppendChild(tabXml.ImportNode(tabUrlNode, true)); + } + + EventManager.Instance.OnTabSerialize(new TabSyncEventArgs { Tab = tab, TabNode = tabNode }); + + return tabNode; + } + + /// check whether there is a conflict between tab path and portal alias. + /// portal id. + /// tab path. + /// if the tab path is a duplicate of a portal alias, otherwise . + public static bool IsDuplicateWithPortalAlias(int portalId, string tabPath) + { + var aliasLookup = PortalAliasController.Instance.GetPortalAliases(); + + foreach (IPortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId)) + { + string checkAlias = $"{alias.HttpAlias}{tabPath.Replace("//", "/")}"; + + foreach (IPortalAliasInfo a in aliasLookup.Values) + { + if (a.HttpAlias.Equals(checkAlias, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + + return false; + } + + public static bool IsValidTabName(string tabName, out string invalidType) + { + invalidType = string.Empty; + + if (string.IsNullOrEmpty(tabName.Trim())) + { + invalidType = "EmptyTabName"; + return false; + } + + var cleanTabName = HtmlUtils.StripNonWord(tabName, false); + if (TabNameCheck1.IsMatch(tabName) || TabNameCheck2.IsMatch(cleanTabName)) + { + invalidType = "InvalidTabName"; + return false; + } + + if (Config.GetFriendlyUrlProvider() == "advanced" && PortalSettings.Current != null) + { + var doNotRewriteRegex = new FriendlyUrlSettings(PortalSettings.Current.PortalId).DoNotRewriteRegex; + if (!string.IsNullOrEmpty(doNotRewriteRegex) && + (Regex.IsMatch(cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) + || Regex.IsMatch("/" + cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) + || Regex.IsMatch("/" + cleanTabName + "/", doNotRewriteRegex, RegexOptions.IgnoreCase))) + { + invalidType = "InvalidTabName"; + return false; + } + } + + return true; + } + + /// + public bool AddMissingLanguagesWithWarnings(int portalId, int tabId) + { + var addedAllMissingLanguages = true; + var currentTab = this.GetTab(tabId, portalId, false); + if (currentTab.CultureCode != null) + { + var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalId); + var workingTab = currentTab; + if (workingTab.CultureCode != defaultLocale.Code && workingTab.DefaultLanguageTab == null) + { + // we are adding missing languages to a single culture page that is not in the default language + // so we must first add a page in the default culture + this.CreateLocalizedCopyInternal(workingTab, defaultLocale, false, true, insertAfterOriginal: true); + } + + if (currentTab.DefaultLanguageTab != null) + { + workingTab = currentTab.DefaultLanguageTab; + } + + foreach (Locale locale in LocaleController.Instance.GetLocales(portalId).Values) + { + if (!LocaleController.Instance.IsDefaultLanguage(locale.Code)) + { + bool missing = true; + foreach (var localizedTab in workingTab.LocalizedTabs.Values.Where(localizedTab => localizedTab.CultureCode == locale.Code)) + { + missing = false; + } + + if (missing) + { + bool isRootOrLocalizedParentExists = this.CanLocalizeTabToLocale(workingTab, locale); + if (isRootOrLocalizedParentExists) + { + this.CreateLocalizedCopyInternal(workingTab, locale, false, true, insertAfterOriginal: true); + } + else + { + addedAllMissingLanguages = false; + } + } + } + } + + // For newly localized parent tabs, its localized children need to be updated to point at their corresponding localized parents + this.UpdateChildTabLocalizedParents(portalId, tabId); + } + + return addedAllMissingLanguages; + } + + /// Adds a tab. + /// The tab to be added. + /// The tab is added to the end of the current Level. + /// The new tab ID. + public int AddTab(TabInfo tab) + { + return this.AddTab(tab, true); + } + + /// Adds a tab. + /// The tab to be added. + /// Flag that indicates whether to add the "AllTabs" Modules. + /// The tab is added to the end of the current Level. + /// The new tab ID. + public int AddTab(TabInfo tab, bool includeAllTabsModules) + { + // Add tab to store + int tabID = this.AddTabInternal(tab, -1, -1, includeAllTabsModules); + + // Clear the Cache + this.ClearCache(tab.PortalID); + + return tabID; + } + + /// Adds a tab after the specified tab. + /// The tab to be added. + /// Id of the tab after which this tab is added. + /// The new tab ID. + public int AddTabAfter(TabInfo tab, int afterTabId) + { + // Add tab to store + int tabID = this.AddTabInternal(tab, afterTabId, -1, true); + + // Clear the Cache + this.ClearCache(tab.PortalID); + + return tabID; + } + + /// Adds a tab before the specified tab. + /// The tab to be added. + /// Id of the tab before which this tab is added. + /// The new tab ID. + public int AddTabBefore(TabInfo objTab, int beforeTabId) + { + // Add tab to store + int tabID = this.AddTabInternal(objTab, -1, beforeTabId, true); + + // Clear the Cache + this.ClearCache(objTab.PortalID); + + return tabID; + } + + /// Clears tabs and portal cache for the specific portal. + /// The portal id. + public void ClearCache(int portalId) + { + DataCache.ClearTabsCache(portalId); + + // Clear the Portal cache so the Pages count is correct + DataCache.ClearPortalCache(portalId, false); + + DataCache.RemoveCache(DataCache.PortalDictionaryCacheKey); + + CacheController.FlushPageIndexFromCache(); + } + + /// + public void RefreshCache(int portalId, int tabId) + { + var portalTabs = this.GetTabsByPortal(portalId); + if (portalTabs.WithTabId(tabId) != null) + { + var updateTab = this.GetTab(tabId, portalId, true); + portalTabs.RefreshCache(tabId, updateTab); + } + } + + /// + public void ConvertTabToNeutralLanguage(int portalId, int tabId, string cultureCode, bool clearCache) + { + // parent tabs can not be deleted + if (this.GetTabsByPortal(portalId).WithParentId(tabId).Count == 0) + { + // delete all translated / localized tabs for this tab + var tab = this.GetTab(tabId, portalId, true); + foreach (var localizedTab in tab.LocalizedTabs.Values) + { + this.HardDeleteTabInternal(localizedTab.TabID, portalId); + } + + // reset culture of current tab back to neutral + this.dataProvider.ConvertTabToNeutralLanguage(portalId, tabId, cultureCode); + if (clearCache) + { + this.ClearCache(portalId); + } + } + } + + /// Creates content item for the tab.. + /// The updated tab. + public void CreateContentItem(TabInfo tab) + { + // First create ContentItem as we need the ContentItemID + ContentType contentType = ContentType.Tab; + + IContentController contentController = Util.GetContentController(); + tab.Content = string.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; + if (contentType != null) + { + tab.ContentTypeId = contentType.ContentTypeId; + } + + tab.Indexed = false; + contentController.AddContentItem(tab); + } + + /// Creates the localized copies. + /// The original tab. + public void CreateLocalizedCopies(TabInfo originalTab) + { + Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(originalTab.PortalID); + foreach (Locale subLocale in LocaleController.Instance.GetLocales(originalTab.PortalID).Values) + { + if (subLocale.Code != defaultLocale.Code) + { + this.CreateLocalizedCopyInternal(originalTab, subLocale, false, true); + } + } + + // For newly localized parent tabs, its localized children need to be updated to point at their corresponding localized parents + this.UpdateChildTabLocalizedParents(originalTab.PortalID, originalTab.TabID); + } + + /// Creates the localized copy. + /// The original tab. + /// The locale. + /// Clear the cache?. + public void CreateLocalizedCopy(TabInfo originalTab, Locale locale, bool clearCache) + { + this.CreateLocalizedCopyInternal(originalTab, locale, true, clearCache); + + // For newly localized parent tabs, its localized children need to be updated to point at their corresponding localized parents + this.UpdateChildTabLocalizedParents(originalTab.PortalID, originalTab.TabID); + } + + /// Deletes a tab permanently from the database. + /// TabId of the tab to be deleted. + /// PortalId of the portal. + /// + /// The tab will not delete if it has child tab(s). + /// + public void DeleteTab(int tabId, int portalId) + { + // parent tabs can not be deleted + if (this.GetTabsByPortal(portalId).WithParentId(tabId).Count == 0) + { + this.HardDeleteTabInternal(tabId, portalId); + } + + this.ClearCache(portalId); + } + + /// Deletes a tab permanently from the database. + /// The tab id. + /// The portal id. + /// if set to will delete all child tabs. + public void DeleteTab(int tabId, int portalId, bool deleteDescendants) + { + List descendantList = this.GetTabsByPortal(portalId).DescendentsOf(tabId); + if (deleteDescendants && descendantList.Count > 0) + { + // Iterate through descendants from bottom - which will remove children first + for (int i = descendantList.Count - 1; i >= 0; i += -1) + { + this.HardDeleteTabInternal(descendantList[i].TabID, portalId); + } + } + + this.HardDeleteTabInternal(tabId, portalId); + this.ClearCache(portalId); + } + + /// Delete a Setting of a tab instance. + /// ID of the affected tab. + /// Name of the setting to be deleted. + public void DeleteTabSetting(int tabId, string settingName) + { + this.dataProvider.DeleteTabSetting(tabId, settingName); + var log = new LogInfo { LogTypeKey = nameof(EventLogType.TAB_SETTING_DELETED) }; + log.LogProperties.Add(new LogDetailInfo("TabID", tabId.ToString(CultureInfo.InvariantCulture))); + log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); + LogController.Instance.AddLog(log); + + UpdateTabVersion(tabId); + this.ClearTabSettingsCache(tabId); + } + + /// Delete all Settings of a tab instance. + /// ID of the affected tab. + public void DeleteTabSettings(int tabId) + { + this.dataProvider.DeleteTabSettings(tabId); + var log = new LogInfo { LogTypeKey = nameof(EventLogType.TAB_SETTING_DELETED) }; + log.LogProperties.Add(new LogDetailInfo("TabId", tabId.ToString(CultureInfo.InvariantCulture))); + LogController.Instance.AddLog(log); + UpdateTabVersion(tabId); + this.ClearTabSettingsCache(tabId); + } + + /// Delete a tabUrl. + /// the tabUrl. + /// the portal. + /// whether to clear the cache. + public void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) + { + DataProvider.Instance().DeleteTabUrl(tabUrl.TabId, tabUrl.SeqNum); + + EventLogController.Instance.AddLog( + "tabUrl.TabId", + tabUrl.TabId.ToString(CultureInfo.InvariantCulture), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.TABURL_DELETED); + if (clearCache) + { + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.TabUrlCacheKey, portalId)); + CacheController.ClearCustomAliasesCache(); + var tab = this.GetTab(tabUrl.TabId, portalId); + tab.ClearTabUrls(); + } + } + + /// + public bool DeleteTranslatedTabs(int portalId, string cultureCode, bool clearCache) + { + if (PortalController.Instance.GetCurrentPortalSettings() != null) + { + var defaultLanguage = PortalController.Instance.GetCurrentPortalSettings().DefaultLanguage; + if (cultureCode != defaultLanguage) + { + this.dataProvider.DeleteTranslatedTabs(portalId, cultureCode); + + if (clearCache) + { + this.ClearCache(portalId); + } + } + } + + return true; + } + + /// + public void EnsureNeutralLanguage(int portalId, string cultureCode, bool clearCache) + { + this.dataProvider.EnsureNeutralLanguage(portalId, cultureCode); + if (clearCache) + { + this.ClearCache(portalId); + } + } + + /// Get the list of skins per alias at tab level. + /// the tab id. + /// the portal id. + /// list of TabAliasSkinInfo. + public List GetAliasSkins(int tabId, int portalId) + { + // Get the Portal AliasSkin Dictionary + Dictionary> dicTabAliases = this.GetAliasSkins(portalId); + + // Get the Collection from the Dictionary + List tabAliases; + bool bFound = dicTabAliases.TryGetValue(tabId, out tabAliases); + if (!bFound) + { + // Return empty collection + tabAliases = new List(); + } + + return tabAliases; + } + + /// Get the list of custom aliases associated with a page (tab). + /// the tab id. + /// the portal id. + /// dictionary of tabid and aliases. + public Dictionary GetCustomAliases(int tabId, int portalId) + { + // Get the Portal CustomAlias Dictionary + Dictionary> dicCustomAliases = this.GetCustomAliases(portalId); + + // Get the Collection from the Dictionary + Dictionary customAliases; + bool bFound = dicCustomAliases.TryGetValue(tabId, out customAliases); + if (!bFound) + { + // Return empty collection + customAliases = new Dictionary(); + } + + return customAliases; + } + + /// Gets the tab. + /// The tab id. + /// The portal id or . + /// tab info. + public TabInfo GetTab(int tabId, int portalId) + { + return this.GetTab(tabId, portalId, false); + } + + /// Gets the tab. + /// The tab id. + /// The portal id or . + /// if set to will get tab info directly from database. + /// tab info. + public TabInfo GetTab(int tabId, int portalId, bool ignoreCache) + { + TabInfo tab = null; + + if (tabId <= 0) + { + Logger.WarnFormat(CultureInfo.InvariantCulture, "Invalid tabId {0} of portal {1}", tabId, portalId); + } + else if (ignoreCache || Host.Host.PerformanceSetting == Globals.PerformanceSettings.NoCaching) + { + // if we are using the cache + tab = CBO.FillObject(this.dataProvider.GetTab(tabId)); + } + else + { + // if we do not know the PortalId then try to find it in the Portals Dictionary using the TabId + portalId = GetPortalId(tabId, portalId); + + // if we have the PortalId then try to get the TabInfo object + tab = this.GetTabsByPortal(portalId).WithTabId(tabId) ?? + this.GetTabsByPortal(GetPortalId(tabId, Null.NullInteger)).WithTabId(tabId); + + if (tab == null) + { + // recheck the info directly from database to make sure we can avoid error if the cache doesn't update + // correctly, this may occur when install is set up in web farm. + tab = CBO.FillObject(this.dataProvider.GetTab(tabId)); + + // if tab is not null, and it is for "portalId", that means that the cache doesn't update correctly, + // we need to clear the cache and let it rebuild cache when request next time. + if (tab != null && tab.PortalID == portalId) + { + this.ClearCache(tab.PortalID); + } + else + { + Logger.WarnFormat(CultureInfo.InvariantCulture, "Unable to find tabId {0} of portal {1}", tabId, portalId); + } + } + } + + return tab; + } + + /// Gets the tab by culture. + /// The tab id. + /// The portal id. + /// The locale. + /// tab info. + public TabInfo GetTabByCulture(int tabId, int portalId, Locale locale) + { + TabInfo localizedTab = null; + TabCollection tabs = this.GetTabsByPortal(portalId); + + // Get Tab specified by Id + TabInfo originalTab = tabs.WithTabId(tabId); + + if (locale != null && originalTab != null) + { + // Check if tab is in the requested culture + if (string.IsNullOrEmpty(originalTab.CultureCode) || originalTab.CultureCode == locale.Code) + { + localizedTab = originalTab; + } + else + { + // See if tab exists for culture + if (originalTab.IsDefaultLanguage) + { + originalTab.LocalizedTabs.TryGetValue(locale.Code, out localizedTab); + } + else + { + if (originalTab.DefaultLanguageTab != null) + { + if (originalTab.DefaultLanguageTab.CultureCode == locale.Code) + { + localizedTab = originalTab.DefaultLanguageTab; + } + else + { + if ( + !originalTab.DefaultLanguageTab.LocalizedTabs.TryGetValue( + locale.Code, + out localizedTab)) + { + localizedTab = originalTab.DefaultLanguageTab; + } + } + } + } + } + } + + return localizedTab; + } + + /// Gets the name of the tab by name. + /// Name of the tab. + /// The portal id. + /// tab info. + public TabInfo GetTabByName(string tabName, int portalId) + { + return this.GetTabsByPortal(portalId).WithTabName(tabName); + } + + /// Gets the name of the tab by name and parent id. + /// Name of the tab. + /// The portal id. + /// The parent id. + /// tab info. + public TabInfo GetTabByName(string tabName, int portalId, int parentId) + { + return this.GetTabsByPortal(portalId).WithTabNameAndParentId(tabName, parentId); + } + + /// Gets the tabs which use the module. + /// The module ID. + /// tab collection. + public IDictionary GetTabsByModuleID(int moduleID) + { + return CBO.FillDictionary("TabID", this.dataProvider.GetTabsByModuleID(moduleID)); + } + + /// Gets the tabs which use the module. + /// The tabmodule ID. + /// tab collection. + public IDictionary GetTabsByTabModuleID(int tabModuleId) + { + return CBO.FillDictionary("TabID", this.dataProvider.GetTabsByTabModuleID(tabModuleId)); + } + + /// Gets the tabs which use the package. + /// The portal ID. + /// The package ID. + /// if set to [for host]. + /// tab collection. + public IDictionary GetTabsByPackageID(int portalID, int packageID, bool forHost) + { + return CBO.FillDictionary("TabID", this.dataProvider.GetTabsByPackageID(portalID, packageID, forHost)); + } + + /// Gets the tabs by portal. + /// The portal id. + /// tab collection. + public TabCollection GetTabsByPortal(int portalId) + { + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabCacheKey, portalId); + return CBO.GetCachedObject( + new CacheItemArgs( + cacheKey, + DataCache.TabCacheTimeOut, + DataCache.TabCachePriority), + c => + { + List tabs = CBO.FillCollection(this.dataProvider.GetTabs(portalId)); + return new TabCollection(tabs); + }); + } + + /// + public TabCollection GetUserTabsByPortal(int portalId) + { + var tabs = this.GetTabsByPortal(portalId); + var portal = PortalController.Instance.GetPortal(portalId); + + IEnumerable filteredList = from tab in tabs + where + !tab.Value.IsSystem + && tab.Value.TabID != portal.AdminTabId + && tab.Value.ParentId != portal.AdminTabId + select tab.Value; + return new TabCollection(filteredList); + } + + /// read all settings for a tab from TabSettings table. + /// ID of the Tab to query. + /// + /// (cached) hashtable containing all settings. + /// + public Hashtable GetTabSettings(int tabId) + { + var portalId = GetPortalId(tabId, -1); + Hashtable settings; + if (!this.GetTabSettingsByPortal(portalId).TryGetValue(tabId, out settings)) + { + settings = new Hashtable(); + } + + return settings; + } + + /// Get the list of url's associated with a page (tab). + /// the tab id. + /// the portal id. + /// list of urls associated with a tab. + public List GetTabUrls(int tabId, int portalId) + { + // Get the Portal TabUrl Dictionary + Dictionary> dicTabUrls = this.GetTabUrls(portalId); + + // Get the Collection from the Dictionary + List tabRedirects; + bool bFound = dicTabUrls.TryGetValue(tabId, out tabRedirects); + if (!bFound) + { + // Return empty collection + tabRedirects = new List(); + } + + return tabRedirects; + } + + /// Gives the translator role edit rights. + /// The localized tab. + /// The users. + public void GiveTranslatorRoleEditRights(TabInfo localizedTab, Dictionary users) + { + var permissionCtrl = new PermissionController(); + ArrayList permissionsList = permissionCtrl.GetPermissionByCodeAndKey("SYSTEM_TAB", "EDIT"); + + string translatorRoles = PortalController.GetPortalSetting($"DefaultTranslatorRoles-{localizedTab.CultureCode}", localizedTab.PortalID, string.Empty); + foreach (string translatorRole in translatorRoles.Split(';')) + { + if (users != null) + { + foreach (var translator in RoleController.Instance.GetUsersByRole(localizedTab.PortalID, translatorRole)) + { + users[translator.UserID] = translator; + } + } + + if (permissionsList is { Count: > 0 }) + { + var translatePermission = (PermissionInfo)permissionsList[0]; + string roleName = translatorRole; + RoleInfo role = RoleController.Instance.GetRole( + localizedTab.PortalID, + r => r.RoleName == roleName); + if (role != null) + { + TabPermissionInfo perm = + localizedTab.TabPermissions.Where( + tp => tp.RoleID == role.RoleID && tp.PermissionKey == "EDIT").SingleOrDefault(); + if (perm == null) + { + // Create Permission + var tabTranslatePermission = new TabPermissionInfo(translatePermission) + { + RoleID = role.RoleID, + AllowAccess = true, + RoleName = roleName, + }; + localizedTab.TabPermissions.Add(tabTranslatePermission); + this.UpdateTab(localizedTab); + } + } + } + } + } + + /// + public bool HasMissingLanguages(int portalId, int tabId) + { + var currentTab = this.GetTab(tabId, portalId, false); + var workingTab = currentTab; + var locales = LocaleController.Instance.GetLocales(portalId); + var localeCount = locales.Count; + if (currentTab.DefaultLanguageTab != null) + { + workingTab = currentTab.DefaultLanguageTab; + } + + var localizedCount = 1 + + locales.Values.Where(locale => !LocaleController.Instance.IsDefaultLanguage(locale.Code)) + .Count(locale => workingTab.LocalizedTabs.Values.Any(localizedTab => localizedTab.CultureCode == locale.Code)); + + return (localeCount - localizedCount) != 0; + } + + /// Checks whether the tab is published. Published means: view permissions of tab are identical to the DefaultLanguageTab. + /// The tab that is checked. + /// true if tab is published. + public bool IsTabPublished(TabInfo publishTab) + { + bool returnValue = true; + + // To publish a subsidiary language tab we need to enable the View Permissions + if (publishTab != null && publishTab.DefaultLanguageTab != null) + { + foreach (TabPermissionInfo perm in + publishTab.DefaultLanguageTab.TabPermissions.Where(p => p.PermissionKey == "VIEW")) + { + TabPermissionInfo sourcePerm = perm; + TabPermissionInfo targetPerm = + publishTab.TabPermissions.Where( + p => + p.PermissionKey == sourcePerm.PermissionKey && p.RoleID == sourcePerm.RoleID && + p.UserID == sourcePerm.UserID).SingleOrDefault(); + + if (targetPerm == null) + { + returnValue = false; + break; + } + } + } + + return returnValue; + } + + /// Localizes the tab. + /// The original tab. + /// The locale. + public void LocalizeTab(TabInfo originalTab, Locale locale) + { + this.LocalizeTab(originalTab, locale, true); + } + + /// + public void LocalizeTab(TabInfo originalTab, Locale locale, bool clearCache) + { + this.dataProvider.LocalizeTab(originalTab.TabID, locale.Code, UserController.Instance.GetCurrentUserInfo().UserID); + if (clearCache) + { + DataCache.ClearTabsCache(originalTab.PortalID); + DataCache.ClearModuleCache(originalTab.TabID); + } + } + + /// Moves the tab after a specific tab. + /// The tab want to move. + /// will move objTab after this tab. + public void MoveTabAfter(TabInfo tab, int afterTabId) + { + // Get AfterTab + var afterTab = this.GetTab(afterTabId, tab.PortalID, false); + + // Create Tab Redirects + if (afterTab.ParentId != tab.ParentId) + { + this.CreateTabRedirects(tab); + } + + // Move Tab + this.dataProvider.MoveTabAfter(tab.TabID, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); + + // Clear the Cache + this.ClearCache(tab.PortalID); + + var portalId = GetPortalId(tab.TabID, -1); + var updatedTab = this.GetTab(tab.TabID, portalId, true); + EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); + } + + /// Moves the tab before a specific tab. + /// The tab want to move. + /// will move objTab before this tab. + public void MoveTabBefore(TabInfo tab, int beforeTabId) + { + // Get AfterTab + var beforeTab = this.GetTab(beforeTabId, tab.PortalID, false); + + // Create Tab Redirects + if (beforeTab.ParentId != tab.ParentId) + { + this.CreateTabRedirects(tab); + } + + // Move Tab + this.dataProvider.MoveTabBefore(tab.TabID, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID); + + // Clear the Cache + this.ClearCache(tab.PortalID); + + var portalId = GetPortalId(tab.TabID, -1); + var updatedTab = this.GetTab(tab.TabID, portalId, true); + EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); + } + + /// Moves the tab to a new parent. + /// The tab want to move. + /// will move tab to this parent. + public void MoveTabToParent(TabInfo tab, int parentId) + { + // Create Tab Redirects + if (parentId != tab.ParentId) + { + this.CreateTabRedirects(tab); + } + + // Move Tab + this.dataProvider.MoveTabToParent(tab.TabID, parentId, UserController.Instance.GetCurrentUserInfo().UserID); + + // Clear the Cache + this.ClearCache(tab.PortalID); + + var portalId = GetPortalId(tab.TabID, -1); + var updatedTab = this.GetTab(tab.TabID, portalId, true); + EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); + } + + /// Populates the bread crumbs. + /// The tab. + public void PopulateBreadCrumbs(ref TabInfo tab) + { + if (tab.BreadCrumbs == null) + { + var crumbs = new ArrayList(); + this.PopulateBreadCrumbs(tab.PortalID, ref crumbs, tab.TabID); + tab.BreadCrumbs = crumbs; + } + } + + /// Populates the bread crumbs. + /// The portal ID. + /// The bread crumbs. + /// The tab ID. + public void PopulateBreadCrumbs(int portalID, ref ArrayList breadCrumbs, int tabID) + { + // find the tab in the tabs collection + TabInfo tab; + TabCollection portalTabs = this.GetTabsByPortal(portalID); + TabCollection hostTabs = this.GetTabsByPortal(Null.NullInteger); + bool found = portalTabs.TryGetValue(tabID, out tab); + if (!found) + { + found = hostTabs.TryGetValue(tabID, out tab); + } + + // if tab was found + if (found) + { + breadCrumbs.Insert(0, tab.Clone()); + + // get the tab parent + if (!Null.IsNull(tab.ParentId)) + { + this.PopulateBreadCrumbs(portalID, ref breadCrumbs, tab.ParentId); + } + } + } + + /// Publishes the tab. Set the VIEW permission. + /// The publish tab. + public void PublishTab(TabInfo publishTab) + { + // To publish a subsidiary language tab we need to enable the View Permissions + if (publishTab != null && publishTab.DefaultLanguageTab != null) + { + foreach (TabPermissionInfo perm in + publishTab.DefaultLanguageTab.TabPermissions.Where(p => p.PermissionKey == "VIEW")) + { + TabPermissionInfo sourcePerm = perm; + TabPermissionInfo targetPerm = + publishTab.TabPermissions.Where( + p => + p.PermissionKey == sourcePerm.PermissionKey && p.RoleID == sourcePerm.RoleID && + p.UserID == sourcePerm.UserID).SingleOrDefault(); + + if (targetPerm == null) + { + publishTab.TabPermissions.Add(sourcePerm); + } + + TabPermissionController.SaveTabPermissions(publishTab); + } + } + } + + /// Publishes the tabs. + /// The tabs. + public void PublishTabs(List tabs) + { + foreach (TabInfo t in tabs) + { + if (t.IsTranslated) + { + this.PublishTab(t); + } + } + } + + /// Restores the tab. + /// The obj tab. + /// The portal settings. + public void RestoreTab(TabInfo tab, PortalSettings portalSettings) + { + if (tab.DefaultLanguageTab != null) + { + // We are trying to restore the child, so recall this function with the master language's tab id + this.RestoreTab(tab.DefaultLanguageTab, portalSettings); + return; + } + + tab.IsDeleted = false; + this.UpdateTab(tab); + + // Restore any localized children + foreach (TabInfo localizedtab in tab.LocalizedTabs.Values) + { + localizedtab.IsDeleted = false; + this.UpdateTab(localizedtab); + } + + EventLogController.Instance.AddLog(tab, portalSettings, portalSettings.UserId, string.Empty, EventLogController.EventLogType.TAB_RESTORED); + + ArrayList allTabsModules = ModuleController.Instance.GetAllTabsModules(tab.PortalID, true); + var tabModules = ModuleController.Instance.GetTabModules(tab.TabID); + foreach (ModuleInfo objModule in allTabsModules) + { + if (!tabModules.ContainsKey(objModule.ModuleID)) + { + ModuleController.Instance.CopyModule(objModule, tab, Null.NullString, true); + } + } + + this.ClearCache(tab.PortalID); + + EventManager.Instance.OnTabRestored(new TabEventArgs { Tab = tab }); + } + + /// Save url information for a page (tab). + /// the tab url. + /// the portal id. + /// whether to clear the cache. + public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) + { + var portalAliasId = (tabUrl.PortalAliasUsage == PortalAliasUsageType.Default) + ? Null.NullInteger + : tabUrl.PortalAliasId; + + var saveLog = EventLogController.EventLogType.TABURL_CREATED; + + if (tabUrl.HttpStatus == "200") + { + saveLog = EventLogController.EventLogType.TABURL_CREATED; + } + else + { + // need to see if sequence number exists to decide if insert or update + List t = this.GetTabUrls(portalId, tabUrl.TabId); + var existingSeq = t.FirstOrDefault(r => r.SeqNum == tabUrl.SeqNum); + if (existingSeq == null) + { + saveLog = EventLogController.EventLogType.TABURL_CREATED; + } + } + + DataProvider.Instance().SaveTabUrl(tabUrl.TabId, tabUrl.SeqNum, portalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.Instance.GetCurrentUserInfo().UserID); + + EventLogController.Instance.AddLog( + "tabUrl", + tabUrl.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + saveLog); + + if (clearCache) + { + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.TabUrlCacheKey, portalId)); + CacheController.ClearCustomAliasesCache(); + this.ClearCache(portalId); + var tab = this.GetTab(tabUrl.TabId, portalId); + tab.ClearTabUrls(); + } + } + + /// + public bool SoftDeleteTab(int tabId, PortalSettings portalSettings) + { + bool deleted; + TabInfo tab = this.GetTab(tabId, portalSettings.PortalId, false); + if (tab != null) + { + if (tab.DefaultLanguageTab != null && LocaleController.Instance.GetLocales(portalSettings.PortalId).ContainsKey(tab.CultureCode)) + { + // We are trying to delete the child, so recall this function with the master language's tab id + return this.SoftDeleteTab(tab.DefaultLanguageTab.TabID, portalSettings); + } + + // Delete the Tab + deleted = this.SoftDeleteTabInternal(tab, portalSettings); + + // Delete any localized children + if (deleted) + { + foreach (TabInfo localizedtab in tab.LocalizedTabs.Values) + { + this.SoftDeleteTabInternal(localizedtab, portalSettings); + } + } + } + else + { + deleted = false; + } + + return deleted; + } + + /// Updates the tab to database. + /// The updated tab. + public void UpdateTab(TabInfo updatedTab) + { + TabInfo originalTab = this.GetTab(updatedTab.TabID, updatedTab.PortalID, true); + + // Update ContentItem If neccessary + if (updatedTab.TabID != Null.NullInteger) + { + if (updatedTab.ContentItemId == Null.NullInteger) + { + this.CreateContentItem(updatedTab); + } + else + { + UpdateContentItem(updatedTab); + } + } + + // Create Tab Redirects + if (originalTab.ParentId != updatedTab.ParentId || originalTab.TabName != updatedTab.TabName) + { + this.CreateTabRedirects(updatedTab); + } + + // Update Tab to DataStore + this.dataProvider.UpdateTab( + updatedTab.TabID, + updatedTab.ContentItemId, + updatedTab.PortalID, + updatedTab.VersionGuid, + updatedTab.DefaultLanguageGuid, + updatedTab.LocalizedVersionGuid, + updatedTab.TabName, + updatedTab.IsVisible, + updatedTab.DisableLink, + updatedTab.ParentId, + updatedTab.IconFileRaw, + updatedTab.IconFileLargeRaw, + updatedTab.Title, + updatedTab.Description, + updatedTab.KeyWords, + updatedTab.IsDeleted, + updatedTab.Url, + updatedTab.SkinSrc, + updatedTab.ContainerSrc, + updatedTab.StartDate, + updatedTab.EndDate, + updatedTab.RefreshInterval, + updatedTab.PageHeadText, + updatedTab.IsSecure, + updatedTab.PermanentRedirect, + updatedTab.SiteMapPriority, + UserController.Instance.GetCurrentUserInfo().UserID, + updatedTab.CultureCode, + updatedTab.IsSystem); + + // Update Tags + List terms = updatedTab.Terms; + ITermController termController = Util.GetTermController(); + termController.RemoveTermsFromContent(updatedTab); + foreach (Term term in terms) + { + termController.AddTermToContent(term, updatedTab); + } + + EventLogController.Instance.AddLog( + updatedTab, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + EventLogController.EventLogType.TAB_UPDATED); + + // Update Tab permissions + TabPermissionController.SaveTabPermissions(updatedTab); + + // Update TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist + try + { + this.UpdateTabSettings(ref updatedTab); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + // Update Tab Version + UpdateTabVersion(updatedTab.TabID); + + // Clear Tab Caches + this.ClearCache(updatedTab.PortalID); + if (updatedTab.PortalID != originalTab.PortalID) + { + this.ClearCache(originalTab.PortalID); + } + + EventManager.Instance.OnTabUpdated(new TabEventArgs { Tab = updatedTab }); + } + + /// Adds or updates a tab's setting value. + /// ID of the tab to update. + /// name of the setting property. + /// value of the setting (String). + /// empty SettingValue will remove the setting, if not preserveIfEmpty is true. + public void UpdateTabSetting(int tabId, string settingName, string settingValue) + { + this.UpdateTabSettingInternal(tabId, settingName, settingValue, true); + } + + /// Updates the translation status. + /// The localized tab. + /// if set to means the tab has already been translated. + public void UpdateTranslationStatus(TabInfo localizedTab, bool isTranslated) + { + if (isTranslated && (localizedTab.DefaultLanguageTab != null)) + { + localizedTab.LocalizedVersionGuid = localizedTab.DefaultLanguageTab.LocalizedVersionGuid; + } + else + { + localizedTab.LocalizedVersionGuid = Guid.NewGuid(); + } + + DataProvider.Instance() + .UpdateTabTranslationStatus( + localizedTab.TabID, + localizedTab.LocalizedVersionGuid, + UserController.Instance.GetCurrentUserInfo().UserID); + + // Clear Tab Caches + this.ClearCache(localizedTab.PortalID); + } + + /// It marks a page as published at least once. + /// The Tab to be marked. + public void MarkAsPublished(TabInfo tab) + { + this.dataProvider.MarkAsPublished(tab.TabID); + + // Clear Tab Caches + this.ClearCache(tab.PortalID); + + EventManager.Instance.OnTabMarkedAsPublished(new TabEventArgs { Tab = tab }); + } + + /// + public bool IsHostOrAdminPage(TabInfo tab) + { + return IsHostTab(tab) || this.IsAdminTab(tab); + } + + internal Dictionary> GetTabUrls(int portalId) + { + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabUrlCacheKey, portalId); + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabUrlCacheTimeOut, + DataCache.TabUrlCachePriority, + portalId), + this.GetTabUrlsCallback); + } + + /// + protected override Func GetFactory() + { + return () => new TabController(); + } + + private static void AddAllTabsModules(TabInfo tab) + { + var portalSettings = new PortalSettings(tab.TabID, tab.PortalID); + foreach (ModuleInfo allTabsModule in ModuleController.Instance.GetAllTabsModules(tab.PortalID, true)) + { + // [DNN-6276]We need to check that the Module is not implicitly deleted. ie If all instances are on Pages + // that are all "deleted" then even if the Module itself is not deleted, we would not expect the + // Module to be added + var canAdd = + (from ModuleInfo allTabsInstance in ModuleController.Instance.GetTabModulesByModule(allTabsModule.ModuleID) select Instance.GetTab(allTabsInstance.TabID, tab.PortalID, false)).Any( + t => !t.IsDeleted) && (!portalSettings.ContentLocalizationEnabled || allTabsModule.CultureCode == tab.CultureCode); + if (canAdd) + { + ModuleController.Instance.CopyModule(allTabsModule, tab, Null.NullString, true); + } + } + } + + private static void DeserializeTabSettings(XmlNodeList nodeTabSettings, TabInfo objTab) + { + foreach (XmlNode oTabSettingNode in nodeTabSettings) + { + string sKey = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingname"); + string sValue = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingvalue"); + objTab.TabSettings[sKey] = sValue; + } + } + + private static void DeserializeTabPermissions(XmlNodeList nodeTabPermissions, TabInfo tab, bool isAdminTemplate) + { + var permissionController = new PermissionController(); + int permissionID = 0; + foreach (XmlNode tabPermissionNode in nodeTabPermissions) + { + string permissionKey = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "permissionkey"); + string permissionCode = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "permissioncode"); + string roleName = XmlUtils.GetNodeValue(tabPermissionNode.CreateNavigator(), "rolename"); + bool allowAccess = XmlUtils.GetNodeValueBoolean(tabPermissionNode, "allowaccess"); + ArrayList arrPermissions = permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey); + int i; + for (i = 0; i <= arrPermissions.Count - 1; i++) + { + var permission = (IPermissionDefinitionInfo)arrPermissions[i]; + permissionID = permission.PermissionId; + } + + int roleID = int.MinValue; + switch (roleName) + { + case Globals.glbRoleAllUsersName: + roleID = Convert.ToInt32(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture); + break; + case Globals.glbRoleUnauthUserName: + roleID = Convert.ToInt32(Globals.glbRoleUnauthUser, CultureInfo.InvariantCulture); + break; + default: + IPortalInfo portal = PortalController.Instance.GetPortal(tab.PortalID); + var role = RoleController.Instance.GetRole( + portal.PortalId, + r => r.RoleName == roleName); + if (role != null) + { + roleID = role.RoleID; + } + else + { + if (isAdminTemplate && roleName.Equals("Administrators", StringComparison.OrdinalIgnoreCase)) + { + roleID = portal.AdministratorRoleId; + } + } + + break; + } + + if (roleID != int.MinValue) + { + var tabPermission = new TabPermissionInfo + { + TabID = tab.TabID, + PermissionID = permissionID, + RoleID = roleID, + UserID = Null.NullInteger, + AllowAccess = allowAccess, + }; + + bool canAdd = !tab.TabPermissions.Cast() + .Any(tp => tp.TabID == tabPermission.TabID + && tp.PermissionID == tabPermission.PermissionID + && tp.RoleID == tabPermission.RoleID + && tp.UserID == tabPermission.UserID); + if (canAdd) + { + tab.TabPermissions.Add(tabPermission); + } + } + } + } + + private static void DeserializeTabUrls(XmlNode nodeTabUrl, TabUrlInfo objTabUrl) + { + objTabUrl.SeqNum = XmlUtils.GetAttributeValueAsInteger(nodeTabUrl.CreateNavigator(), "SeqNum", 0); + objTabUrl.Url = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url")) ? "/" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url"); + objTabUrl.QueryString = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "QueryString"); + objTabUrl.CultureCode = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "CultureCode"); + objTabUrl.HttpStatus = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus")) ? "200" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus"); + objTabUrl.IsSystem = XmlUtils.GetAttributeValueAsBoolean(nodeTabUrl.CreateNavigator(), "IsSystem", true); + objTabUrl.PortalAliasId = Null.NullInteger; + objTabUrl.PortalAliasUsage = PortalAliasUsageType.Default; + } + + private static int GetIndexOfTab(TabInfo objTab, IEnumerable tabs) + { + return Null.NullInteger + tabs.TakeWhile(tab => tab.TabID != objTab.TabID).Count(); + } + + private static int GetPortalId(int tabId, int portalId) + { + if (Null.IsNull(portalId)) + { + var portalDic = PortalController.GetPortalDictionary(); + if (portalDic != null && portalDic.TryGetValue(tabId, out var pid)) + { + portalId = pid; + } + } + + return portalId; + } + + private static object GetTabPathDictionaryCallback(CacheItemArgs cacheItemArgs) + { + string cultureCode = Convert.ToString(cacheItemArgs.ParamList[0], CultureInfo.InvariantCulture); + var portalId = (int)cacheItemArgs.ParamList[1]; + var tabPathDictionary = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + IDataReader dr = DataProvider.Instance().GetTabPaths(portalId, cultureCode); + try + { + while (dr.Read()) + { + tabPathDictionary[Null.SetNullString(dr["TabPath"])] = Null.SetNullInteger(dr["TabID"]); + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + CBO.CloseDataReader(dr, true); + } + + return tabPathDictionary; + } + + private static void UpdateTabVersion(int tabId) + { + DataProvider.Instance().UpdateTabVersion(tabId, Guid.NewGuid()); + } + + private static void ValidateTabPath(TabInfo tab) + { + string tabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); + int tabId = GetTabByTabPath(tab.PortalID, tabPath, tab.CultureCode); + if (tabId > Null.NullInteger) + { + // Tab exists so Throw + throw new TabExistsException( + tabId, + $"Page Exists in portal: {tab.PortalID}, path: {tab.TabPath}, culture: {tab.CultureCode}"); + } + } + + private static void EnableTabVersioningAndWorkflow(TabInfo tab) + { + if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, true); + } + + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) + { + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, true); + } + } + + private static void DisableTabVersioningAndWorkflow(TabInfo tab) + { + if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); + } + + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) + { + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); + } + } + + private static bool IsHostTab(TabInfo tab) + { + return tab.PortalID == Null.NullInteger; + } + + /// update content item for the tab when tab name changed. + /// The updated tab. + private static void UpdateContentItem(TabInfo tab) + { + IContentController contentController = Util.GetContentController(); + var newContent = string.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; + if (tab.Content != newContent) + { + tab.Content = newContent; + contentController.UpdateContentItem(tab); + } + } + + /// + /// Checks if the page is root or has a localized parent. + /// If neither is true, then we cannot create localized version of the page for the given locale. + /// + /// The tab to be checked. + /// The locale to be checked. + /// Whether the tab can be localized to the locale. + private bool CanLocalizeTabToLocale(TabInfo tab, Locale locale) + { + // If root page, can be localized + if (Null.IsNull(tab.ParentId)) + { + return true; + } + + // Otherwise can be localized only if localized parent is found + TabInfo parent = this.GetTab(tab.ParentId, tab.PortalID, false); + TabInfo localizedParent = this.GetTabByCulture(parent.TabID, parent.PortalID, locale); + return localizedParent != null; + } + + private bool IsAdminTab(TabInfo tab) + { + var portal = PortalController.Instance.GetPortal(tab.PortalID); + return portal.AdminTabId == tab.TabID || this.IsAdminTabRecursive(tab, portal.AdminTabId); + } + + private bool IsAdminTabRecursive(TabInfo tab, int adminTabId) + { + if (tab.ParentId == Null.NullInteger) + { + return false; + } + + if (tab.ParentId == adminTabId) + { + return true; + } + + var parentTab = this.GetTab(tab.ParentId, tab.PortalID); + return this.IsAdminTabRecursive(parentTab, adminTabId); + } + + private int AddTabInternal(TabInfo tab, int afterTabId, int beforeTabId, bool includeAllTabsModules) + { + ValidateTabPath(tab); + + // First create ContentItem as we need the ContentItemID + this.CreateContentItem(tab); + + // Add Tab + if (afterTabId > 0) + { + tab.TabID = this.dataProvider.AddTabAfter(tab, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); + } + else + { + tab.TabID = beforeTabId > 0 + ? this.dataProvider.AddTabBefore(tab, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID) + : this.dataProvider.AddTabToEnd(tab, UserController.Instance.GetCurrentUserInfo().UserID); + } + + // Clear the Cache + this.ClearCache(tab.PortalID); + + ITermController termController = Util.GetTermController(); + termController.RemoveTermsFromContent(tab); + foreach (Term term in tab.Terms) + { + termController.AddTermToContent(term, tab); + } + + EventLogController.Instance.AddLog( + tab, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + EventLogController.EventLogType.TAB_CREATED); + + // Add Tab Permissions + TabPermissionController.SaveTabPermissions(tab); + + // Add TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist + try + { + this.UpdateTabSettings(ref tab); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + // Add AllTabs Modules + if (includeAllTabsModules && tab.PortalID != Null.NullInteger) + { + AddAllTabsModules(tab); + } + + // Check Tab Versioning + if (tab.PortalID == Null.NullInteger || !TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID, tab.TabID)) + { + this.MarkAsPublished(tab); + } + + EventManager.Instance.OnTabCreated(new TabEventArgs { Tab = tab }); + + return tab.TabID; + } + + private void CreateLocalizedCopyInternal(TabInfo originalTab, Locale locale, bool allTabsModulesFromDefault, bool clearCache, bool insertAfterOriginal = false) + { + try + { + Logger.TraceFormat(CultureInfo.InvariantCulture, "Localizing TabId: {0}, TabPath: {1}, Locale: {2}", originalTab.TabID, originalTab.TabPath, locale.Code); + var defaultLocale = LocaleController.Instance.GetDefaultLocale(originalTab.PortalID); + + // First Clone the Tab + TabInfo localizedCopy = originalTab.Clone(); + localizedCopy.TabID = Null.NullInteger; + localizedCopy.StateID = Null.NullInteger; + localizedCopy.ContentItemId = Null.NullInteger; + + // Set Guids and Culture Code + localizedCopy.UniqueId = Guid.NewGuid(); + localizedCopy.VersionGuid = Guid.NewGuid(); + localizedCopy.LocalizedVersionGuid = Guid.NewGuid(); + localizedCopy.CultureCode = locale.Code; + localizedCopy.TabName = localizedCopy.TabName + " (" + locale.Code + ")"; + + // copy page tags + foreach (var term in originalTab.Terms) + { + localizedCopy.Terms.Add(term); + } + + if (locale == defaultLocale) + { + originalTab.DefaultLanguageGuid = localizedCopy.UniqueId; + this.UpdateTab(originalTab); + } + else + { + localizedCopy.DefaultLanguageGuid = originalTab.UniqueId; + } + + // Copy Permissions from original Tab for Admins only + // If original tab is user tab or its parent tab is user tab, then copy full permission + // from original tab. + PortalInfo portal = PortalController.Instance.GetPortal(originalTab.PortalID); + if (originalTab.TabID == portal.UserTabId || originalTab.ParentId == portal.UserTabId) + { + localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions); + } + else + { + localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions.Where(p => p.RoleID == portal.AdministratorRoleId)); + } + + // Get the original Tabs Parent + // check the original whether have parent. + if (!Null.IsNull(originalTab.ParentId)) + { + TabInfo originalParent = this.GetTab(originalTab.ParentId, originalTab.PortalID, false); + + // Get the localized parent + TabInfo localizedParent = this.GetTabByCulture(originalParent.TabID, originalParent.PortalID, locale); + localizedCopy.ParentId = localizedParent.TabID; + } + + // Save Tab + var afterTabId = insertAfterOriginal ? originalTab.TabID : -1; + const int beforeTabId = -1; + const bool includeAllModules = false; + this.AddTabInternal(localizedCopy, afterTabId, beforeTabId, includeAllModules); // not include modules show on all page, it will handled in copy modules action. + + // if the tab has custom stylesheet defined, then also copy the stylesheet to the localized version. + if (originalTab.TabSettings.ContainsKey("CustomStylesheet")) + { + this.UpdateTabSetting(localizedCopy.TabID, "CustomStylesheet", originalTab.TabSettings["CustomStylesheet"].ToString()); + } + + /* Tab versioning and workflow is disabled + * during the creation of the Localized copy + */ + DisableTabVersioningAndWorkflow(localizedCopy); + + // Make shallow copies of all modules + ModuleController.Instance.CopyModules(originalTab, localizedCopy, true, allTabsModulesFromDefault); + + // Convert these shallow copies to deep copies + foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(localizedCopy.TabID)) + { + ModuleController.Instance.LocalizeModule(kvp.Value, locale); + } + + // if not copy modules which show on all pages from default language, we need add all modules in current culture. + if (!allTabsModulesFromDefault) + { + AddAllTabsModules(localizedCopy); + } + + // Add Translator Role + this.GiveTranslatorRoleEditRights(localizedCopy, null); + + /* Tab versioning and workflow is re-enabled + * when the Localized copy is created + */ + EnableTabVersioningAndWorkflow(localizedCopy); + this.MarkAsPublished(localizedCopy); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + throw; + } + + // Clear the Cache + if (clearCache) + { + this.ClearCache(originalTab.PortalID); + } + } + + /// If a parent tab is localized, its localized children need to be updated to point at their corresponding localized parents. + /// The portal ID. + /// The parent tab ID. + private void UpdateChildTabLocalizedParents(int portalId, int parentTabId) + { + var childTabs = GetTabsByParent(parentTabId, portalId); + + foreach (var childTab in childTabs) + { + if (childTab.CultureCode == null) + { + continue; + } + + var locale = LocaleController.Instance.GetLocale(portalId, childTab.CultureCode); + + if (locale == null) + { + continue; + } + + TabInfo localizedParent = this.GetTabByCulture(parentTabId, portalId, locale); + if (childTab.ParentId != localizedParent.TabID) + { + childTab.ParentId = localizedParent.TabID; + + this.UpdateTab(childTab); + + this.UpdateChildTabLocalizedParents(portalId, childTab.TabID); + } + } + } + + private void ClearTabSettingsCache(int tabId) + { + var portalId = GetPortalId(tabId, -1); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabSettingsCacheKey, portalId); + DataCache.RemoveCache(cacheKey); + + // also clear the settings from tab object in cache. + var tab = this.GetTab(tabId, portalId, false); + tab?.ClearSettingsCache(); + } + + private void CreateTabRedirect(TabInfo tab) + { + var settings = PortalController.Instance.GetCurrentPortalSettings(); + + if (settings != null && tab.TabID != settings.HomeTabId && tab.TabUrls.All(u => u.HttpStatus != "200")) + { + var domainRoot = TestableGlobals.Instance.AddHTTP(settings.PortalAlias.HTTPAlias); + + if (!string.IsNullOrEmpty(domainRoot)) + { + var url = TestableGlobals.Instance.NavigateURL(tab.TabID); + + url = url.Replace(domainRoot, string.Empty); + + var seqNum = (tab.TabUrls.Count > 0) ? tab.TabUrls.Max(t => t.SeqNum) + 1 : 1; + var tabUrl = new TabUrlInfo + { + TabId = tab.TabID, + SeqNum = seqNum, + PortalAliasId = -1, + PortalAliasUsage = PortalAliasUsageType.Default, + Url = url, + QueryString = string.Empty, + CultureCode = tab.CultureCode, + HttpStatus = "301", + IsSystem = true, + }; + + this.SaveTabUrl(tabUrl, tab.PortalID, false); + } + } + } + + private void CreateTabRedirects(TabInfo tab) + { + this.CreateTabRedirect(tab); + + var descendants = this.GetTabsByPortal(tab.PortalID).DescendentsOf(tab.TabID); + + // Create Redirect for descendant tabs + foreach (TabInfo descendantTab in descendants) + { + this.CreateTabRedirect(descendantTab); + } + } + + private Dictionary> GetAliasSkins(int portalId) + { + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabAliasSkinCacheKey, portalId); + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabAliasSkinCacheTimeOut, + DataCache.TabAliasSkinCachePriority, + portalId), + this.GetAliasSkinsCallback); + } + + private object GetAliasSkinsCallback(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + var dic = new Dictionary>(); + if (portalId > -1) + { + IDataReader dr = DataProvider.Instance().GetTabAliasSkins(portalId); + try + { + while (dr.Read()) + { + // fill business object + var tabAliasSkin = CBO.FillObject(dr, false); + + // add Tab Alias Skin to dictionary + if (dic.TryGetValue(tabAliasSkin.TabId, out var tabAliasSkins)) + { + tabAliasSkins.Add(tabAliasSkin); + } + else + { + // Create new Tab Alias Skin Collection for TabId + var collection = new List { tabAliasSkin, }; + + // Add Collection to Dictionary + dic.Add(tabAliasSkin.TabId, collection); + } + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); + } + } + + return dic; + } + + private Dictionary> GetCustomAliases(int portalId) + { + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabCustomAliasCacheKey, portalId); + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabCustomAliasCacheTimeOut, + DataCache.TabCustomAliasCachePriority, + portalId), + this.GetCustomAliasesCallback); + } + + private object GetCustomAliasesCallback(CacheItemArgs cacheItemArgs) + { + var portalID = (int)cacheItemArgs.ParamList[0]; + var dic = new Dictionary>(); + if (portalID > -1) + { + IDataReader dr = DataProvider.Instance().GetTabCustomAliases(portalID); + try + { + while (dr.Read()) + { + // fill business object + var tabId = (int)dr["TabId"]; + var customAlias = (string)dr["httpAlias"]; + var cultureCode = (string)dr["cultureCode"]; + + // add Custom Alias to dictionary + if (dic.TryGetValue(tabId, out var aliases)) + { + aliases[cultureCode] = customAlias; + } + else + { + // Create new Custom Alias Collection for TabId + var collection = new Dictionary { { cultureCode, customAlias } }; + + // Add Collection to Dictionary + dic.Add(tabId, collection); + } + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); + } + } + + return dic; + } + + private List GetSiblingTabs(TabInfo objTab) + { + return this.GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, true).WithParentId(objTab.ParentId); + } + + private Dictionary GetTabSettingsByPortal(int portalId) + { + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabSettingsCacheKey, portalId); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.TabCacheTimeOut, + DataCache.TabCachePriority), + c => + { + var tabSettings = new Dictionary(); + using (var dr = this.dataProvider.GetTabSettings(portalId)) + { + while (dr.Read()) + { + int tabId = dr.GetInt32(0); + Hashtable settings; + if (!tabSettings.TryGetValue(tabId, out settings)) + { + settings = new Hashtable(); + tabSettings[tabId] = settings; + } + + if (!dr.IsDBNull(2)) + { + settings[dr.GetString(1)] = dr.GetString(2); + } + else + { + settings[dr.GetString(1)] = string.Empty; + } + } + } + + return tabSettings; + }); + } + + private object GetTabUrlsCallback(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + var dic = new Dictionary>(); + + if (portalId > -1) + { + IDataReader dr = DataProvider.Instance().GetTabUrls(portalId); + try + { + while (dr.Read()) + { + // fill business object + var tabRedirect = CBO.FillObject(dr, false); + + // add Tab Redirect to dictionary + if (dic.TryGetValue(tabRedirect.TabId, out var tabUrls)) + { + tabUrls.Add(tabRedirect); + } + else + { + // Create new Tab Redirect Collection for TabId + var collection = new List { tabRedirect, }; + + // Add Collection to Dictionary + dic.Add(tabRedirect.TabId, collection); + } + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); + } + } + + return dic; + } + + private void HardDeleteTabInternal(int tabId, int portalId) + { + // Delete all tabModule Instances + foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabId).Values) + { + ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, false); + } + + var tab = this.GetTab(tabId, portalId, false); + + // Delete Tab + this.dataProvider.DeleteTab(tabId); + + // Log deletion + EventLogController.Instance.AddLog( + "TabID", + tabId.ToString(CultureInfo.InvariantCulture), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.TAB_DELETED); + + // queue remove tab/page from search index + var document = new SearchDocumentToDelete + { + TabId = tabId, + }; + + DataProvider.Instance().AddSearchDeletedItems(document); + + // Remove the Content Item + if (tab != null && tab.ContentItemId > Null.NullInteger) + { + IContentController contentController = Util.GetContentController(); + contentController.DeleteContentItem(tab); + } + + if (tab != null) + { + EventManager.Instance.OnTabDeleted(new TabEventArgs { Tab = tab }); + } + } + + private bool SoftDeleteChildTabs(int intTabid, PortalSettings portalSettings) + { + bool bDeleted = true; + foreach (TabInfo objtab in GetTabsByParent(intTabid, portalSettings.PortalId)) + { + bDeleted = this.SoftDeleteTabInternal(objtab, portalSettings); + if (!bDeleted) + { + break; + } + } + + return bDeleted; + } + + private bool SoftDeleteTabInternal(TabInfo tabToDelete, PortalSettings portalSettings) + { + Dto.ChangeControlState changeControlStateForTab = null; + if (tabToDelete.PortalID > -1) + { + changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState( + tabToDelete.PortalID, + tabToDelete.TabID); + if (changeControlStateForTab.IsChangeControlEnabledForTab) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tabToDelete.TabID, false); + TabWorkflowSettings.Instance.SetWorkflowEnabled(tabToDelete.PortalID, tabToDelete.TabID, false); + } + } + + var deleted = false; + if (!IsSpecialTab(tabToDelete.TabID, portalSettings)) + { + if (this.SoftDeleteChildTabs(tabToDelete.TabID, portalSettings)) + { + tabToDelete.IsDeleted = true; + this.UpdateTab(tabToDelete); + + foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabToDelete.TabID).Values) + { + ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, true); + } + + EventLogController.Instance.AddLog( + tabToDelete, + portalSettings, + portalSettings.UserId, + string.Empty, + EventLogController.EventLogType.TAB_SENT_TO_RECYCLE_BIN); + deleted = true; + + EventManager.Instance.OnTabRemoved(new TabEventArgs { Tab = tabToDelete }); + } + } + + if (changeControlStateForTab != null && changeControlStateForTab.IsChangeControlEnabledForTab) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tabToDelete.TabID, changeControlStateForTab.IsVersioningEnabledForTab); + TabWorkflowSettings.Instance.SetWorkflowEnabled(tabToDelete.PortalID, tabToDelete.TabID, changeControlStateForTab.IsWorkflowEnabledForTab); + } + + return deleted; + } + + private void UpdateTabSettingInternal(int tabId, string settingName, string settingValue, bool clearCache) + { + using (var dr = this.dataProvider.GetTabSetting(tabId, settingName)) + { + if (dr.Read()) + { + if (dr.GetString(0) != settingValue) + { + this.dataProvider.UpdateTabSetting( + tabId, + settingName, + settingValue, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.TAB_SETTING_UPDATED, + "TabId", + tabId, + settingName, + settingValue, + UserController.Instance.GetCurrentUserInfo().UserID); + } + } + else + { + this.dataProvider.UpdateTabSetting( + tabId, + settingName, + settingValue, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.TAB_SETTING_CREATED, + "TabId", + tabId, + settingName, + settingValue, + UserController.Instance.GetCurrentUserInfo().UserID); + } + + dr.Close(); + } + + UpdateTabVersion(tabId); + if (clearCache) + { + this.ClearTabSettingsCache(tabId); + } + } + + private void UpdateTabSettings(ref TabInfo updatedTab) + { + foreach (string sKeyLoopVariable in updatedTab.TabSettings.Keys) + { + this.UpdateTabSettingInternal( + updatedTab.TabID, + sKeyLoopVariable, + Convert.ToString(updatedTab.TabSettings[sKeyLoopVariable], CultureInfo.InvariantCulture), + false); + } + } + } +} diff --git a/DNN Platform/Library/Entities/Tabs/TabInfo.cs b/DNN Platform/Library/Entities/Tabs/TabInfo.cs index ff5be7180cd..64e7e8dfb33 100644 --- a/DNN Platform/Library/Entities/Tabs/TabInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabInfo.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Entities.Tabs using System.Collections; using System.Collections.Generic; using System.Data; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; @@ -386,7 +387,7 @@ public string FullUrl break; case TabType.Tab: // alternate tab url - fullUrl = TestableGlobals.Instance.NavigateURL(Convert.ToInt32(this.Url)); + fullUrl = TestableGlobals.Instance.NavigateURL(Convert.ToInt32(this.Url, CultureInfo.InvariantCulture)); break; case TabType.File: // file url @@ -699,6 +700,7 @@ public string SkinDoctype public bool UseBaseFriendlyUrls { get; set; } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { string outputFormat = string.Empty; @@ -851,7 +853,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format break; case "sitemappriority": propertyNotFound = false; - result = PropertyAccess.FormatString(this.SiteMapPriority.ToString(), format); + result = PropertyAccess.FormatString(this.SiteMapPriority.ToString(formatProvider), format); break; } @@ -1093,16 +1095,16 @@ private XmlDocument LoadDocType() private void IconFileGetter(ref string iconFile, string iconRaw) { - if ((!string.IsNullOrEmpty(iconRaw) && iconRaw.StartsWith("~")) || this.PortalID == Null.NullInteger) + if ((!string.IsNullOrEmpty(iconRaw) && iconRaw.StartsWith("~", StringComparison.Ordinal)) || this.PortalID == Null.NullInteger) { iconFile = iconRaw; } else if (iconFile == null && !string.IsNullOrEmpty(iconRaw) && this.PortalID != Null.NullInteger) { IFileInfo fileInfo; - if (iconRaw.StartsWith("FileID=", StringComparison.InvariantCultureIgnoreCase)) + if (iconRaw.StartsWith("FileID=", StringComparison.OrdinalIgnoreCase)) { - var fileId = Convert.ToInt32(iconRaw.Substring(7)); + var fileId = Convert.ToInt32(iconRaw.Substring(7), CultureInfo.InvariantCulture); fileInfo = FileManager.Instance.GetFile(fileId); } else diff --git a/DNN Platform/Library/Entities/Tabs/TabModulesController.cs b/DNN Platform/Library/Entities/Tabs/TabModulesController.cs index 09d1804804e..c6395b0bd2b 100644 --- a/DNN Platform/Library/Entities/Tabs/TabModulesController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabModulesController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Tabs using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -64,7 +65,7 @@ public Dictionary GetTabModuleSettingsByName(string settingName) { var portalId = PortalSettings.Current.PortalId; var dataProvider = DataProvider.Instance(); - var cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabModuleSettingsNameCacheKey, portalId, settingName); var cachedItems = CBO.GetCachedObject>( new CacheItemArgs(cacheKey, DataCache.TabModuleCacheTimeOut, DataCache.TabModuleCachePriority), c => diff --git a/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs b/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs index b49e872ada0..a54fc505c41 100644 --- a/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Entities.Tabs using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -24,11 +25,11 @@ public class TabPublishingController : ServiceLocator public bool IsTabPublished(int tabID, int portalID) { - var allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); + var allUsersRoleId = int.Parse(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture); var tab = TabController.Instance.GetTab(tabID, portalID); var existPermission = GetAlreadyPermission(tab, "VIEW", allUsersRoleId); - return existPermission != null && existPermission.AllowAccess; + return existPermission is { AllowAccess: true, }; } /// @@ -65,14 +66,14 @@ public bool CanPublishingBePerformed(int tabID, int portalID) Hashtable settings = TabController.Instance.GetTabSettings(tabID); if (settings["WorkflowID"] != null) { - return Convert.ToInt32(settings["WorkflowID"]) == 1; // If workflowID is 1, then the Page workflow is Direct Publish + return Convert.ToInt32(settings["WorkflowID"], CultureInfo.InvariantCulture) == 1; // If workflowID is 1, then the Page workflow is Direct Publish } // If workflowID is 1, then the Page workflow is Direct Publish // If WorkflowID is -1, then there is no Workflow setting - var workflowID = Convert.ToInt32(PortalController.GetPortalSetting("WorkflowID", portalID, "-1")); + var workflowId = Convert.ToInt32(PortalController.GetPortalSetting("WorkflowID", portalID, "-1"), CultureInfo.InvariantCulture); - return workflowID is 1 or -1; + return workflowId is 1 or -1; } /// @@ -83,7 +84,7 @@ protected override Func GetFactory() private static void PublishTabInternal(TabInfo tab) { - var allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); + var allUsersRoleId = int.Parse(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture); var existPermission = GetAlreadyPermission(tab, "VIEW", allUsersRoleId); if (existPermission != null) diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs index f0e41bf872b..eb50472def3 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Tabs.TabVersions { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Entities.Modules; @@ -85,6 +86,7 @@ public interface ITabVersionBuilder /// Get the latest version or 1 if module is not versionable. /// The ModuleInfo to be queried. /// The latest version of the module. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] int GetModuleContentLatestVersion(ModuleInfo module); } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs index 79d91527ec6..8468339c346 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs @@ -6,6 +6,8 @@ namespace DotNetNuke.Entities.Tabs.TabVersions using System; using System.Collections.Generic; using System.Data.SqlClient; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using DotNetNuke.Abstractions.Modules; @@ -85,12 +87,12 @@ public void Publish(int portalId, int tabId, int createdByUserId) var tabVersion = this.GetUnPublishedVersion(tabId); if (tabVersion == null) { - throw new InvalidOperationException(string.Format(Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); } if (tabVersion.IsPublished) { - throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); } var previousPublishVersion = this.GetCurrentVersion(tabId); @@ -109,12 +111,12 @@ public void Discard(int tabId, int createdByUserId) var tabVersion = this.GetUnPublishedVersion(tabId); if (tabVersion == null) { - throw new InvalidOperationException(string.Format(Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); } if (tabVersion.IsPublished) { - throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); } this.DiscardVersion(tabId, tabVersion); @@ -129,19 +131,20 @@ public void DeleteVersion(int tabId, int createdByUserId, int version) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public TabVersion RollBackVesion(int tabId, int createdByUserId, int version) { this.CheckVersioningEnabled(tabId); if (this.GetUnPublishedVersion(tabId) != null) { - throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeRolledBack_UnpublishedVersionExists", Localization.ExceptionsResourceFile), tabId, version)); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("TabVersionCannotBeRolledBack_UnpublishedVersionExists", Localization.ExceptionsResourceFile), tabId, version)); } var lastTabVersion = this.tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version).FirstOrDefault(); if (lastTabVersion == null || lastTabVersion.Version == version) { - throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeRolledBack_LastVersion", Localization.ExceptionsResourceFile), tabId, version)); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("TabVersionCannotBeRolledBack_LastVersion", Localization.ExceptionsResourceFile), tabId, version)); } var publishedDetails = this.GetVersionModulesDetails(tabId, lastTabVersion.Version).ToArray(); @@ -161,7 +164,7 @@ public TabVersion RollBackVesion(int tabId, int createdByUserId, int version) } catch (DnnTabVersionException e) { - Logger.Error(string.Format("There was a problem making rollbak of the module {0}. Message: {1}.", rollbackDetail.ModuleId, e.Message)); + Logger.Error($"There was a problem making rollback of the module {rollbackDetail.ModuleId}. Message: {e.Message}."); continue; } @@ -212,12 +215,12 @@ public TabVersion CreateNewVersion(int portalid, int tabId, int createdByUserId) catch (InvalidOperationException e) { Services.Exceptions.Exceptions.LogException(e); - throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExistsConcurrencyProblem", Localization.ExceptionsResourceFile), tabId), e); + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExistsConcurrencyProblem", Localization.ExceptionsResourceFile), tabId), e); } catch (SqlException sqlException) { Services.Exceptions.Exceptions.LogException(sqlException); - throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExistsConcurrencyProblem", Localization.ExceptionsResourceFile), tabId)); + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExistsConcurrencyProblem", Localization.ExceptionsResourceFile), tabId)); } } @@ -250,7 +253,7 @@ public TabVersion GetUnPublishedVersion(int tabId) /// public IEnumerable GetCurrentModules(int tabId) { - var cacheKey = string.Format(DataCache.PublishedTabModuleCacheKey, tabId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PublishedTabModuleCacheKey, tabId); return CBO.GetCachedObject>( new CacheItemArgs( cacheKey, @@ -260,6 +263,7 @@ public IEnumerable GetCurrentModules(int tabId) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public IEnumerable GetVersionModules(int tabId, int version) { return this.ConvertToModuleInfo(this.GetVersionModulesDetails(tabId, version), tabId); @@ -463,9 +467,8 @@ private void ForceDeleteVersion(int tabId, int version) { throw new InvalidOperationException( string.Format( - Localization.GetString( - "TabVersionCannotBeDeleted_UnpublishedVersion", - Localization.ExceptionsResourceFile), + CultureInfo.InvariantCulture, + Localization.GetString("TabVersionCannotBeDeleted_UnpublishedVersion", Localization.ExceptionsResourceFile), tabId, version)); } @@ -475,9 +478,8 @@ private void ForceDeleteVersion(int tabId, int version) { throw new InvalidOperationException( string.Format( - Localization.GetString( - "TabVersionCannotBeDiscarded_OnlyOneVersion", - Localization.ExceptionsResourceFile), + CultureInfo.InvariantCulture, + Localization.GetString("TabVersionCannotBeDiscarded_OnlyOneVersion", Localization.ExceptionsResourceFile), tabId, version)); } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs index 180690df4c5..5091cb1d11e 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs @@ -6,6 +6,8 @@ namespace DotNetNuke.Entities.Tabs.TabVersions { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -52,12 +54,14 @@ public void SaveTabVersion(TabVersion tabVersion) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void SaveTabVersion(TabVersion tabVersion, int createdByUserID) { this.SaveTabVersion(tabVersion, createdByUserID, createdByUserID); } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void SaveTabVersion(TabVersion tabVersion, int createdByUserID, int modifiedByUserID) { tabVersion.TabVersionId = Provider.SaveTabVersion(tabVersion.TabVersionId, tabVersion.TabId, tabVersion.TimeStamp, tabVersion.Version, tabVersion.IsPublished, createdByUserID, modifiedByUserID); @@ -65,6 +69,7 @@ public void SaveTabVersion(TabVersion tabVersion, int createdByUserID, int modif } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public TabVersion CreateTabVersion(int tabId, int createdByUserID, bool isPublished = false) { var lastTabVersion = this.GetTabVersions(tabId).OrderByDescending(tv => tv.Version).FirstOrDefault(); @@ -74,7 +79,7 @@ public TabVersion CreateTabVersion(int tabId, int createdByUserID, bool isPublis { if (!lastTabVersion.IsPublished && !isPublished) { - throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExists", Localization.ExceptionsResourceFile))); + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExists", Localization.ExceptionsResourceFile))); } newVersion = lastTabVersion.Version + 1; @@ -107,7 +112,7 @@ protected override Func GetFactory() private static string GetTabVersionsCacheKey(int tabId) { - return string.Format(DataCache.TabVersionsCacheKey, tabId); + return string.Format(CultureInfo.InvariantCulture, DataCache.TabVersionsCacheKey, tabId); } private static void ClearCache(int tabId) diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs index e13ebf33a5d..93bb5d5f9dc 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs @@ -5,6 +5,8 @@ namespace DotNetNuke.Entities.Tabs.TabVersions { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -52,12 +54,14 @@ public void SaveTabVersionDetail(TabVersionDetail tabVersionDetail) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void SaveTabVersionDetail(TabVersionDetail tabVersionDetail, int createdByUserID) { this.SaveTabVersionDetail(tabVersionDetail, createdByUserID, createdByUserID); } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void SaveTabVersionDetail(TabVersionDetail tabVersionDetail, int createdByUserID, int modifiedByUserID) { tabVersionDetail.TabVersionDetailId = Provider.SaveTabVersionDetail( @@ -94,7 +98,7 @@ protected override System.Func GetFactory() private static string GetTabVersionDetailCacheKey(int tabVersionId) { - return string.Format(DataCache.TabVersionDetailsCacheKey, tabVersionId); + return string.Format(CultureInfo.InvariantCulture, DataCache.TabVersionDetailsCacheKey, tabVersionId); } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs index 729a64fdd1a..39268380829 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs @@ -2,95 +2,95 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs.TabVersions -{ - using System; - using System.Globalization; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Framework; - - public class TabVersionSettings : ServiceLocator, ITabVersionSettings - { - private const int TabVersionsMaxNumber = 5; - private const string TabVersionQueryStringParam = "DnnTabVersion"; +namespace DotNetNuke.Entities.Tabs.TabVersions +{ + using System; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + + public class TabVersionSettings : ServiceLocator, ITabVersionSettings + { + private const int TabVersionsMaxNumber = 5; + private const string TabVersionQueryStringParam = "DnnTabVersion"; private const string TabVersioningSettingKey = "TabVersioningSettingKey"; /// - public int GetMaxNumberOfVersions(int portalId) - { - Requires.NotNegative("portalId", portalId); - return portalId == Null.NullInteger ? TabVersionsMaxNumber : PortalController.GetPortalSettingAsInteger("TabVersionsMaxNumber", portalId, TabVersionsMaxNumber); + public int GetMaxNumberOfVersions(int portalId) + { + Requires.NotNegative("portalId", portalId); + return portalId == Null.NullInteger ? TabVersionsMaxNumber : PortalController.GetPortalSettingAsInteger("TabVersionsMaxNumber", portalId, TabVersionsMaxNumber); } /// - public void SetMaxNumberOfVersions(int portalId, int maxNumberOfVersions) - { - Requires.NotNegative("portalId", portalId); - PortalController.UpdatePortalSetting(portalId, "TabVersionsMaxNumber", maxNumberOfVersions.ToString(CultureInfo.InvariantCulture)); + public void SetMaxNumberOfVersions(int portalId, int maxNumberOfVersions) + { + Requires.NotNegative("portalId", portalId); + PortalController.UpdatePortalSetting(portalId, "TabVersionsMaxNumber", maxNumberOfVersions.ToString(CultureInfo.InvariantCulture)); } /// - public void SetEnabledVersioningForPortal(int portalId, bool enabled) - { - Requires.NotNegative("portalId", portalId); - PortalController.UpdatePortalSetting(portalId, "TabVersionsEnabled", enabled.ToString(CultureInfo.InvariantCulture)); + public void SetEnabledVersioningForPortal(int portalId, bool enabled) + { + Requires.NotNegative("portalId", portalId); + PortalController.UpdatePortalSetting(portalId, "TabVersionsEnabled", enabled.ToString(CultureInfo.InvariantCulture)); } /// - public void SetEnabledVersioningForTab(int tabId, bool enabled) - { - Requires.NotNegative("tabId", tabId); - - TabController.Instance.UpdateTabSetting(tabId, TabVersioningSettingKey, enabled.ToString(CultureInfo.InvariantCulture)); + public void SetEnabledVersioningForTab(int tabId, bool enabled) + { + Requires.NotNegative("tabId", tabId); + + TabController.Instance.UpdateTabSetting(tabId, TabVersioningSettingKey, enabled.ToString(CultureInfo.InvariantCulture)); } /// - public bool IsVersioningEnabled(int portalId) - { - Requires.NotNegative("portalId", portalId); - return - Convert.ToBoolean(PortalController.GetPortalSetting("TabVersionsEnabled", portalId, bool.FalseString)); + public bool IsVersioningEnabled(int portalId) + { + Requires.NotNegative("portalId", portalId); + return + Convert.ToBoolean(PortalController.GetPortalSetting("TabVersionsEnabled", portalId, bool.FalseString)); } /// - public bool IsVersioningEnabled(int portalId, int tabId) - { - Requires.NotNegative("portalId", portalId); - Requires.NotNegative("tabId", tabId); - - if (!this.IsVersioningEnabled(portalId)) - { - return false; - } - - var tabInfo = TabController.Instance.GetTab(tabId, portalId); - var isHostOrAdminPage = TabController.Instance.IsHostOrAdminPage(tabInfo); - if (isHostOrAdminPage) - { - return false; - } - - var settings = TabController.Instance.GetTabSettings(tabId); - var isVersioningEnableForTab = settings[TabVersioningSettingKey] == null - || Convert.ToBoolean(settings[TabVersioningSettingKey]); - - return isVersioningEnableForTab; + public bool IsVersioningEnabled(int portalId, int tabId) + { + Requires.NotNegative("portalId", portalId); + Requires.NotNegative("tabId", tabId); + + if (!this.IsVersioningEnabled(portalId)) + { + return false; + } + + var tabInfo = TabController.Instance.GetTab(tabId, portalId); + var isHostOrAdminPage = TabController.Instance.IsHostOrAdminPage(tabInfo); + if (isHostOrAdminPage) + { + return false; + } + + var settings = TabController.Instance.GetTabSettings(tabId); + var isVersioningEnableForTab = settings[TabVersioningSettingKey] == null + || Convert.ToBoolean(settings[TabVersioningSettingKey], CultureInfo.InvariantCulture); + + return isVersioningEnableForTab; } /// - public string GetTabVersionQueryStringParameter(int portalId) - { - Requires.NotNegative("portalId", portalId); - return PortalController.GetPortalSetting("TabVersionQueryStringParameter", portalId, TabVersionQueryStringParam); + public string GetTabVersionQueryStringParameter(int portalId) + { + Requires.NotNegative("portalId", portalId); + return PortalController.GetPortalSetting("TabVersionQueryStringParameter", portalId, TabVersionQueryStringParam); } /// - protected override Func GetFactory() - { - return () => new TabVersionSettings(); - } - } -} + protected override Func GetFactory() + { + return () => new TabVersionSettings(); + } + } +} diff --git a/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs b/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs index e357bc9aeb9..9a1f1350726 100644 --- a/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs @@ -2,99 +2,99 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs -{ - using System; - using System.Globalization; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Content.Workflow; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Framework; - - public class TabWorkflowSettings : ServiceLocator, ITabWorkflowSettings - { - private const string DefaultTabWorkflowKey = "DefaultTabWorkflowKey"; - private const string TabWorkflowEnableKey = "TabWorkflowEnabledKey"; - private readonly ITabController tabController; +namespace DotNetNuke.Entities.Tabs +{ + using System; + using System.Globalization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + + public class TabWorkflowSettings : ServiceLocator, ITabWorkflowSettings + { + private const string DefaultTabWorkflowKey = "DefaultTabWorkflowKey"; + private const string TabWorkflowEnableKey = "TabWorkflowEnabledKey"; + private readonly ITabController tabController; private readonly ISystemWorkflowManager systemWorkflowManager; /// Initializes a new instance of the class. - public TabWorkflowSettings() - { - this.tabController = TabController.Instance; - this.systemWorkflowManager = SystemWorkflowManager.Instance; + public TabWorkflowSettings() + { + this.tabController = TabController.Instance; + this.systemWorkflowManager = SystemWorkflowManager.Instance; } /// - public int GetDefaultTabWorkflowId(int portalId) - { - var workflowId = PortalController.GetPortalSettingAsInteger(DefaultTabWorkflowKey, portalId, Null.NullInteger); - if (workflowId == Null.NullInteger) - { - var workflow = this.systemWorkflowManager.GetDirectPublishWorkflow(portalId); - workflowId = (workflow != null) ? workflow.WorkflowID : Null.NullInteger; - if (workflowId != Null.NullInteger) - { - PortalController.UpdatePortalSetting(portalId, DefaultTabWorkflowKey, workflowId.ToString(CultureInfo.InvariantCulture), true); - } - } - - return workflowId; + public int GetDefaultTabWorkflowId(int portalId) + { + var workflowId = PortalController.GetPortalSettingAsInteger(DefaultTabWorkflowKey, portalId, Null.NullInteger); + if (workflowId == Null.NullInteger) + { + var workflow = this.systemWorkflowManager.GetDirectPublishWorkflow(portalId); + workflowId = (workflow != null) ? workflow.WorkflowID : Null.NullInteger; + if (workflowId != Null.NullInteger) + { + PortalController.UpdatePortalSetting(portalId, DefaultTabWorkflowKey, workflowId.ToString(CultureInfo.InvariantCulture), true); + } + } + + return workflowId; } /// - public void SetDefaultTabWorkflowId(int portalId, int workflowId) - { - PortalController.UpdatePortalSetting(portalId, DefaultTabWorkflowKey, workflowId.ToString(CultureInfo.InvariantCulture), true); + public void SetDefaultTabWorkflowId(int portalId, int workflowId) + { + PortalController.UpdatePortalSetting(portalId, DefaultTabWorkflowKey, workflowId.ToString(CultureInfo.InvariantCulture), true); } /// - public void SetWorkflowEnabled(int portalId, bool enabled) - { - Requires.NotNegative("portalId", portalId); - - PortalController.UpdatePortalSetting(portalId, TabWorkflowEnableKey, enabled.ToString(CultureInfo.InvariantCulture), true); + public void SetWorkflowEnabled(int portalId, bool enabled) + { + Requires.NotNegative("portalId", portalId); + + PortalController.UpdatePortalSetting(portalId, TabWorkflowEnableKey, enabled.ToString(CultureInfo.InvariantCulture), true); } /// - public void SetWorkflowEnabled(int portalId, int tabId, bool enabled) - { - Requires.NotNegative("tabId", tabId); - - this.tabController.UpdateTabSetting(tabId, TabWorkflowEnableKey, enabled.ToString(CultureInfo.InvariantCulture)); + public void SetWorkflowEnabled(int portalId, int tabId, bool enabled) + { + Requires.NotNegative("tabId", tabId); + + this.tabController.UpdateTabSetting(tabId, TabWorkflowEnableKey, enabled.ToString(CultureInfo.InvariantCulture)); } /// - public bool IsWorkflowEnabled(int portalId, int tabId) - { - if (!this.IsWorkflowEnabled(portalId)) - { - return false; - } - - var tabInfo = this.tabController.GetTab(tabId, portalId); - var settings = this.tabController.GetTabSettings(tabId); - - return !this.tabController.IsHostOrAdminPage(tabInfo) && (settings[TabWorkflowEnableKey] == null || Convert.ToBoolean(settings[TabWorkflowEnableKey])); + public bool IsWorkflowEnabled(int portalId, int tabId) + { + if (!this.IsWorkflowEnabled(portalId)) + { + return false; + } + + var tabInfo = this.tabController.GetTab(tabId, portalId); + var settings = this.tabController.GetTabSettings(tabId); + + return !this.tabController.IsHostOrAdminPage(tabInfo) && (settings[TabWorkflowEnableKey] == null || Convert.ToBoolean(settings[TabWorkflowEnableKey], CultureInfo.InvariantCulture)); } /// - public bool IsWorkflowEnabled(int portalId) - { - if (portalId == Null.NullInteger) - { - return false; - } - - return Convert.ToBoolean(PortalController.GetPortalSetting(TabWorkflowEnableKey, portalId, bool.FalseString)); + public bool IsWorkflowEnabled(int portalId) + { + if (portalId == Null.NullInteger) + { + return false; + } + + return Convert.ToBoolean(PortalController.GetPortalSetting(TabWorkflowEnableKey, portalId, bool.FalseString)); } /// - protected override Func GetFactory() - { - return () => new TabWorkflowSettings(); - } - } -} + protected override Func GetFactory() + { + return () => new TabWorkflowSettings(); + } + } +} diff --git a/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs b/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs index ff420cfa59c..e32b6021cc9 100644 --- a/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Urls using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.Linq; using System.Reflection; using System.Text; @@ -27,6 +28,7 @@ public class AdvancedFriendlyUrlProvider : FriendlyUrlProviderBase private static readonly Regex AumDebugRegex = new Regex("/_aumdebug/(?:true|false)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex LangMatchRegex = new Regex("/language/(?.[^/]+)(?:/|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex CodePatternRegex = new Regex(CodePattern, RegexOptions.Compiled); + private static readonly HashSet IllegalPageNames = new HashSet(StringComparer.OrdinalIgnoreCase) { "con", "aux", "nul", "prn", }; /// Initializes a new instance of the class. /// The provider attributes. @@ -235,13 +237,13 @@ private static string AddPage(string path, string pageName) } else if (!friendlyPath.EndsWith(pageName, StringComparison.OrdinalIgnoreCase)) { - if (friendlyPath.EndsWith("/")) + if (friendlyPath.EndsWith("/", StringComparison.Ordinal)) { - friendlyPath = friendlyPath + pageName; + friendlyPath = $"{friendlyPath}{pageName}"; } else { - friendlyPath = friendlyPath + "/" + pageName; + friendlyPath = $"{friendlyPath}/{pageName}"; } } @@ -302,7 +304,7 @@ private static string CreateFriendlyUrl( if (changeToSiteRoot) { // no page path if changing to site root because of parameter replacement rule (593) - if (newPath.StartsWith("/")) + if (newPath.StartsWith("/", StringComparison.Ordinal)) { newPath = newPath.Substring(1); } @@ -336,7 +338,7 @@ private static string CreateFriendlyUrl( && !builtInUrl) { // Url is home page, and there's no friendly path to add, so we don't need the home page path (ie, /home is unneeded, just use the site root) - if (newPageName.Length == 0 && pageAndExtension.StartsWith(".")) + if (newPageName.Length == 0 && pageAndExtension.StartsWith(".", StringComparison.Ordinal)) { // when the newPageName isn't specified, and the pageAndExtension is just an extension // just add the querystring on the end @@ -475,13 +477,11 @@ private static PortalAliasInfo GetAliasForPortal(string httpAlias, int portalId, if (aliasArray.Count > 0) { alias = aliasArray[0]; // nab the first one here - messages.Add("Portal Id " + portalId.ToString() + " does not match http alias " + httpAlias + - " - " + alias.HTTPAlias + " was used instead"); + messages.Add($"Portal Id {portalId} does not match http alias {httpAlias} - {alias.HTTPAlias} was used instead"); } else { - messages.Add("Portal Id " + portalId.ToString() + - " does not match http alias and no usable alias could be found"); + messages.Add($"Portal Id {portalId} does not match http alias and no usable alias could be found"); } } @@ -603,12 +603,12 @@ private static string GetFriendlyAlias( } // the portal alias is not in the path already, so we need to get it in there - if (friendlyPath.StartsWith("~/")) + if (friendlyPath.StartsWith("~/", StringComparison.Ordinal)) { friendlyPath = friendlyPath.Substring(1); } - if (friendlyPath.StartsWith("/") == false) + if (!friendlyPath.StartsWith("/", StringComparison.Ordinal)) { friendlyPath = "/" + friendlyPath; } @@ -674,7 +674,7 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa } string queryString = queryStringMatch.Groups[2].Value.Replace("&", "&"); - if (queryString.StartsWith("?")) + if (queryString.StartsWith("?", StringComparison.Ordinal)) { queryString = queryString.TrimStart('?'); } @@ -685,26 +685,24 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa string pathToAppend = string.Empty; string[] pair = nameValuePairs[i].Split('='); - var illegalPageNames = new[] { "con", "aux", "nul", "prn" }; - - if (!illegalPageNames.Contains(pair[0].ToLowerInvariant()) && (pair.Length == 1 || !illegalPageNames.Contains(pair[1].ToLowerInvariant()))) + if (!IllegalPageNames.Contains(pair[0]) && (pair.Length == 1 || !IllegalPageNames.Contains(pair[1]))) { // Add name part of name/value pair - if (friendlyPath.EndsWith("/")) + if (friendlyPath.EndsWith("/", StringComparison.Ordinal)) { if (pair[0].Equals("tabid", StringComparison.OrdinalIgnoreCase)) { // always lowercase the tabid part of the path - pathToAppend = pathToAppend + pair[0].ToLowerInvariant(); + pathToAppend = $"{pathToAppend}{pair[0].ToLowerInvariant()}"; } else { - pathToAppend = pathToAppend + pair[0]; + pathToAppend = $"{pathToAppend}{pair[0]}"; } } else { - pathToAppend = pathToAppend + "/" + pair[0]; + pathToAppend = $"{pathToAppend}/{pair[0]}"; } if (pair.Length > 1) @@ -712,21 +710,20 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa if (pair[1].Length > 0) { var rx = RegexUtils.GetCachedRegex(settings.RegexMatch); - if (rx.IsMatch(pair[1]) == false) + if (!rx.IsMatch(pair[1])) { // Contains Non-AlphaNumeric Characters if (pair[0].Equals("tabid", StringComparison.OrdinalIgnoreCase)) { - int tabId; - if (int.TryParse(pair[1], out tabId)) + if (int.TryParse(pair[1], out var tabId)) { if (tab != null && tab.TabID == tabId) { if (tab.TabPath != Null.NullString && settings.IncludePageName) { - if (pathToAppend.StartsWith("/") == false) + if (!pathToAppend.StartsWith("/", StringComparison.Ordinal)) { - pathToAppend = "/" + pathToAppend; + pathToAppend = $"/{pathToAppend}"; } pathToAppend = tab.TabPath.Replace("//", "/").TrimStart('/').TrimEnd('/') + pathToAppend; @@ -740,19 +737,18 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa if (tab != null && (tab.IsSuperTab || RewriteController.IsAdminTab(tab.PortalID, tab.TabPath, settings))) { // 741 : check admin paths to make sure they aren't using + encoding - pathToAppend = pathToAppend + "/" + pair[1].Replace(" ", "%20"); + pathToAppend = $"{pathToAppend}/{pair[1].Replace(" ", "%20")}"; } else { - pathToAppend = pathToAppend + "/" + - pair[1].Replace(" ", settings.SpaceEncodingValue); + pathToAppend = $"{pathToAppend}/{pair[1].Replace(" ", settings.SpaceEncodingValue)}"; // 625 : replace space with specified url encoding value } } else { - pathToAppend = pathToAppend + "/" + pair[1]; + pathToAppend = $"{pathToAppend}/{pair[1]}"; } } else @@ -776,11 +772,11 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa // Rewrite into URL, contains only alphanumeric and the % or space if (queryStringSpecialChars.Length == 0) { - queryStringSpecialChars = key + "=" + valueBuilder; + queryStringSpecialChars = $"{key}={valueBuilder}"; } else { - queryStringSpecialChars = queryStringSpecialChars + "&" + key + "=" + valueBuilder; + queryStringSpecialChars = $"{queryStringSpecialChars}&{key}={valueBuilder}"; } pathToAppend = string.Empty; @@ -788,7 +784,7 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa } else { - pathToAppend = pathToAppend + "/" + settings.SpaceEncodingValue; + pathToAppend = $"{pathToAppend}/{settings.SpaceEncodingValue}"; // 625 : replace with specified space encoding value } @@ -800,11 +796,11 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa { if (queryStringSpecialChars.Length == 0) { - queryStringSpecialChars = pair[0] + "=" + pair[1]; + queryStringSpecialChars = $"{pair[0]}={pair[1]}"; } else { - queryStringSpecialChars = queryStringSpecialChars + "&" + pair[0] + "=" + pair[1]; + queryStringSpecialChars = $"{queryStringSpecialChars}&{pair[0]}={pair[1]}"; } } } @@ -815,7 +811,7 @@ private static string GetFriendlyQueryString(TabInfo tab, string path, string pa if (queryStringSpecialChars.Length > 0) { - return AddPage(friendlyPath, pageName) + "?" + queryStringSpecialChars; + return $"{AddPage(friendlyPath, pageName)}?{queryStringSpecialChars}"; } return AddPage(friendlyPath, pageName); @@ -1201,7 +1197,7 @@ private static string ImproveFriendlyUrlWithMessages( finalPath = AumDebugRegex.Replace(finalPath, string.Empty); // 'and we're done! - if ((customOnly && isCustomUrl) || customOnly == false || builtInUrl) + if ((customOnly && isCustomUrl) || !customOnly || builtInUrl) { result = Globals.AddHTTP(finalPath); } @@ -1209,7 +1205,7 @@ private static string ImproveFriendlyUrlWithMessages( } else { - var re = RegexUtils.GetCachedRegex("[^?]*/tabId/(\\d+)/ctl/([A-Z][a-z]+)/" + pageName + "$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + var re = RegexUtils.GetCachedRegex($@"[^?]*/tabId/(\d+)/ctl/([A-Z][a-z]+)/{pageName}$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); if (re.IsMatch(friendlyPath)) { Match sesMatch = re.Match(friendlyPath); @@ -1250,7 +1246,7 @@ private static void OutputFriendlyUrlMessages( string resultUrl, FriendlyUrlSettings settings) { - if (settings != null && settings.AllowDebugCode && HttpContext.Current != null) + if (settings is { AllowDebugCode: true, } && HttpContext.Current != null) { HttpRequest request = HttpContext.Current.Request; string debugCheck = CheckForDebug(request); @@ -1260,7 +1256,7 @@ private static void OutputFriendlyUrlMessages( // append the friendly url headers HttpResponse response = HttpContext.Current.Response; - string msgId = id.ToString("000"); + string msgId = id.ToString("000", CultureInfo.InvariantCulture); int tabId = -1; string tabName = "null"; if (tab != null) @@ -1269,26 +1265,26 @@ private static void OutputFriendlyUrlMessages( tabName = tab.TabName; } - msgId += "-" + tabId.ToString("000"); + msgId += "-" + tabId.ToString("000", CultureInfo.InvariantCulture); - if (messages != null && messages.Count > 0) + if (messages is { Count: > 0, }) { response.AppendHeader( - "X-Friendly-Url-" + msgId + ".00", - "Messages for Tab " + tabId.ToString() + ", " + tabName + ", " + path + " calltype:" + method); + $"X-Friendly-Url-{msgId}.00", + $"Messages for Tab {tabId}, {tabName}, {path} calltype:{method}"); int i = 1; foreach (string msg in messages) { - response.AppendHeader("X-Friendly-Url-" + msgId + "." + i.ToString("00"), msg); + response.AppendHeader($"X-Friendly-Url-{msgId}.{i:00}", msg); i++; } if (resultUrl != null) { response.AppendHeader( - "X-Friendly-Url-" + msgId + ".99", - "Path : " + path + " Generated Url : " + resultUrl); + $"X-Friendly-Url-{msgId}.99", + $"Path : {path} Generated Url : {resultUrl}"); } } else @@ -1296,8 +1292,8 @@ private static void OutputFriendlyUrlMessages( if (debugCheck == "all") { response.AppendHeader( - "X-Friendly-Url-" + msgId + ".00", - "Path : " + path + " Generated Url: " + resultUrl); + $"X-Friendly-Url-{msgId}.00", + $"Path : {path} Generated Url: {resultUrl}"); } } } @@ -1363,8 +1359,7 @@ private static void RemoveExcludedPartsOfPath(FriendlyUrlSettings settings, ref // Build new path and query string newPath = pathBuilder.ToString(); qs = string.IsNullOrWhiteSpace(qs) ? - queryStringBuilder.ToString() : - string.Format("{0}&{1}", qs, queryStringBuilder); + queryStringBuilder.ToString() : $"{qs}&{queryStringBuilder}"; } private static bool TransformStandardPath(ref string newPath, ref string newTabPath) diff --git a/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs b/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs index 5936f6caa26..5fd5aaf002b 100644 --- a/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs +++ b/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs @@ -423,7 +423,7 @@ private static void ShowDebugData(HttpContext context, string requestUri, UrlAct var ps = (PortalSettings)context.Items["PortalSettings"]; if (ps != null) { - portalSettings = ps.PortalId.ToString(); + portalSettings = ps.PortalId.ToString(CultureInfo.InvariantCulture); if (ps.PortalAlias != null) { portalSettings += ":" + ps.PortalAlias.HTTPAlias; @@ -434,6 +434,7 @@ private static void ShowDebugData(HttpContext context, string requestUri, UrlAct response.AppendHeader( "X-" + ProductName + "-Debug", string.Format( + CultureInfo.InvariantCulture, debugMsg, requestUri, finalUrl, @@ -447,7 +448,7 @@ private static void ShowDebugData(HttpContext context, string requestUri, UrlAct { foreach (string msg in result.DebugMessages) { - response.AppendHeader("X-" + ProductName + "-Debug-" + msgNum.ToString("00"), msg); + response.AppendHeader("X-" + ProductName + "-Debug-" + msgNum.ToString("00", CultureInfo.InvariantCulture), msg); msgNum++; } } @@ -654,9 +655,10 @@ private static void Handle404OrException(FriendlyUrlSettings settings, HttpConte response.AppendHeader( errRH, string.Format( + CultureInfo.InvariantCulture, errRV, "DNN Tab", - errTab.TabName + "(Tabid:" + errTabId.ToString() + ")", + $"{errTab.TabName}(Tabid:{errTabId})", reason)); // show debug messages even if in debug mode @@ -805,7 +807,7 @@ private static void Handle404OrException(FriendlyUrlSettings settings, HttpConte // 912 : change to new if statement to handle cases where the TabId404 couldn't be handled correctly if (unhandled404) { - // proces the error on the external Url by rewriting to the external url + // process the error on the external Url by rewriting to the external url if (!string.IsNullOrEmpty(errUrl)) { response.ClearContent(); @@ -816,7 +818,7 @@ private static void Handle404OrException(FriendlyUrlSettings settings, HttpConte reason = result.Reason.ToString(); } - response.AppendHeader(errRH, string.Format(errRV, "Url", errUrl, reason)); + response.AppendHeader(errRH, string.Format(CultureInfo.InvariantCulture, errRV, "Url", errUrl, reason)); if (reason404 != null) { response.AppendHeader("X-Url-Master-404-Data", reason404); @@ -888,16 +890,16 @@ private static void Handle404OrException(FriendlyUrlSettings settings, HttpConte } } - if (ceSection != null && ceSection.Mode == CustomErrorsMode.Off) + if (ceSection is { Mode: CustomErrorsMode.Off, }) { errorPageHtml.Write(errorPageHtmlHeader); - errorPageHtml.Write("
Exception:
" + ex.Message + "
"); - errorPageHtml.Write("
Stack Trace:
" + ex.StackTrace + "
"); + errorPageHtml.Write($"
Exception:
{ex.Message}
"); + errorPageHtml.Write($"
Stack Trace:
{ex.StackTrace}
"); errorPageHtml.Write("
Administrators
"); errorPageHtml.Write("
You can see this exception because the customErrors attribute in the web.config is set to 'off'. Change this value to 'on' or 'RemoteOnly' to show Error Handling
"); try { - if (errUrl != null && errUrl.StartsWith("~")) + if (errUrl != null && errUrl.StartsWith("~", StringComparison.Ordinal)) { errUrl = VirtualPathUtility.ToAbsolute(errUrl); } @@ -906,7 +908,7 @@ private static void Handle404OrException(FriendlyUrlSettings settings, HttpConte { if (errUrl != null) { - errorPageHtml.Write("
The error handling would have shown this page : " + errUrl + "
"); + errorPageHtml.Write($"
The error handling would have shown this page : {errUrl}
"); } else { @@ -1619,7 +1621,7 @@ private static bool CheckForRedirects( // 610 don't always end with '/' - reverses previous setting // 687 don't double-check 301 redirects. 'CheckFor301' is less concise than 'Redirect301' // DNN-21906: if the redirect is for splash page, then we should continue the 302 redirect. - if (requestUri.AbsolutePath.EndsWith("/") && result.Action != ActionType.Redirect301 && result.Reason != RedirectReason.Requested_SplashPage) + if (requestUri.AbsolutePath.EndsWith("/", StringComparison.Ordinal) && result.Action != ActionType.Redirect301 && result.Reason != RedirectReason.Requested_SplashPage) { result.Action = ActionType.CheckFor301; } @@ -1868,7 +1870,7 @@ private static bool CheckForRedirects( } // DNN-9158: prevent SSL Offloading infinite redirects - if (!result.IsSecureConnection && result.IsSSLOffloaded && bestFriendlyNoScheme.StartsWith("https")) + if (!result.IsSecureConnection && result.IsSSLOffloaded && bestFriendlyNoScheme.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { bestFriendlyNoScheme = $"http://{bestFriendlyNoScheme.Substring(8)}"; } @@ -2061,9 +2063,7 @@ private static bool CheckForSecureRedirect( // no secure redirection for physical resources, only tab-specific requests can be redirected for ssl connections if (portalSettings.ActiveTab != null) { - result.DebugMessages.Add("ActiveTab: " + portalSettings.ActiveTab.TabID.ToString() + "/" + - portalSettings.ActiveTab.TabName + " IsSecure: " + - portalSettings.ActiveTab.IsSecure.ToString()); + result.DebugMessages.Add($"ActiveTab: {portalSettings.ActiveTab.TabID}/{portalSettings.ActiveTab.TabName} IsSecure: {portalSettings.ActiveTab.IsSecure}"); switch (portalSettings.SSLSetup) { @@ -2411,8 +2411,7 @@ private void ProcessRequest( } // 852: add skinSrc to path if it exists and if it's not already there - string debugMessage; - RewriteController.AddSkinToRewritePath(result.TabId, result.PortalId, ref rewritePath, skin, out debugMessage); + RewriteController.AddSkinToRewritePath(result.TabId, result.PortalId, ref rewritePath, skin, out var debugMessage); result.RewritePath = rewritePath; // reset back from ref temp var if (debugMessage != null) { @@ -2424,16 +2423,16 @@ private void ProcessRequest( if (!finished && result.DoRewrite) { // if so, do the rewrite - if (result.RewritePath.StartsWith(result.Scheme) || result.RewritePath.StartsWith(Globals.glbDefaultPage) == false) + if (result.RewritePath.StartsWith(result.Scheme, StringComparison.OrdinalIgnoreCase) || !result.RewritePath.StartsWith(Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase)) { - if (result.RewritePath.Contains(Globals.glbDefaultPage) == false) + if (!result.RewritePath.Contains(Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase)) { RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); } else { // if there is no TabId and we have the domain - if (!result.RewritePath.ToLowerInvariant().Contains("tabId=")) + if (!result.RewritePath.Contains("tabId=", StringComparison.OrdinalIgnoreCase)) { RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); } @@ -2607,7 +2606,7 @@ private void ProcessRequest( // 702 : don't check final url until checked for null reference first if (result.FinalUrl != null) { - if (result.FinalUrl.StartsWith("https://")) + if (result.FinalUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { if (showDebug) { @@ -2733,25 +2732,24 @@ private void ProcessRequest( } else { - if (result.DoRewrite == false && result.CanRewrite != StateBoolean.False && !finished && + if (!result.DoRewrite && result.CanRewrite != StateBoolean.False && !finished && result.Action == ActionType.Continue) { // 739 : catch no-extension 404 errors string pathWithNoQs = result.OriginalPath; - if (pathWithNoQs.Contains("?")) + if (pathWithNoQs.Contains("?", StringComparison.Ordinal)) { pathWithNoQs = pathWithNoQs.Substring(0, pathWithNoQs.IndexOf("?", StringComparison.Ordinal)); } - if (!pathWithNoQs.Substring(pathWithNoQs.Length - 5, 5).Contains(".")) + if (!pathWithNoQs.AsSpan(pathWithNoQs.Length - 5, 5).Contains(".", StringComparison.Ordinal)) { // no page extension, output a 404 if the Url is not found // 766 : check for physical path before passing off as a 404 error // 829 : change to use action physical path // 893 : filter by regex pattern to exclude urls which are valid, but show up as extensionless if ((request != null && Directory.Exists(result.PhysicalPath)) - || - Regex.IsMatch(pathWithNoQs, settings.ValidExtensionlessUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + || Regex.IsMatch(pathWithNoQs, settings.ValidExtensionlessUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { // do nothing : it's a request for a valid physical path, maybe including a default document result.VirtualPath = StateBoolean.False; @@ -3013,7 +3011,7 @@ private void IdentifyPortalAlias( else { result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); - if (result.PortalAlias == null && result.DomainName.EndsWith("/")) + if (result.PortalAlias == null && result.DomainName.EndsWith("/", StringComparison.Ordinal)) { result.DomainName = result.DomainName.TrimEnd('/'); result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); diff --git a/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs b/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs index d1709f3c56f..33b2a6ed598 100644 --- a/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Urls using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.Text.RegularExpressions; using System.Web; @@ -83,13 +84,13 @@ internal override string FriendlyUrl(TabInfo tab, string path, string pageName, private static string AddPage(string path, string pageName) { string friendlyPath = path; - if (friendlyPath.EndsWith("/")) + if (friendlyPath.EndsWith("/", StringComparison.Ordinal)) { - friendlyPath = friendlyPath + pageName; + friendlyPath = $"{friendlyPath}{pageName}"; } else { - friendlyPath = friendlyPath + "/" + pageName; + friendlyPath = $"{friendlyPath}/{pageName}"; } return friendlyPath; @@ -114,7 +115,7 @@ private static string GetFriendlyAlias(string path, string portalAlias, bool isP { string friendlyPath = path; string matchString = string.Empty; - if (string.IsNullOrEmpty(portalAlias) == false) + if (!string.IsNullOrEmpty(portalAlias)) { string httpAlias = Globals.AddHTTP(portalAlias).ToLowerInvariant(); if (HttpContext.Current?.Items["UrlRewrite:OriginalUrl"] != null) @@ -122,7 +123,7 @@ private static string GetFriendlyAlias(string path, string portalAlias, bool isP string originalUrl = HttpContext.Current.Items["UrlRewrite:OriginalUrl"].ToString().ToLowerInvariant(); httpAlias = Globals.AddPort(httpAlias, originalUrl); - if (originalUrl.StartsWith(httpAlias)) + if (originalUrl.StartsWith(httpAlias, StringComparison.OrdinalIgnoreCase)) { matchString = httpAlias; } @@ -154,7 +155,7 @@ private static string GetFriendlyAlias(string path, string portalAlias, bool isP // manage the case where the current hostname is www.domain.com and the portalalias is domain.com // (this occurs when www.domain.com is not listed as portal alias for the portal, but domain.com is) string wwwHttpAlias = Globals.AddHTTP("www." + portalAlias); - if (originalUrl.StartsWith(wwwHttpAlias)) + if (originalUrl.StartsWith(wwwHttpAlias, StringComparison.OrdinalIgnoreCase)) { matchString = wwwHttpAlias; } @@ -168,9 +169,9 @@ private static string GetFriendlyAlias(string path, string portalAlias, bool isP if (!string.IsNullOrEmpty(matchString)) { - if (path.IndexOf("~", StringComparison.Ordinal) != -1) + if (path.Contains("~", StringComparison.Ordinal)) { - friendlyPath = friendlyPath.Replace(matchString.EndsWith("/") ? "~/" : "~", matchString); + friendlyPath = friendlyPath.Replace(matchString.EndsWith("/", StringComparison.Ordinal) ? "~/" : "~", matchString); } else { @@ -182,7 +183,7 @@ private static string GetFriendlyAlias(string path, string portalAlias, bool isP friendlyPath = Globals.ResolveUrl(friendlyPath); } - if (friendlyPath.StartsWith("//") && isPagePath) + if (friendlyPath.StartsWith("//", StringComparison.Ordinal) && isPagePath) { friendlyPath = friendlyPath.Substring(1); } @@ -224,7 +225,7 @@ private string GetFriendlyQueryString(TabInfo tab, string path, string pageName) friendlyPath = queryStringMatch.Groups[1].Value; friendlyPath = DefaultPageRx.Replace(friendlyPath, string.Empty); string queryString = queryStringMatch.Groups[2].Value.Replace("&", "&"); - if (queryString.StartsWith("?")) + if (queryString.StartsWith("?", StringComparison.Ordinal)) { queryString = queryString.TrimStart(Convert.ToChar("?")); } @@ -236,7 +237,7 @@ private string GetFriendlyQueryString(TabInfo tab, string path, string pageName) string[] pair = nameValuePairs[i].Split(Convert.ToChar("=")); // Add name part of name/value pair - if (friendlyPath.EndsWith("/")) + if (friendlyPath.EndsWith("/", StringComparison.Ordinal)) { pathToAppend = pathToAppend + pair[0]; } @@ -258,7 +259,7 @@ private string GetFriendlyQueryString(TabInfo tab, string path, string pageName) { if (tab != null) { - var tabId = Convert.ToInt32(pair[1]); + var tabId = Convert.ToInt32(pair[1], CultureInfo.InvariantCulture); if (tab.TabID == tabId) { if (!string.IsNullOrEmpty(tab.TabPath) && this.IncludePageName) diff --git a/DNN Platform/Library/Entities/Urls/CacheController.cs b/DNN Platform/Library/Entities/Urls/CacheController.cs index f3d840a0b89..91ffe73c42e 100644 --- a/DNN Platform/Library/Entities/Urls/CacheController.cs +++ b/DNN Platform/Library/Entities/Urls/CacheController.cs @@ -10,6 +10,7 @@ namespace DotNetNuke.Entities.Urls using System.Collections.Specialized; using System.Configuration; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Threading; using System.Web.Caching; @@ -44,6 +45,7 @@ public class CacheController private const string AlwaysCallProviderTabsKey = "url_AlwaysCallProviderTabs_{0}"; private const string HomePageSkinsKey = "url_HomePageSkins_{0}"; private const string TabPathsKey = "url_TabPathsKey_{0}"; + private static readonly string[] PortalCacheDependencyKeys = ["DNN_PortalDictionary",]; private static CacheItemRemovedReason cacheItemRemovedReason; private static bool logRemovedReason; private CacheItemRemovedCallback onRemovePageIndex; @@ -138,7 +140,7 @@ public static PortalInfo GetPortal(int portalId, bool exceptionOnNull) if (exceptionOnNull && pi == null) { - throw new PortalNotFoundException("No Portal Found for portalid : " + portalId.ToString()); + throw new PortalNotFoundException($"No Portal Found for portalid : {portalId}"); } return pi; @@ -151,7 +153,7 @@ public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason #if DEBUG if (logRemovedReason) { - var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + var log = new LogInfo { LogTypeKey = "HOST_ALERT", }; string itemName; string count; @@ -172,9 +174,9 @@ public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason // was cleared. } - if (v != null && v.GetType() == typeof(SharedDictionary)) + if (v is SharedDictionary stringDict) { - count = "Item Count: " + ((SharedDictionary)v).Values.Count.ToString(); + count = "Item Count: " + stringDict.Values.Count; } else { @@ -184,20 +186,18 @@ public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason break; case "DNN_" + UrlDictKey: itemName = "Friendly Url List"; - if (v != null && - v.GetType() == typeof(SharedDictionary>)) + if (v is SharedDictionary> friendlyUrls) { - var friendlyUrls = (SharedDictionary>)v; - portalCounts = new List(); + portalCounts = []; using (friendlyUrls.GetReadLock()) { - count = "Portal Count: " + friendlyUrls.Count.ToString(); + count = $"Portal Count: {friendlyUrls.Count}"; foreach (int key in friendlyUrls.Keys) { - SharedDictionary portalUrls = friendlyUrls[key]; + var portalUrls = friendlyUrls[key]; using (portalUrls.GetReadLock()) { - portalCounts.Add("Portal " + key.ToString() + " Item Count :" + portalUrls.Count.ToString()); + portalCounts.Add($"Portal {key} Item Count :{portalUrls.Count}"); } } } @@ -224,7 +224,7 @@ public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason int i = 0; foreach (string item in portalCounts) { - log.AddProperty("Item " + i.ToString(), item); + log.AddProperty($"Item {i}", item); i++; } } @@ -250,14 +250,14 @@ internal static string FindFriendlyUrlParmsConfigFilePath(int portalId, out bool string result = string.Empty; portalSpecificFound = false; const string fileName = "friendlyUrlParms.config"; - string rootPath = Globals.ApplicationMapPath + "\\"; + string rootPath = $@"{Globals.ApplicationMapPath}\"; string filePath; if (portalId > -1) { // specific portal // first look in the root folder with the portalid as a prefix - filePath = rootPath + portalId.ToString() + "." + fileName; + filePath = $"{rootPath}{portalId.ToString(CultureInfo.InvariantCulture)}.{fileName}"; } else { @@ -312,7 +312,7 @@ internal static string FindFriendlyUrlParmsConfigFilePath(int portalId, out bool internal static List GetAlwaysCallProviderTabs(int portalId) { List result = null; - string key = string.Format(AlwaysCallProviderTabsKey, portalId); + string key = string.Format(CultureInfo.InvariantCulture, AlwaysCallProviderTabsKey, portalId); var tabIdsToAlwaysCall = (int[])DataCache.GetCache(key); if (tabIdsToAlwaysCall != null) { @@ -326,7 +326,7 @@ internal static List GetAlwaysCallProviderTabs(int portalId) internal static List GetCustomAliasesFromCache() { object raw = DataCache.GetCache(CustomPortalAliasesKey); - return (raw != null) ? (List)raw : null; + return (List)raw; } internal static void ClearCustomAliasesCache() @@ -336,15 +336,14 @@ internal static void ClearCustomAliasesCache() internal static Hashtable GetHomePageSkinsFromCache(int portalId) { - string key = string.Format(HomePageSkinsKey, portalId); - var result = (Hashtable)DataCache.GetCache(key); - return result; + string key = string.Format(CultureInfo.InvariantCulture, HomePageSkinsKey, portalId); + return (Hashtable)DataCache.GetCache(key); } internal static List GetListOfTabsWithProviders(int portalId, FriendlyUrlSettings settings) { List result = null; - string key = string.Format(PortalModuleProviderTabsKey, portalId); + string key = string.Format(CultureInfo.InvariantCulture, PortalModuleProviderTabsKey, portalId); var tabIdsForPortal = (int[])DataCache.GetCache(key); if (tabIdsForPortal != null) { @@ -356,10 +355,10 @@ internal static List GetListOfTabsWithProviders(int portalId, FriendlyUrlSe internal static Dictionary> GetParameterRedirects(FriendlyUrlSettings settings, int portalId, ref List messages) { - string redirectActionKey = string.Format(RedirectActionsKey, portalId); // cached one portal at a time + string redirectActionKey = string.Format(CultureInfo.InvariantCulture, RedirectActionsKey, portalId); // cached one portal at a time if (messages == null) { - messages = new List(); + messages = []; } var redirectActions = (Dictionary>)DataCache.GetCache(redirectActionKey); @@ -370,8 +369,7 @@ internal static Dictionary> GetParameterRedir redirectActions = new Dictionary>(); // 807 : look for portal specific files - bool portalSpecific; - string fileName = FindFriendlyUrlParmsConfigFilePath(portalId, out portalSpecific); + string fileName = FindFriendlyUrlParmsConfigFilePath(portalId, out var portalSpecific); if (fileName != string.Empty) { redirectActions.LoadFromXmlFile(fileName, portalId, portalSpecific, ref messages); @@ -406,7 +404,7 @@ internal static Dictionary> GetParameterRedir internal static Dictionary> GetParameterReplacements(FriendlyUrlSettings settings, int portalId, ref List messages) { - string replaceActionKey = "replaceActions:" + portalId.ToString(); + string replaceActionKey = "replaceActions:" + portalId.ToString(CultureInfo.InvariantCulture); var replaceActions = (Dictionary>)DataCache.GetCache(replaceActionKey); if (messages == null) { @@ -447,10 +445,10 @@ internal static Dictionary> GetParameterReplac internal static Dictionary> GetParameterRewrites(int portalId, ref List messages, Guid parentTraceId) { - string rewriteActionKey = string.Format(RewriteActionsKey, portalId.ToString()); + string rewriteActionKey = string.Format(CultureInfo.InvariantCulture, RewriteActionsKey, portalId); if (messages == null) { - messages = new List(); + messages = []; } var rewriteActions = (Dictionary>)DataCache.GetCache(rewriteActionKey); @@ -459,10 +457,9 @@ internal static Dictionary> GetParameter try { rewriteActions = new Dictionary>(); - bool portalSpecific; // 807 : new change to look for portal rule files in portal specific locations - string filename = FindFriendlyUrlParmsConfigFilePath(portalId, out portalSpecific); + string filename = FindFriendlyUrlParmsConfigFilePath(portalId, out var portalSpecific); if (!string.IsNullOrEmpty(filename)) { rewriteActions.LoadFromXmlFile(filename, portalId, portalSpecific, ref messages); @@ -520,11 +517,11 @@ internal static List GetProvidersForTabAndPortal( if (checkAllTabs) { // the portal has an 'all tabs' provider in it - string allTabsKey = string.Format(PortalModuleProvidersAllTabsKey, portalId); + string allTabsKey = string.Format(CultureInfo.InvariantCulture, PortalModuleProvidersAllTabsKey, portalId); var cachedAllTabsProviders = (List)DataCache.GetCache(allTabsKey); if (cachedAllTabsProviders != null) { - allCachedProviders = new List(); + allCachedProviders = []; allCachedProviders.AddRange(cachedAllTabsProviders); } } @@ -533,7 +530,7 @@ internal static List GetProvidersForTabAndPortal( if (checkThisTab) { // tab exists, get the providers for this tab - string key = string.Format(PortalModuleProvidersForTabKey, portalId, tabId); + string key = string.Format(CultureInfo.InvariantCulture, PortalModuleProvidersForTabKey, portalId, tabId); var cachedTabProviders = (List)DataCache.GetCache(key); if (cachedTabProviders != null) { @@ -551,14 +548,14 @@ internal static List GetProvidersForTabAndPortal( internal static SharedDictionary GetTabPathsFromCache(int portalId) { - return (SharedDictionary)DataCache.GetCache(string.Format(TabPathsKey, portalId)); + return (SharedDictionary)DataCache.GetCache(string.Format(CultureInfo.InvariantCulture, TabPathsKey, portalId)); } - internal static void StoreAlwaysCallProviderTabs(int portalId, List alwaysCallTabids, FriendlyUrlSettings settings) + internal static void StoreAlwaysCallProviderTabs(int portalId, List alwaysCallTabIds, FriendlyUrlSettings settings) { - if (alwaysCallTabids != null) + if (alwaysCallTabIds != null) { - SetPageCache(string.Format(AlwaysCallProviderTabsKey, portalId), alwaysCallTabids.ToArray(), settings); + SetPageCache(string.Format(CultureInfo.InvariantCulture, AlwaysCallProviderTabsKey, portalId), alwaysCallTabIds.ToArray(), settings); } } @@ -575,9 +572,9 @@ internal static void StoreCustomAliasesInCache(List aliases, FriendlyUrl internal static void StoreHomePageSkinsInCache(int portalId, Hashtable homePageSkins) { - if (homePageSkins != null && homePageSkins.Count > 0) + if (homePageSkins is { Count: > 0, }) { - DataCache.SetCache(string.Format(HomePageSkinsKey, portalId), homePageSkins); + DataCache.SetCache(string.Format(CultureInfo.InvariantCulture, HomePageSkinsKey, portalId), homePageSkins); } } @@ -618,25 +615,25 @@ internal static void StoreListOfTabsWithProviders(List pro foreach (int providerTabId in provider.ProviderConfig.TabIds) { - if (providersWithTabs.Contains(providerTabId) == false) + if (!providersWithTabs.Contains(providerTabId)) { providersWithTabs.Add(providerTabId); - providersWithTabsStr.Add(providerTabId.ToString()); + providersWithTabsStr.Add(providerTabId.ToString(CultureInfo.InvariantCulture)); } } } // store list as array in cache - string key = string.Format(PortalModuleProviderTabsKey, portalId); + string key = string.Format(CultureInfo.InvariantCulture, PortalModuleProviderTabsKey, portalId); SetPageCache(key, providersWithTabs.ToArray(), settings); if (settings.LogCacheMessages) { var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; log.AddProperty("Url Rewriting Caching Message", "Portal Module Providers Tab List stored in cache"); log.AddProperty("Cache Item Key", key); - log.AddProperty("PortalId", portalId.ToString()); + log.AddProperty("PortalId", portalId.ToString(CultureInfo.InvariantCulture)); log.AddProperty("Provider With Tabs", string.Join(",", providersWithTabsStr.ToArray())); - log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString()); + log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -644,7 +641,7 @@ internal static void StoreListOfTabsWithProviders(List pro internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSettings settings, List providers) { // get the key for the portal module providers - string allTabsKey = string.Format(PortalModuleProvidersAllTabsKey, portalId); + string allTabsKey = string.Format(CultureInfo.InvariantCulture, PortalModuleProvidersAllTabsKey, portalId); // get the providers that are on all tabs var allTabsProviders = new List(); @@ -674,7 +671,7 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett { thisTabProviders = [provider,]; tabsProviders.Add(tabId, thisTabProviders); - tabIdStr.Add(tabId.ToString()); + tabIdStr.Add(tabId.ToString(CultureInfo.InvariantCulture)); } } @@ -716,7 +713,7 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett { foreach (int tabId in tabsProviders.Keys) { - SetPageCache(string.Format(PortalModuleProvidersForTabKey, portalId, tabId), tabsProviders[tabId], settings); + SetPageCache(string.Format(CultureInfo.InvariantCulture, PortalModuleProvidersForTabKey, portalId, tabId), tabsProviders[tabId], settings); } } @@ -724,10 +721,10 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett { var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; log.AddProperty("Url Rewriting Caching Message", "Extension Url Providers stored in cache"); - log.AddProperty("PortalId/TabIds", portalId.ToString() + "/" + string.Join(",", tabIdStr.ToArray())); - log.AddProperty("All Tabs Providers Count", allTabsProviders.Count.ToString()); - log.AddProperty("Portal Tabs Providers Count", providerCount.ToString()); - log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString()); + log.AddProperty("PortalId/TabIds", portalId.ToString(CultureInfo.InvariantCulture) + "/" + string.Join(",", tabIdStr.ToArray())); + log.AddProperty("All Tabs Providers Count", allTabsProviders.Count.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("Portal Tabs Providers Count", providerCount.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -834,14 +831,14 @@ internal void StoreFriendlyUrlIndexInCache( log.AddProperty("Cache Key", UrlDictKey); using (urlDict.GetReadLock()) { - log.AddProperty("Item Count", urlDict.Values.Count.ToString()); + log.AddProperty("Item Count", urlDict.Values.Count.ToString(CultureInfo.InvariantCulture)); } - log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString()); - log.AddProperty("Item added to cache", "Url Portals object added to cache. Key:" + UrlPortalsKey + " Items: " + urlPortals.Count.ToString()); + log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("Item added to cache", "Url Portals object added to cache. Key:" + UrlPortalsKey + " Items: " + urlPortals.Count.ToString(CultureInfo.InvariantCulture)); using (customAliasTabs.GetReadLock()) { - log.AddProperty("Item added to cache", "Custom Alias Tabs added to cache. Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString()); + log.AddProperty("Item added to cache", "Custom Alias Tabs added to cache. Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString(CultureInfo.InvariantCulture)); } LogController.Instance.AddLog(log); @@ -879,10 +876,10 @@ internal void StorePageIndexInCache( log.AddProperty("Cache Item Key", PageIndexKey); using (tabDictionary.GetReadLock()) { - log.AddProperty("Item Count", tabDictionary.Count.ToString()); + log.AddProperty("Item Count", tabDictionary.Count.ToString(CultureInfo.InvariantCulture)); } - log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString()); + log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -891,18 +888,16 @@ internal void StorePageIndexInCache( internal void StoreTabPathsInCache(int portalId, SharedDictionary tabPathDictionary, FriendlyUrlSettings settings) { SetPageCache( - string.Format(TabPathsKey, portalId), + string.Format(CultureInfo.InvariantCulture, TabPathsKey, portalId), tabPathDictionary, - new DNNCacheDependency(GetTabsCacheDependency(new List { portalId })), + new DNNCacheDependency(GetTabsCacheDependency([portalId,])), settings, null); } private static CacheDependency GetPortalsCacheDependency() { - var keys = new List { "DNN_PortalDictionary" }; - var portalsDepedency = new CacheDependency(null, keys.ToArray()); - return portalsDepedency; + return new CacheDependency(null, PortalCacheDependencyKeys); } private static void SetPageCache(string key, object value, FriendlyUrlSettings settings) @@ -953,7 +948,7 @@ private static CacheDependency GetTabsCacheDependency(IEnumerable portalIds foreach (int portalId in portalIds) { const string cacheKey = DataCache.TabCacheKey; - string key = string.Format(cacheKey, portalId); + string key = string.Format(CultureInfo.InvariantCulture, cacheKey, portalId); key = "DNN_" + key; // add on the DNN_ prefix keys.Add(key); } diff --git a/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs b/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs index 2d3b7c226b7..dc498846402 100644 --- a/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs +++ b/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Urls { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Xml; @@ -84,7 +85,7 @@ public static void LoadFromXmlFile(this Dictionary 0) @@ -321,7 +322,7 @@ public static void LoadFromXmlFile(this Dictionary +{ + public new void Add(RewriterRule r) => base.Add(r); +} diff --git a/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs b/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs index 6c3a83b1d3a..00be8801891 100644 --- a/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs +++ b/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Urls { using System; using System.Collections.Concurrent; + using System.Globalization; using System.Linq; using DotNetNuke.Collections.Internal; @@ -61,7 +62,7 @@ internal static SharedDictionary> FetchCus urlPortals, customAliasForTabs, settings, - "Portal Id " + portalId.ToString() + " added to index."); + "Portal Id " + portalId.ToString(CultureInfo.InvariantCulture) + " added to index."); } } else @@ -69,10 +70,10 @@ internal static SharedDictionary> FetchCus // either values are null (Not in cache) or we want to force the rebuild, or we want to bypass the cache // rebuild the dictionary for this portal urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs); - urlPortals = new ConcurrentBag { portalId }; // always rebuild the portal list + urlPortals = [portalId,]; // always rebuild the portal list // if we are to cache this item (byPassCache = false) - if (bypassCache == false) + if (!bypassCache) { // cache these items string reason = forceRebuild ? "Force Rebuild of Index" : "Index not in cache"; @@ -126,10 +127,10 @@ private static SharedDictionary> BuildUrlD // check the custom alias tabs collection and add to the dictionary where necessary foreach (var customAlias in tab.CustomAliases) { - string key = tab.TabID.ToString() + ":" + customAlias.Key; + string key = tab.TabID.ToString(CultureInfo.InvariantCulture) + ":" + customAlias.Key; using (customAliasTabs.GetWriteLock()) // obtain write lock on custom alias Tabs { - if (customAliasTabs.ContainsKey(key) == false) + if (!customAliasTabs.ContainsKey(key)) { customAliasTabs.Add(key, customAlias.Value); } diff --git a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs index ababffb9c7c..541b241baf3 100644 --- a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs +++ b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs @@ -7,10 +7,12 @@ namespace DotNetNuke.Entities.Urls using System.Collections.Generic; using System.Collections.Specialized; using System.Data; + using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Web.Caching; + using DotNetNuke.Abstractions.Portals; using DotNetNuke.Application; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; @@ -57,82 +59,80 @@ public static List GetProviders(int portalId) /// Note : similar copy for UI purposes in ConfigurationController.cs. public static List GetModuleProviders(int portalId) { - var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); + var cacheKey = FormattableString.Invariant($"ExtensionUrlProviders_{portalId}"); var moduleProviders = CBO.GetCachedObject>( new CacheItemArgs( - cacheKey, - 60, - CacheItemPriority.High, - portalId), - c => - { - var id = (int)c.Params[0]; - IDataReader dr = DataProvider.Instance().GetExtensionUrlProviders(id); - try - { - var providers = new List(); - var providerConfigs = CBO.FillCollection(dr, new List(), false); - - foreach (var providerConfig in providerConfigs) - { - var providerType = Reflection.CreateType(providerConfig.ProviderType); - if (providerType == null) - { - continue; - } - - var provider = Reflection.CreateObject(providerType) as ExtensionUrlProvider; - if (provider == null) - { - continue; - } - - provider.ProviderConfig = providerConfig; - provider.ProviderConfig.PortalId = id; - providers.Add(provider); - } - - if (dr.NextResult()) - { - // Setup Settings - while (dr.Read()) - { - var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); - var key = Null.SetNullString(dr["SettingName"]); - var value = Null.SetNullString(dr["SettingValue"]); - - var provider = providers.SingleOrDefault(p => p.ProviderConfig.ExtensionUrlProviderId == extensionUrlProviderId); - if (provider != null) - { - provider.ProviderConfig.Settings[key] = value; - } - } - } - - if (dr.NextResult()) - { - // Setup Tabs - while (dr.Read()) - { - var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); - var tabId = Null.SetNullInteger(dr["TabID"]); - - var provider = providers.SingleOrDefault(p => p.ProviderConfig.ExtensionUrlProviderId == extensionUrlProviderId); - if (provider != null && !provider.ProviderConfig.TabIds.Contains(tabId)) - { - provider.ProviderConfig.TabIds.Add(tabId); - } - } - } - - return providers; - } - finally - { - // Close reader - CBO.CloseDataReader(dr, true); - } - }); + cacheKey, + 60, + CacheItemPriority.High, + portalId), + static c => + { + var id = (int)c.Params[0]; + IDataReader dr = DataProvider.Instance().GetExtensionUrlProviders(id); + try + { + var providers = new List(); + var providerConfigs = CBO.FillCollection(dr, new List(), false); + + foreach (var providerConfig in providerConfigs) + { + var providerType = Reflection.CreateType(providerConfig.ProviderType); + if (providerType == null) + { + continue; + } + + if (Reflection.CreateObject(providerType) is not ExtensionUrlProvider provider) + { + continue; + } + + provider.ProviderConfig = providerConfig; + provider.ProviderConfig.PortalId = id; + providers.Add(provider); + } + + if (dr.NextResult()) + { + // Setup Settings + while (dr.Read()) + { + var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); + var key = Null.SetNullString(dr["SettingName"]); + var value = Null.SetNullString(dr["SettingValue"]); + + var provider = providers.SingleOrDefault(p => + p.ProviderConfig.ExtensionUrlProviderId == extensionUrlProviderId); + provider?.ProviderConfig.Settings[key] = value; + } + } + + if (dr.NextResult()) + { + // Setup Tabs + while (dr.Read()) + { + var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); + var tabId = Null.SetNullInteger(dr["TabID"]); + + var provider = providers.SingleOrDefault(p => + p.ProviderConfig.ExtensionUrlProviderId == extensionUrlProviderId); + if (provider != null && !provider.ProviderConfig.TabIds.Contains(tabId)) + { + provider.ProviderConfig.TabIds.Add(tabId); + } + } + } + + return providers; + } + finally + { + // Close reader + CBO.CloseDataReader(dr, true); + } + }); return moduleProviders; } @@ -208,8 +208,8 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat log.AddProperty("Redirect Location", string.IsNullOrEmpty(result.FinalUrl) ? "[no redirect]" : result.FinalUrl); log.AddProperty("Action", result.Action.ToString()); log.AddProperty("Reason", result.Reason.ToString()); - log.AddProperty("Portal Id", result.PortalId.ToString()); - log.AddProperty("Tab Id", result.TabId.ToString()); + log.AddProperty("Portal Id", result.PortalId.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("Tab Id", result.TabId.ToString(CultureInfo.InvariantCulture)); log.AddProperty("Http Alias", result.PortalAlias != null ? result.PortalAlias.HTTPAlias : "Null"); if (result.DebugMessages != null) @@ -223,7 +223,7 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat msg = "[message was null]"; } - log.AddProperty("Debug Message[result] " + i.ToString(), msg); + log.AddProperty("Debug Message[result] " + i.ToString(CultureInfo.InvariantCulture), msg); i++; } } @@ -238,7 +238,7 @@ public static void LogModuleProviderExceptionInRequest(Exception ex, string stat int i = 1; foreach (string msg in messages) { - log.AddProperty("Debug Message[raw] " + i.ToString(), msg); + log.AddProperty("Debug Message[raw] " + i.ToString(CultureInfo.InvariantCulture), msg); i++; } } @@ -460,8 +460,7 @@ internal static bool GetUrlFromExtensionUrlProviders( wasChanged = true; changedPath = customPath.Trim(); changeToSiteRoot = !useDnnPagePath; // useDNNpagePath means no change to site root. - const string format = "Path returned from {0} -> path:{1}, ending Page:{2}, use Page Path:{3}"; - messages.Add(string.Format(format, provider.ProviderConfig.ProviderName, customPath, endingPageName, useDnnPagePath)); + messages.Add($"Path returned from {provider.ProviderConfig.ProviderName} -> path:{customPath}, ending Page:{endingPageName}, use Page Path:{useDnnPagePath}"); break; // first module provider to change the Url is the only one used } } @@ -645,15 +644,15 @@ internal static bool TransformFriendlyUrlPath( private static void ClearCache() { - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + foreach (IPortalInfo portal in PortalController.Instance.GetPortals()) { - ClearCache(portal.PortalID); + ClearCache(portal.PortalId); } } private static void ClearCache(int portalId) { - var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, "ExtensionUrlProviders_{0}", portalId); DataCache.RemoveCache(cacheKey); } diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs index d7f0c4c9249..7156cde1708 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs @@ -15,26 +15,36 @@ namespace DotNetNuke.Entities.Urls public class FriendlyUrlOptions { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool ConvertDiacriticChars; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string IllegalChars; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public int MaxUrlPathLength; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string PageExtension; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string PunctuationReplacement; // 922 : change to use regexMatch pattern for allowable characters [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string RegexMatch; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public Dictionary ReplaceCharWithChar = new Dictionary(); [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string ReplaceChars; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool ReplaceDoubleChars; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string SpaceEncoding; private static readonly object RegexLookupLock = new object(); diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs index 1f2729527e5..873ecf3beab 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs @@ -171,7 +171,7 @@ internal static bool CheckUserProfileReplacement( if (user != null && !string.IsNullOrEmpty(user.VanityUrl)) { doReplacement = true; - urlName = (!string.IsNullOrEmpty(settings.VanityUrlPrefix)) ? string.Format("{0}/{1}", settings.VanityUrlPrefix, user.VanityUrl) : user.VanityUrl; + urlName = (!string.IsNullOrEmpty(settings.VanityUrlPrefix)) ? $"{settings.VanityUrlPrefix}/{user.VanityUrl}" : user.VanityUrl; urlWasChanged = true; } @@ -182,7 +182,7 @@ internal static bool CheckUserProfileReplacement( { // replacing for the parent tab id string childTabPath = TabIndexController.GetTabPath(tab, options, parentTraceId); - if (string.IsNullOrEmpty(childTabPath) == false) + if (!string.IsNullOrEmpty(childTabPath)) { // remove the parent tab path from the child tab path TabInfo profilePage = TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false); @@ -203,7 +203,7 @@ internal static bool CheckUserProfileReplacement( // append any extra remaining path value to the end if (!string.IsNullOrEmpty(remainingPath)) { - if (remainingPath.StartsWith("/") == false) + if (!remainingPath.StartsWith("/", StringComparison.Ordinal)) { changedPath += "/" + remainingPath; } @@ -251,7 +251,7 @@ private static void SplitUserIdFromFriendlyUrlPath( if (!string.IsNullOrEmpty(otherParametersPath)) { // remove the trailing slash from otherParamtersPath if it exists, because the other parameters may be anywhere in the path - if (otherParametersPath.EndsWith("/")) + if (otherParametersPath.EndsWith("/", StringComparison.Ordinal)) { otherParametersPath = otherParametersPath.Substring(0, otherParametersPath.Length - 1); } @@ -292,17 +292,17 @@ private static void SplitUserIdFromFriendlyUrlPath( } // add back the remainders - if (rem1ParmsGp != null && rem1ParmsGp.Success) + if (rem1ParmsGp is { Success: true, }) { remainingPath = rem1ParmsGp.Value; } - if (rem2ParmsGp != null && rem2ParmsGp.Success) + if (rem2ParmsGp is { Success: true, }) { remainingPath += rem2ParmsGp.Value; } - if (remainingPath.EndsWith("/")) + if (remainingPath.EndsWith("/", StringComparison.Ordinal)) { remainingPath = remainingPath.Substring(0, remainingPath.Length - 1); } @@ -325,7 +325,7 @@ private static void SplitUserIdFromFriendlyUrlPath( } } - if (remainingPath.Length > 0 && remainingPath.StartsWith("/") == false) + if (remainingPath.Length > 0 && !remainingPath.StartsWith("/", StringComparison.Ordinal)) { remainingPath = "/" + remainingPath; } diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs index 5c1d4e6777b..5bae28d4cdd 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs @@ -697,7 +697,7 @@ public string UseBaseFriendlyUrls if (this.useBaseFriendlyUrls == null) { this.useBaseFriendlyUrls = this.GetStringSetting(UseBaseFriendlyUrlsSetting, string.Empty); - if (!string.IsNullOrEmpty(this.useBaseFriendlyUrls) && !this.useBaseFriendlyUrls.EndsWith(";")) + if (!string.IsNullOrEmpty(this.useBaseFriendlyUrls) && !this.useBaseFriendlyUrls.EndsWith(";", StringComparison.Ordinal)) { this.useBaseFriendlyUrls += ";"; } diff --git a/DNN Platform/Library/Entities/Urls/InternalAlias.cs b/DNN Platform/Library/Entities/Urls/InternalAlias.cs index d03402a863f..9415cdd40a1 100644 --- a/DNN Platform/Library/Entities/Urls/InternalAlias.cs +++ b/DNN Platform/Library/Entities/Urls/InternalAlias.cs @@ -10,6 +10,7 @@ namespace DotNetNuke.Entities.Urls public class InternalAlias { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string HttpAlias; } } diff --git a/DNN Platform/Library/Entities/Urls/PageIndexData.cs b/DNN Platform/Library/Entities/Urls/PageIndexData.cs index df49d11b097..3911836f39f 100644 --- a/DNN Platform/Library/Entities/Urls/PageIndexData.cs +++ b/DNN Platform/Library/Entities/Urls/PageIndexData.cs @@ -11,8 +11,10 @@ namespace DotNetNuke.Entities.Urls internal class PageIndexData { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string LastPageKey; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string LastPageValue; } } diff --git a/DNN Platform/Library/Entities/Urls/RedirectController.cs b/DNN Platform/Library/Entities/Urls/RedirectController.cs index fcb45bc565d..25d87097372 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectController.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Urls using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.Text.RegularExpressions; using System.Web; @@ -220,7 +221,7 @@ internal static bool CheckForParameterRedirect( // changes the tabid of page, effects a page redirect along with a parameter redirect if (int.TryParse(parmPart, out tabId)) { - parms = parms.Replace("tabid/" + tabId.ToString(), string.Empty); + parms = parms.Replace("tabid/" + tabId.ToString(CultureInfo.InvariantCulture), string.Empty); } // remove the tabid/xx from the path @@ -264,7 +265,7 @@ internal static bool CheckForParameterRedirect( false, settings, Guid.Empty); - if (friendlyUrlNoParms.EndsWith("/") == false) + if (!friendlyUrlNoParms.EndsWith("/", StringComparison.Ordinal)) { friendlyUrlNoParms += "/"; } @@ -276,34 +277,34 @@ internal static bool CheckForParameterRedirect( { result.DebugMessages.Add(parmRedirect.Name + " tabId in redirect rule (tabId:" + - tabId.ToString() + ", portalId:" + - result.PortalId.ToString() + + tabId.ToString(CultureInfo.InvariantCulture) + ", portalId:" + + result.PortalId.ToString(CultureInfo.InvariantCulture) + " ), tab was not found"); } else { result.DebugMessages.Add(parmRedirect.Name + " tabId in redirect rule (tabId:" + - tabId.ToString() + ", portalId:" + - result.PortalId.ToString() + " ), tab found : " + + tabId.ToString(CultureInfo.InvariantCulture) + ", portalId:" + + result.PortalId.ToString(CultureInfo.InvariantCulture) + " ), tab found : " + tab.TabName); } } } - if (parms.StartsWith("//")) + if (parms.StartsWith("//", StringComparison.Ordinal)) { parms = parms.Substring(2); } - if (parms.StartsWith("/")) + if (parms.StartsWith("/", StringComparison.Ordinal)) { parms = parms.Substring(1); } if (settings.PageExtensionUsageType != PageExtensionUsageType.Never) { - if (parms.EndsWith("/")) + if (parms.EndsWith("/", StringComparison.Ordinal)) { parms = parms.TrimEnd('/'); } diff --git a/DNN Platform/Library/Entities/Urls/RedirectReason.cs b/DNN Platform/Library/Entities/Urls/RedirectReason.cs index 4ab36da5905..57f6774eca8 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectReason.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectReason.cs @@ -3,7 +3,8 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls -{ +{ +#pragma warning disable CA1707 // Identifiers should not contain underscores public enum RedirectReason { /// The URL was in an unfriendly format. @@ -119,5 +120,6 @@ public enum RedirectReason /// A non-permanent redirect. Tab_Temporary_Redirect = 37, - } + } +#pragma warning restore CA1707 } diff --git a/DNN Platform/Library/Entities/Urls/RedirectTokens.cs b/DNN Platform/Library/Entities/Urls/RedirectTokens.cs index 20bc31acb11..acd105686ed 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectTokens.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectTokens.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { + using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text.RegularExpressions; @@ -367,13 +368,13 @@ internal static string RemoveAnyRedirectTokensAndReasons(string rewritePath) if (p == "?") { result = result.Replace(tokenAndValue, string.Empty); - if (result.Contains("?&")) + if (result.Contains("?&", StringComparison.Ordinal)) { result = result.Replace("?&", "?"); } else { - if (result.EndsWith("?") || result.EndsWith("&")) + if (result.EndsWith("?", StringComparison.Ordinal) || result.EndsWith("&", StringComparison.Ordinal)) { // trim end result = result.Substring(0, result.Length - 1); diff --git a/DNN Platform/Library/Entities/Urls/RewriteController.cs b/DNN Platform/Library/Entities/Urls/RewriteController.cs index 1240ca54468..9e2dccb56b8 100644 --- a/DNN Platform/Library/Entities/Urls/RewriteController.cs +++ b/DNN Platform/Library/Entities/Urls/RewriteController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Urls using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -142,7 +143,7 @@ internal static bool AddSkinToRewritePath(int tabId, int portalId, ref string re { if (!string.IsNullOrEmpty(tab.SkinSrc)) { - message = "Tab " + tab.TabID.ToString() + " has skin specified : " + tab.SkinSrc; + message = "Tab " + tab.TabID.ToString(CultureInfo.InvariantCulture) + " has skin specified : " + tab.SkinSrc; if (skin != tab.SkinSrc) { message += " - " + skin + " not applied due to tab specific skin"; @@ -242,7 +243,7 @@ internal static string CleanExtension(string value, string extension, string lan replaced = true; } } - else if (result.EndsWith("/")) + else if (result.EndsWith("/", StringComparison.Ordinal)) { result = result.Substring(0, result.Length - 1); replaced = true; @@ -299,7 +300,7 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer parentTraceId); // clean up and prepare the url for scanning - if (url.EndsWith("/")) + if (url.EndsWith("/", StringComparison.Ordinal)) { url = url.TrimEnd('/'); } @@ -723,7 +724,7 @@ internal static void GetUrlWithQuerystring(HttpRequest request, Uri requestUri, if (querystring != string.Empty) { // set up the querystring and the fullUrl to include the querystring - if (querystring.StartsWith("?") == false) + if (!querystring.StartsWith("?", StringComparison.Ordinal)) { querystring = "?" + querystring; } @@ -755,10 +756,10 @@ internal static void IdentifyByPhysicalResource( { isPhysicalResource = false; checkFurtherForRewrite = true; - if (File.Exists(physicalPath) && !physicalPath.EndsWith("\\_noext.aspx")) + if (File.Exists(physicalPath) && !physicalPath.EndsWith(@"\_noext.aspx", StringComparison.OrdinalIgnoreCase)) { // resource found - string appPath = Globals.ApplicationMapPath + "\\default.aspx"; + string appPath = $@"{Globals.ApplicationMapPath}\default.aspx"; bool isDefaultAspxPath = false; if (!string.Equals(physicalPath, appPath, StringComparison.OrdinalIgnoreCase)) { @@ -870,7 +871,7 @@ internal static bool IdentifyByRegEx( // if a match is found here, there is the potential for a 'friendlier' url if (sesUrlParams.Trim().Length > 0) { - sesUrlParams = sesUrlParams.Replace("\\", "/"); + sesUrlParams = sesUrlParams.Replace(@"\", "/"); var urlParams = sesUrlParams.Split('/'); for (var x = 1; x <= urlParams.Length - 1; x++) { @@ -894,7 +895,7 @@ internal static bool IdentifyByRegEx( rewritePath = AddQueryStringToRewritePath(rewritePath, queryString); // 832 : check for leading ~ - if not there, then redirect - if (sendTo.StartsWith("~")) + if (sendTo.StartsWith("~", StringComparison.Ordinal)) { doRewrite = true; SetRewriteParameters(ref result, rewritePath); @@ -1243,7 +1244,7 @@ internal static string RewriteParameters( if (stripLoneParm) { newUrl = UrlParamsRegex.Replace(newUrl, "&"); - if (newUrl.EndsWith("&")) + if (newUrl.EndsWith("&", StringComparison.Ordinal)) { newUrl = newUrl.Substring(0, newUrl.Length - 1); } @@ -1364,7 +1365,7 @@ internal static string RewriteParameters( // makes sure the newUrl has got a trailing ampersand or a ? to start the query string if (newUrl.Contains("?")) { - if (newUrl.EndsWith("&") == false) + if (newUrl.EndsWith("&", StringComparison.Ordinal) == false) { newUrl += "&"; } @@ -1376,7 +1377,7 @@ internal static string RewriteParameters( } // makes sure the new parms string hasn't got a starting ampersand - if (parms.StartsWith("&")) + if (parms.StartsWith("&", StringComparison.Ordinal)) { parms = parms.Substring(1); } @@ -1417,7 +1418,7 @@ private static string AddQueryStringToRewritePath(string rewritePath, string que if (queryString != string.Empty) { bool rewritePathHasQuery = rewritePath.IndexOf("?", StringComparison.Ordinal) != -1; - if (queryString.StartsWith("?")) + if (queryString.StartsWith("?", StringComparison.Ordinal)) { queryString = queryString.Substring(1); } @@ -1496,7 +1497,7 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst // on other server software installed (apparently) // so check the raw Url and the url, and see if they are the same except for the /default.aspx string rawUrl = result.RawUrl; - if (url.ToLowerInvariant().EndsWith(rawUrl + defaultPage.ToLowerInvariant())) + if (url.ToLowerInvariant().EndsWith(rawUrl + defaultPage, StringComparison.OrdinalIgnoreCase)) { // special case - change the url to be equal to the raw Url url = url.Substring(0, url.Length - defaultPage.Length); @@ -1518,7 +1519,7 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst if (portal.HomeTabId == -1) { string tabKey = url; - if (tabKey.EndsWith("/")) + if (tabKey.EndsWith("/", StringComparison.Ordinal)) { tabKey = tabKey.TrimEnd('/'); } @@ -1569,18 +1570,18 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst if (checkForCustomAlias) { - // ok, this isnt' a chosen portal alias, check the list of custom aliases + // ok, this isn't a chosen portal alias, check the list of custom aliases List customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings); if (customAliasesForTabs != null && customAliasesForTabs.Contains(portalAlias.HTTPAlias.ToLowerInvariant())) { // ok, the alias is used as a custom tab, so now look in the dictionary to see if it's used a 'root' context string tabKey = url.ToLowerInvariant(); - if (tabKey.EndsWith("/")) + if (tabKey.EndsWith("/", StringComparison.Ordinal)) { tabKey = tabKey.TrimEnd('/'); } - if (tabKey.EndsWith("/default.aspx")) + if (tabKey.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase)) { tabKey = tabKey.Substring(0, tabKey.Length - 13); // 13 = "/default.aspx".length } @@ -1598,18 +1599,18 @@ private static string CheckIfPortalAlias(string url, NameValueCollection queryst } } - if (customTabAlias == false) + if (!customTabAlias) { int tabId; if (!string.IsNullOrEmpty(querystringCol["TabId"])) { - tabId = Convert.ToInt32(querystringCol["TabId"]); + tabId = Convert.ToInt32(querystringCol["TabId"], CultureInfo.InvariantCulture); result.Action = ActionType.CheckFor301; } else { // not a custom alias for a specific tab, so it must be the home page for the portal we identified, - // if its first request and splash page defined, then redirec to splash page. + // if its first request and splash page defined, then redirect to splash page. if (portal.SplashTabId > Null.NullInteger && HttpContext.Current != null && !HttpContext.Current.Request.Cookies.AllKeys.Contains("SplashPageView")) { @@ -1718,10 +1719,10 @@ private static bool CheckSpecialCase(string tabKeyVal, SharedDictionary>( new CacheItemArgs(cacheKey, 20, CacheItemPriority.High, portalId), - c => new Dictionary()); + static c => new Dictionary()); if (!vanityUrlLookupDictionary.TryGetValue(vanityUrl, out var user)) { @@ -1771,7 +1772,7 @@ private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrl var user = GetUser(PortalController.GetEffectivePortalId(result.PortalId), vanityUrl); if (user != null) { - userParam = "UserId=" + user.UserID.ToString(); + userParam = "UserId=" + user.UserID.ToString(CultureInfo.InvariantCulture); // Get the User profile Tab var portal = PortalController.Instance.GetPortal(result.PortalId); @@ -1781,7 +1782,7 @@ private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrl string profilePagePath = TabPathHelper.GetFriendlyUrlTabPath(profilePage, options, Guid.NewGuid()); // modify lookup key; - tabLookUpKey = tabLookUpKey.Replace(TabKeySeparator + string.Format("{0}/{1}", settings.VanityUrlPrefix, vanityUrl), TabKeySeparator + profilePagePath.TrimStart('/').ToLowerInvariant()); + tabLookUpKey = tabLookUpKey.Replace($"{TabKeySeparator}{settings.VanityUrlPrefix}/{vanityUrl}", TabKeySeparator + profilePagePath.TrimStart('/').ToLowerInvariant()); using (tabDict.GetReadLock()) { @@ -1814,7 +1815,7 @@ private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrl var tabPath = tabLookUpKey.Split(TabKeySeparators, StringSplitOptions.None)[1]; using (tabDict.GetReadLock()) { - foreach (var key in tabDict.Keys.Where(k => k.EndsWith(TabKeySeparator + tabPath))) + foreach (var key in tabDict.Keys.Where(k => k.EndsWith(TabKeySeparator + tabPath, StringComparison.OrdinalIgnoreCase))) { if (tabDict[key].Contains("language=" + currentLocale)) { diff --git a/DNN Platform/Library/Entities/Urls/RewriterUtils.cs b/DNN Platform/Library/Entities/Urls/RewriterUtils.cs index 6d7d59311c6..c0c733267cb 100644 --- a/DNN Platform/Library/Entities/Urls/RewriterUtils.cs +++ b/DNN Platform/Library/Entities/Urls/RewriterUtils.cs @@ -59,7 +59,7 @@ internal static string ResolveUrl(string appPath, string url) } // String does not contain a ~, so just return Url - if (url.StartsWith("~") == false) + if (!url.StartsWith("~", StringComparison.Ordinal)) { return url; } @@ -70,8 +70,8 @@ internal static string ResolveUrl(string appPath, string url) return appPath; } - var seperatorChar = url.ToCharArray()[1]; - if (seperatorChar == '/' || seperatorChar == '\\') + var separatorChar = url.ToCharArray()[1]; + if (separatorChar is '/' or '\\') { // Url looks like ~/ or ~\ if (appPath.Length > 1) @@ -109,8 +109,7 @@ internal static bool OmitFromRewriteProcessing(string localPath) var omissions = omitSettings.Split('|'); - bool shouldOmit = omissions.Any(x => localPath.EndsWith(x)); - + bool shouldOmit = omissions.Any(x => localPath.EndsWith(x, StringComparison.OrdinalIgnoreCase)); if (!shouldOmit) { shouldOmit = Globals.ServicesFrameworkRegex.IsMatch(localPath); diff --git a/DNN Platform/Library/Entities/Urls/TabIndexController.cs b/DNN Platform/Library/Entities/Urls/TabIndexController.cs index 4bd698868ec..e19146cdf74 100644 --- a/DNN Platform/Library/Entities/Urls/TabIndexController.cs +++ b/DNN Platform/Library/Entities/Urls/TabIndexController.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Entities.Urls using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.Linq; using System.Threading; @@ -44,13 +45,13 @@ public static void InvalidateDictionary(string reason, PageIndexData rebuildData } log.AddProperty("Url Rewriting Caching Message", "Page Index Cache Cleared. Reason: " + reason); - log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString()); + log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } internal static string CreateRewritePath(int tabId, string cultureCode, params string[] keyValuePair) { - string rewritePath = "?TabId=" + tabId.ToString(); + string rewritePath = "?TabId=" + tabId.ToString(CultureInfo.InvariantCulture); // 736 : 5.5 compatibility - identify tab rewriting at source by tab culture code RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, cultureCode); @@ -263,15 +264,15 @@ internal static PortalAliasInfo GetPortalAliasByPortal(int portalId, string port portalAliasInfo = portalAliasCollection.SingleOrDefault(a => a.HTTPAlias == currentAlias); if (portalAliasInfo != null) { - string httpAlias = portalAliasInfo.HTTPAlias.ToLowerInvariant(); + string httpAlias = portalAliasInfo.HTTPAlias; if (httpAlias.StartsWith(portalAlias, StringComparison.OrdinalIgnoreCase) && portalAliasInfo.PortalID == portalId) { retValue = portalAliasInfo; break; } - httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); - if (httpAlias.StartsWith(portalAlias, StringComparison.InvariantCultureIgnoreCase) && portalAliasInfo.PortalID == portalId) + httpAlias = httpAlias.StartsWith("www.", StringComparison.OrdinalIgnoreCase) ? httpAlias.Substring("www.".Length) : $"www.{httpAlias}"; + if (httpAlias.StartsWith(portalAlias, StringComparison.OrdinalIgnoreCase) && portalAliasInfo.PortalID == portalId) { retValue = portalAliasInfo; break; @@ -319,7 +320,7 @@ internal static string GetTabPath(TabInfo tab, FriendlyUrlOptions options, Guid if (tpd.Count > 0) { // get the path from the dictionary - string tabKey = tab.TabID.ToString(); + string tabKey = tab.TabID.ToString(CultureInfo.InvariantCulture); if (tpd.TryGetValue(tabKey, out var path)) { tabPath = path; @@ -370,7 +371,7 @@ private static void AddCustomRedirectsToDictionary( // allow for additional qs parameters if (!string.IsNullOrEmpty(redirect.QueryString)) { - rewritePath += redirect.QueryString.StartsWith("&") ? redirect.QueryString : "&" + redirect.QueryString; + rewritePath += redirect.QueryString.StartsWith("&", StringComparison.Ordinal) ? redirect.QueryString : "&" + redirect.QueryString; } string redirectTabPath = redirect.Url; @@ -697,7 +698,7 @@ private static void AddStandardPagesToDict( int tabDepth = 0; // we ignore tab depth as it is only one for these in-built urls // 850 : add in the culture code to the redirect if supplied - string portalRewritePath = "?PortalId=" + portalId.ToString(); + string portalRewritePath = "?PortalId=" + portalId.ToString(CultureInfo.InvariantCulture); string cultureRewritePath = string.Empty; if (!string.IsNullOrEmpty(cultureCode)) { @@ -1228,9 +1229,9 @@ private static void AddToTabDict( && foundTab.TabIdOriginal != "-1") { // check whether to log for this or not - if (checkForDupUrls && foundTab.TabIdOriginal != tabId.ToString()) + if (checkForDupUrls && foundTab.TabIdOriginal != tabId.ToString(CultureInfo.InvariantCulture)) { - // don't show message for where same tab is being added twice) + // don't show message for where same tab is being added twice // there is a naming conflict where this alias/tab path could be mistaken string tab1Name = string.Empty, tab2Name = string.Empty; var dupInSameCulture = false; @@ -1266,7 +1267,7 @@ private static void AddToTabDict( { string msg = "Page naming conflict. Url of (" + foundTab.TabPath + ") resolves to two separate pages (" + tab1Name + " [tabid = " + - foundTab.TabIdOriginal + "], " + tab2Name + " [tabid = " + tabId.ToString() + + foundTab.TabIdOriginal + "], " + tab2Name + " [tabid = " + tabId.ToString(CultureInfo.InvariantCulture) + "]). Only the second page will be shown for the url."; const string msg2 = "PLEASE NOTE : this is an information message only, this message does not affect site operations in any way."; @@ -1281,7 +1282,7 @@ private static void AddToTabDict( log.AddProperty( "Hide this message", "To stop this message from appearing in the log, uncheck the option for 'Produce an Exception in the Site Log if two pages have the same name/path?' in the Advanced Url Rewriting settings."); - log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString()); + log.AddProperty("Thread Id", Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -1291,14 +1292,14 @@ private static void AddToTabDict( dupCheckDict.Remove(dupKey); // add this tab to the duplicate key dictionary - dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(), dupKey, isDeleted)); + dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(CultureInfo.InvariantCulture), dupKey, isDeleted)); } } else { // add this tab to the duplicate key dictionary - the dup key check dict is always maintained // regardless of whether checking is employed or not - dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(), dupKey, isDeleted)); + dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(CultureInfo.InvariantCulture), dupKey, isDeleted)); } } @@ -1448,10 +1449,10 @@ private static SharedDictionary BuildTabDictionary( // Add site root redirects AddSiteRootRedirects(pathSizes, tabIndex, chosenAliases, hasSiteRootRedirect, dupCheck, usingHttpAliases); - // add in any internal aliases as valid aliase + // add in any internal aliases as valid alias AddInternalAliases(settings, usingHttpAliases); - // loop through each tab and add all of the various Url paths that the tab can be found with, + // loop through each tab and add all the various Url paths that the tab can be found with, // for all aliases the tab will be used with foreach (TabInfo tab in tabs.Values) { @@ -1460,11 +1461,11 @@ private static SharedDictionary BuildTabDictionary( // 935 : get the tab path and add to the tab path dictionary if it's not just a straight conversion of the TabPath value // bool modified; string tabPath = TabPathHelper.GetFriendlyUrlTabPath(tab, options, parentTraceId); - string tabKey = tab.TabID.ToString(); + string tabKey = tab.TabID.ToString(CultureInfo.InvariantCulture); using (portalTabPathDictionary.GetWriteLock()) { - if (portalTabPathDictionary.ContainsKey(tabKey) == false) + if (!portalTabPathDictionary.ContainsKey(tabKey)) { portalTabPathDictionary.Add(tabKey, tabPath); } diff --git a/DNN Platform/Library/Entities/Urls/TabPathHelper.cs b/DNN Platform/Library/Entities/Urls/TabPathHelper.cs index fc0b391b77f..2ca0ae31f1d 100644 --- a/DNN Platform/Library/Entities/Urls/TabPathHelper.cs +++ b/DNN Platform/Library/Entities/Urls/TabPathHelper.cs @@ -279,7 +279,7 @@ internal static string GetTabPath( // 770 : check for custom alias in these tabs if (checkForCustomHttpAlias && customAliasForTabs != null) { - string key = tab.TabID.ToString() + ":" + cultureCodeKey; + string key = tab.TabID.ToString(CultureInfo.InvariantCulture) + ":" + cultureCodeKey; using (customAliasForTabs.GetReadLock()) { if (customAliasForTabs.TryGetValue(key, out var alias)) diff --git a/DNN Platform/Library/Entities/Urls/UrlAction.cs b/DNN Platform/Library/Entities/Urls/UrlAction.cs index 85028c7731e..65e8f5d44ab 100644 --- a/DNN Platform/Library/Entities/Urls/UrlAction.cs +++ b/DNN Platform/Library/Entities/Urls/UrlAction.cs @@ -96,6 +96,7 @@ public UrlAction(string scheme, string applicationPath, string physicalPath) public string DomainName { get; set; } + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public Exception Ex { get; set; } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] @@ -279,7 +280,7 @@ public void SetRedirectAllowed(string path, FriendlyUrlSettings settings) private void Constructor(string scheme, string applicationPath, string physicalPath) { - if (scheme.EndsWith("://") == false) + if (!scheme.EndsWith("://", StringComparison.Ordinal)) { this.Scheme = scheme + "://"; } diff --git a/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs b/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs index 1de6e9ded59..ea8ccd8b49e 100644 --- a/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs +++ b/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs @@ -4,8 +4,10 @@ namespace DotNetNuke.Entities.Urls { using System; + using System.Globalization; using System.Web; + using DotNetNuke.Abstractions.Logging; using DotNetNuke.Common.Utilities; using DotNetNuke.Instrumentation; using DotNetNuke.Services.Log.EventLog; @@ -69,10 +71,10 @@ public static void Log404(HttpRequest request, FriendlyUrlSettings settings, Url { var log = new LogInfo { - LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), + LogTypeKey = nameof(EventLogType.PAGE_NOT_FOUND_404), LogPortalID = (result.PortalAlias != null) ? result.PortalId : -1, }; - log.LogProperties.Add(new LogDetailInfo("TabId", (result.TabId > 0) ? result.TabId.ToString() : string.Empty)); + log.LogProperties.Add(new LogDetailInfo("TabId", (result.TabId > 0) ? result.TabId.ToString(CultureInfo.InvariantCulture) : string.Empty)); log.LogProperties.Add(new LogDetailInfo("PortalAlias", (result.PortalAlias != null) ? result.PortalAlias.HTTPAlias : string.Empty)); log.LogProperties.Add(new LogDetailInfo("OriginalUrl", result.RawUrl)); @@ -140,8 +142,8 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction log.AddProperty("Redirect Location", string.IsNullOrEmpty(result.FinalUrl) ? "[no redirect]" : result.FinalUrl); log.AddProperty("Action", result.Action.ToString()); log.AddProperty("Reason", result.Reason.ToString()); - log.AddProperty("Portal Id", result.PortalId.ToString()); - log.AddProperty("Tab Id", result.TabId.ToString()); + log.AddProperty("Portal Id", result.PortalId.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("Tab Id", result.TabId.ToString(CultureInfo.InvariantCulture)); log.AddProperty("Http Alias", result.PortalAlias != null ? result.PortalAlias.HTTPAlias : "Null"); if (result.DebugMessages != null) @@ -149,7 +151,7 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction int i = 1; foreach (string msg in result.DebugMessages) { - log.AddProperty("Debug Message " + i.ToString(), msg); + log.AddProperty("Debug Message " + i.ToString(CultureInfo.InvariantCulture), msg); i++; } } diff --git a/DNN Platform/Library/Entities/Urls/XmlHelpers.cs b/DNN Platform/Library/Entities/Urls/XmlHelpers.cs index fb0bf847839..989600d8a19 100644 --- a/DNN Platform/Library/Entities/Urls/XmlHelpers.cs +++ b/DNN Platform/Library/Entities/Urls/XmlHelpers.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Urls { using System; using System.Collections.Generic; + using System.Globalization; using DotNetNuke.Entities.Tabs; @@ -73,7 +74,7 @@ internal static List TabIdsFromAttributes(string tabIdsRaw, string tabNames } else { - messages.Add("TabName " + tabName + " not found for portalId " + portalId.ToString()); + messages.Add("TabName " + tabName + " not found for portalId " + portalId.ToString(CultureInfo.InvariantCulture)); } } } diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs index 754c8c359a3..8efa85d2751 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Entities.Users.Membership { + using System; using System.Diagnostics.CodeAnalysis; using System.Web; using System.Web.Security; @@ -87,10 +88,10 @@ public PasswordFormat PasswordFormat private static bool IsInstallRequest(HttpRequest request) { - var url = request.Url.LocalPath.ToLowerInvariant(); + var url = request.Url.LocalPath; - return url.EndsWith("/install.aspx") - || url.Contains("/installwizard.aspx"); + return url.EndsWith("/install.aspx", StringComparison.OrdinalIgnoreCase) + || url.Contains("/installwizard.aspx", StringComparison.OrdinalIgnoreCase); } } } diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs index 8bff4be74d2..728698d9223 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Entities.Users { using System; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using DotNetNuke.Services.Tokens; @@ -20,15 +21,10 @@ public MembershipPropertyAccess(UserInfo user) } /// - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } + public CacheLevel Cacheability => CacheLevel.notCacheable; /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { UserMembership objMembership = this.objUser.Membership; @@ -74,7 +70,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "passwordquestion": return PropertyAccess.FormatString(objMembership.PasswordQuestion, format); case "passwordresettoken": - return PropertyAccess.FormatString(Convert.ToString(this.objUser.PasswordResetToken), format); + return PropertyAccess.FormatString(Convert.ToString(this.objUser.PasswordResetToken, CultureInfo.InvariantCulture), format); case "passwordresetexpiration": return PropertyAccess.FormatString(this.objUser.PasswordResetExpiration.ToString(formatProvider), format); case "updatepassword": diff --git a/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs b/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs index af0055afddc..861871d45e3 100644 --- a/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs +++ b/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs @@ -2,35 +2,36 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Users.Membership -{ - using System; - using System.Data; - - using DotNetNuke.Common.Utilities; - - [Serializable] - public class PasswordHistory : BaseEntityInfo - { - public int PasswordHistoryId { get; set; } - - public int UserId { get; set; } - - public string Password { get; set; } - - public string PasswordSalt { get; set; } - - /// Fill the object with data from database. - /// the data reader. - public void Fill(IDataReader dr) - { - this.PasswordHistoryId = Convert.ToInt32(dr["PasswordHistoryID"]); - this.UserId = Null.SetNullInteger(dr["UserID"]); - this.Password = dr["Password"].ToString(); - this.PasswordSalt = dr["PasswordSalt"].ToString(); - - // add audit column data - this.FillInternal(dr); - } - } -} +namespace DotNetNuke.Entities.Users.Membership +{ + using System; + using System.Data; + using System.Globalization; + + using DotNetNuke.Common.Utilities; + + [Serializable] + public class PasswordHistory : BaseEntityInfo + { + public int PasswordHistoryId { get; set; } + + public int UserId { get; set; } + + public string Password { get; set; } + + public string PasswordSalt { get; set; } + + /// Fill the object with data from database. + /// the data reader. + public void Fill(IDataReader dr) + { + this.PasswordHistoryId = Convert.ToInt32(dr["PasswordHistoryID"], CultureInfo.InvariantCulture); + this.UserId = Null.SetNullInteger(dr["UserID"]); + this.Password = dr["Password"].ToString(); + this.PasswordSalt = dr["PasswordSalt"].ToString(); + + // add audit column data + this.FillInternal(dr); + } + } +} diff --git a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs index eb8fb75825a..cd2d5f5d1e8 100644 --- a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Entities.Users // ReSharper restore CheckNamespace { using System; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Web; @@ -154,26 +155,24 @@ public static string GetRichValue(ProfilePropertyDefinition property, string for formatString = "g"; } - result = int.Parse(property.PropertyValue).ToString(formatString, formatProvider); + result = int.Parse(property.PropertyValue, CultureInfo.InvariantCulture).ToString(formatString, formatProvider); break; case "page": - int tabid; - if (int.TryParse(property.PropertyValue, out tabid)) + if (int.TryParse(property.PropertyValue, out var tabId)) { - TabInfo tab = TabController.Instance.GetTab(tabid, Null.NullInteger, false); + TabInfo tab = TabController.Instance.GetTab(tabId, Null.NullInteger, false); if (tab != null) { - result = string.Format("{1}", TestableGlobals.Instance.NavigateURL(tabid), tab.LocalizedTabName); + result = $"{tab.LocalizedTabName}"; } } break; case "image": // File is stored as a FileID - int fileID; - if (int.TryParse(property.PropertyValue, out fileID) && fileID > 0) + if (int.TryParse(property.PropertyValue, out var fileId) && fileId > 0) { - result = Globals.LinkClick(string.Format("fileid={0}", fileID), Null.NullInteger, Null.NullInteger); + result = Globals.LinkClick($"fileid={fileId}", Null.NullInteger, Null.NullInteger); } else { @@ -199,8 +198,8 @@ public static string GetRichValue(ProfilePropertyDefinition property, string for /// A string representing the data type such as: truefalse, date, datetime, integer, page, image or richtext. public static string DisplayDataType(ProfilePropertyDefinition definition) { - string cacheKey = string.Format("DisplayDataType:{0}", definition.DataType); - string strDataType = Convert.ToString(DataCache.GetCache(cacheKey)) + string.Empty; + string cacheKey = string.Format(CultureInfo.InvariantCulture, "DisplayDataType:{0}", definition.DataType); + string strDataType = Convert.ToString(DataCache.GetCache(cacheKey), CultureInfo.InvariantCulture) + string.Empty; if (strDataType == string.Empty) { var objListController = new ListController(); @@ -212,13 +211,13 @@ public static string DisplayDataType(ProfilePropertyDefinition definition) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { - if (currentScope >= Scope.DefaultSettings && this.user != null && this.user.Profile != null) + if (currentScope >= Scope.DefaultSettings && this.user is { Profile: not null, }) { var profile = this.user.Profile; - var property = profile.ProfileProperties.Cast() - .SingleOrDefault(p => string.Equals(p.PropertyName, propertyName, StringComparison.OrdinalIgnoreCase)); + var property = profile.ProfileProperties.SingleOrDefault(p => string.Equals(p.PropertyName, propertyName, StringComparison.OrdinalIgnoreCase)); if (property != null) { diff --git a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs index 0c34d991a89..0d1519b9ad6 100644 --- a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs +++ b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Entities.Users { using System; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Xml.Serialization; @@ -25,6 +26,7 @@ namespace DotNetNuke.Entities.Users public class UserProfile : IIndexable { #pragma warning disable SA1310 // Field names should not contain underscore +#pragma warning disable CA1707 // Identifiers should not contain underscores #pragma warning disable SA1600 // Elements should be documented // Name properties [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] @@ -74,6 +76,7 @@ public class UserProfile : IIndexable [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Biography = UserProfileBiography; #pragma warning restore SA1310 // Field names should not contain underscore +#pragma warning restore CA1707 // Identifiers should not contain underscores #pragma warning restore SA1600 // Elements should be documented private const string UserProfileFirstName = "FirstName"; @@ -155,7 +158,7 @@ public string PhotoURL bool isVisible = ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, user, this.user); if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) { - var fileInfo = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); + var fileInfo = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue, CultureInfo.InvariantCulture)); if (fileInfo != null) { photoURL = FileManager.Instance.GetUrl(fileInfo); @@ -462,19 +465,17 @@ public object this[string name] set { string stringValue; - if (value is DateTime) + if (value is DateTime dateValue) { - var dateValue = (DateTime)value; stringValue = dateValue.ToString(CultureInfo.InvariantCulture); } - else if (value is TimeZoneInfo) + else if (value is TimeZoneInfo timezoneValue) { - var timezoneValue = (TimeZoneInfo)value; stringValue = timezoneValue.Id; } else { - stringValue = Convert.ToString(value); + stringValue = Convert.ToString(value, CultureInfo.InvariantCulture); } this.SetProfileProperty(name, stringValue); @@ -522,11 +523,11 @@ public string GetPropertyValue(string propName) var dataType = controller.GetListEntryInfo("DataType", profileProp.DataType); if (dataType == null) { - LoggerSource.Instance.GetLogger(typeof(UserProfile)).ErrorFormat("Invalid data type {0} for profile property {1}", profileProp.DataType, profileProp.PropertyName); + LoggerSource.Instance.GetLogger(typeof(UserProfile)).ErrorFormat(CultureInfo.InvariantCulture, "Invalid data type {0} for profile property {1}", profileProp.DataType, profileProp.PropertyName); return propValue; } - if (dataType.Value == "Country" || dataType.Value == "Region") + if (dataType.Value is "Country" or "Region") { propValue = GetListValue(dataType.Value, propValue); } diff --git a/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs index ad1ca86d1a2..c2e080de67f 100644 --- a/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs @@ -62,10 +62,12 @@ private static void AddFollowerRequestNotification(UserInfo initiatingUser, User { var notificationType = NotificationsController.Instance.GetNotificationType(IsFollowing(targetUser, initiatingUser) ? FollowerRequest : FollowBackRequest); var subject = string.Format( + CultureInfo.CurrentCulture, Localization.GetString("AddFollowerRequestSubject", Localization.GlobalResourceFile), initiatingUser.DisplayName); var body = string.Format( + CultureInfo.CurrentCulture, Localization.GetString("AddFollowerRequestBody", Localization.GlobalResourceFile), initiatingUser.DisplayName); @@ -79,14 +81,14 @@ private static void AddFollowerRequestNotification(UserInfo initiatingUser, User SenderUserID = initiatingUser.UserID, }; - NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, null, new List { targetUser }); + NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, null, [targetUser,]); } private static bool IsFollowing(UserInfo user1, UserInfo user2) { var userRelationship = RelationshipController.Instance.GetFollowerRelationship(user1, user2); - return userRelationship != null && userRelationship.Status == RelationshipStatus.Accepted; + return userRelationship is { Status: RelationshipStatus.Accepted, }; } } } diff --git a/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs index 4aacd616630..ef8f9b2d737 100644 --- a/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs @@ -106,10 +106,12 @@ private static void AddFriendRequestNotification(UserInfo initiatingUser, UserIn var notificationType = NotificationsController.Instance.GetNotificationType(FriendRequest); var language = GetUserPreferredLocale(targetUser)?.Name; var subject = string.Format( + CultureInfo.CurrentCulture, Localization.GetString("AddFriendRequestSubject", Localization.GlobalResourceFile, language), initiatingUser.DisplayName); var body = string.Format( + CultureInfo.CurrentCulture, Localization.GetString("AddFriendRequestBody", Localization.GlobalResourceFile, language), initiatingUser.DisplayName); diff --git a/DNN Platform/Library/Entities/Users/Social/Relationship.cs b/DNN Platform/Library/Entities/Users/Social/Relationship.cs index e58b085878d..4b534aee6db 100644 --- a/DNN Platform/Library/Entities/Users/Social/Relationship.cs +++ b/DNN Platform/Library/Entities/Users/Social/Relationship.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Users.Social { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; @@ -109,13 +110,13 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.RelationshipId = Convert.ToInt32(dr["RelationshipID"]); + this.RelationshipId = Convert.ToInt32(dr["RelationshipID"], CultureInfo.InvariantCulture); this.UserId = Null.SetNullInteger(dr["UserID"]); this.PortalId = Null.SetNullInteger(dr["PortalID"]); this.Name = dr["Name"].ToString(); this.Description = dr["Description"].ToString(); - this.DefaultResponse = (RelationshipStatus)Convert.ToInt32(dr["DefaultResponse"]); - this.RelationshipTypeId = Convert.ToInt32(dr["RelationshipTypeID"]); + this.DefaultResponse = (RelationshipStatus)Convert.ToInt32(dr["DefaultResponse"], CultureInfo.InvariantCulture); + this.RelationshipTypeId = Convert.ToInt32(dr["RelationshipTypeID"], CultureInfo.InvariantCulture); // add audit column data this.FillInternal(dr); diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs index 4f850b6efb0..c758df2f058 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Entities.Users.Social { using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Abstractions.Logging; @@ -52,6 +53,7 @@ public void DeleteRelationshipType(RelationshipType relationshipType) // log event string logContent = string.Format( + CultureInfo.InvariantCulture, Localization.GetString("RelationshipType_Deleted", Localization.GlobalResourceFile), relationshipType.Name, relationshipType.RelationshipTypeId); @@ -96,6 +98,7 @@ public void SaveRelationshipType(RelationshipType relationshipType) // log event string logContent = string.Format( + CultureInfo.CurrentCulture, Localization.GetString(localizationKey, Localization.GlobalResourceFile), relationshipType.Name); this.AddLog(logContent); @@ -114,6 +117,7 @@ public void DeleteRelationship(Relationship relationship) // log event string logContent = string.Format( + CultureInfo.InvariantCulture, Localization.GetString("Relationship_Deleted", Localization.GlobalResourceFile), relationship.Name, relationship.RelationshipId); @@ -145,7 +149,7 @@ public IList GetRelationshipsByPortalId(int portalId) } var cacheArgs = new CacheItemArgs( - string.Format(DataCache.RelationshipByPortalIDCacheKey, pid), + string.Format(CultureInfo.InvariantCulture, DataCache.RelationshipByPortalIDCacheKey, pid), DataCache.RelationshipByPortalIDCacheTimeOut, DataCache.RelationshipByPortalIDCachePriority, pid); @@ -172,6 +176,7 @@ public void SaveRelationship(Relationship relationship) // log event string logContent = string.Format( + CultureInfo.CurrentCulture, Localization.GetString(localizationKey, Localization.GlobalResourceFile), relationship.Name); this.AddLog(logContent); @@ -190,6 +195,7 @@ public void DeleteUserRelationship(UserRelationship userRelationship) // log event string logContent = string.Format( + CultureInfo.InvariantCulture, Localization.GetString("UserRelationship_Deleted", Localization.GlobalResourceFile), userRelationship.UserRelationshipId, userRelationship.UserId, @@ -244,6 +250,7 @@ public void SaveUserRelationship(UserRelationship userRelationship) // log event string logContent = string.Format( + CultureInfo.InvariantCulture, Localization.GetString(localizationKey, Localization.GlobalResourceFile), userRelationship.UserRelationshipId, userRelationship.UserId, @@ -264,6 +271,7 @@ public void DeleteUserRelationshipPreference(UserRelationshipPreference userRela // log event string logContent = string.Format( + CultureInfo.InvariantCulture, Localization.GetString("UserRelationshipPreference_Deleted", Localization.GlobalResourceFile), userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, @@ -303,6 +311,7 @@ public void SaveUserRelationshipPreference(UserRelationshipPreference userRelati // log event string logContent = string.Format( + CultureInfo.InvariantCulture, Localization.GetString(localizationKey, Localization.GlobalResourceFile), userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, @@ -569,7 +578,7 @@ private static void ClearRelationshipCache(Relationship relationship) { if (relationship.UserId == Null.NullInteger) { - DataCache.RemoveCache(string.Format(DataCache.RelationshipByPortalIDCacheKey, relationship.PortalId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.RelationshipByPortalIDCacheKey, relationship.PortalId)); } } diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs index 8d4718de784..51f843f0346 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Users { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Entities.Modules; @@ -63,10 +64,10 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.RelationshipTypeId = Convert.ToInt32(dr["RelationshipTypeID"]); + this.RelationshipTypeId = Convert.ToInt32(dr["RelationshipTypeID"], CultureInfo.InvariantCulture); this.Name = dr["Name"].ToString(); this.Description = dr["Description"].ToString(); - this.Direction = (RelationshipDirection)Convert.ToInt32(dr["Direction"]); + this.Direction = (RelationshipDirection)Convert.ToInt32(dr["Direction"], CultureInfo.InvariantCulture); // add audit column data this.FillInternal(dr); diff --git a/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs b/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs index bc4d6232533..6c448c11792 100644 --- a/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs +++ b/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Users.Social { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Entities.Modules; @@ -65,11 +66,11 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.UserRelationshipId = Convert.ToInt32(dr["UserRelationshipID"]); - this.UserId = Convert.ToInt32(dr["UserID"]); - this.RelatedUserId = Convert.ToInt32(dr["RelatedUserID"]); - this.RelationshipId = Convert.ToInt32(dr["RelationshipID"]); - this.Status = (RelationshipStatus)Convert.ToInt32(dr["Status"]); + this.UserRelationshipId = Convert.ToInt32(dr["UserRelationshipID"], CultureInfo.InvariantCulture); + this.UserId = Convert.ToInt32(dr["UserID"], CultureInfo.InvariantCulture); + this.RelatedUserId = Convert.ToInt32(dr["RelatedUserID"], CultureInfo.InvariantCulture); + this.RelationshipId = Convert.ToInt32(dr["RelationshipID"], CultureInfo.InvariantCulture); + this.Status = (RelationshipStatus)Convert.ToInt32(dr["Status"], CultureInfo.InvariantCulture); // add audit column data this.FillInternal(dr); diff --git a/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs b/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs index 57bcbf27856..0c14fd1deee 100644 --- a/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs +++ b/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Users.Social { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Entities.Modules; @@ -59,10 +60,10 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.PreferenceId = Convert.ToInt32(dr["PreferenceID"]); - this.UserId = Convert.ToInt32(dr["UserID"]); - this.RelationshipId = Convert.ToInt32(dr["RelationshipID"]); - this.DefaultResponse = (RelationshipStatus)Convert.ToInt32(dr["DefaultResponse"]); + this.PreferenceId = Convert.ToInt32(dr["PreferenceID"], CultureInfo.InvariantCulture); + this.UserId = Convert.ToInt32(dr["UserID"], CultureInfo.InvariantCulture); + this.RelationshipId = Convert.ToInt32(dr["RelationshipID"], CultureInfo.InvariantCulture); + this.DefaultResponse = (RelationshipStatus)Convert.ToInt32(dr["DefaultResponse"], CultureInfo.InvariantCulture); // add audit column data this.FillInternal(dr); diff --git a/DNN Platform/Library/Entities/Users/UserController.cs b/DNN Platform/Library/Entities/Users/UserController.cs index 76bc438f67e..6832019edbe 100644 --- a/DNN Platform/Library/Entities/Users/UserController.cs +++ b/DNN Platform/Library/Entities/Users/UserController.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Entities.Users using System.Collections; using System.Collections.Generic; using System.Configuration; + using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Threading; @@ -67,20 +68,20 @@ public partial class UserController : ServiceLocatorGets or sets the site (portal) id.
public int PortalId { get; set; } - /// Gets the number count for all duplicate e-mail adresses in the database. + /// Gets the number count for all duplicate e-mail addresses in the database. /// An integer representing the amount of duplicate emails. public static int GetDuplicateEmailCount() { return DataProvider.Instance().GetDuplicateEmailCount(PortalSettings.Current.PortalId); } - /// add new userportal record (used for creating sites with existing user). - /// portalid. - /// userid. + /// add new user portal record (used for creating sites with existing user). + /// portal ID. + /// user ID. public static void AddUserPortal(int portalId, int userId) { - Requires.NotNullOrEmpty("portalId", portalId.ToString()); - Requires.NotNullOrEmpty("userId", userId.ToString()); + Requires.NotNullOrEmpty("portalId", portalId.ToString(CultureInfo.InvariantCulture)); + Requires.NotNullOrEmpty("userId", userId.ToString(CultureInfo.InvariantCulture)); MembershipProvider.Instance().AddUserPortal(portalId, userId); } @@ -408,7 +409,7 @@ public static UserCreateStatus CreateUser(ref UserInfo user, bool sendEmailNotif user.PasswordResetToken = passwordGuid; UpdateUser(user.PortalID, user); EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentSettings(), GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_CREATED); - CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalId)); + CachingProvider.Instance().Remove(string.Format(CultureInfo.InvariantCulture, DataCache.PortalUserCountCacheKey, portalId)); if (!user.IsSuperUser) { // autoassign user to portal roles @@ -698,7 +699,7 @@ public static UserInfo GetUserByPasswordResetToken(int portalId, string resetTok public static int GetUserCountByPortal(int portalId) { portalId = GetEffectivePortalId(portalId); - var cacheKey = string.Format(DataCache.PortalUserCountCacheKey, portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PortalUserCountCacheKey, portalId); return CBO.GetCachedObject(new CacheItemArgs(cacheKey, DataCache.PortalUserCountCacheTimeOut, DataCache.PortalUserCountCachePriority, portalId), GetUserCountByPortalCallBack); } @@ -717,8 +718,8 @@ public static string GetUserCreateStatus(UserCreateStatus userRegistrationStatus return Localization.GetString("InvalidEmail"); case UserCreateStatus.InvalidPassword: string strInvalidPassword = Localization.GetString("InvalidPassword"); - strInvalidPassword = strInvalidPassword.Replace("[PasswordLength]", MembershipProviderConfig.MinPasswordLength.ToString()); - strInvalidPassword = strInvalidPassword.Replace("[NoneAlphabet]", MembershipProviderConfig.MinNonAlphanumericCharacters.ToString()); + strInvalidPassword = strInvalidPassword.Replace("[PasswordLength]", MembershipProviderConfig.MinPasswordLength.ToString(CultureInfo.CurrentCulture)); + strInvalidPassword = strInvalidPassword.Replace("[NoneAlphabet]", MembershipProviderConfig.MinNonAlphanumericCharacters.ToString(CultureInfo.CurrentCulture)); return strInvalidPassword; case UserCreateStatus.PasswordMismatch: return Localization.GetString("PasswordMismatch"); @@ -797,7 +798,7 @@ public static Hashtable GetUserSettings(int portalId) { foreach (KeyValuePair kvp in settingsDictionary) { - int index = kvp.Key.IndexOf("_"); + int index = kvp.Key.IndexOf("_", StringComparison.Ordinal); if (index > 0) { // Get the prefix @@ -814,13 +815,13 @@ public static Hashtable GetUserSettings(int portalId) switch (kvp.Key) { case "Display_Mode": - settings[kvp.Key] = (DisplayMode)Convert.ToInt32(kvp.Value); + settings[kvp.Key] = (DisplayMode)Convert.ToInt32(kvp.Value, CultureInfo.InvariantCulture); break; case "Profile_DefaultVisibility": - settings[kvp.Key] = (UserVisibilityMode)Convert.ToInt32(kvp.Value); + settings[kvp.Key] = (UserVisibilityMode)Convert.ToInt32(kvp.Value, CultureInfo.InvariantCulture); break; case "Security_UsersControl": - settings[kvp.Key] = (UsersControl)Convert.ToInt32(kvp.Value); + settings[kvp.Key] = (UsersControl)Convert.ToInt32(kvp.Value, CultureInfo.InvariantCulture); break; default: // update value or add any new values @@ -836,7 +837,7 @@ public static Hashtable GetUserSettings(int portalId) if (currentPortalSettings != null) { - foreach (var kvp in currentPortalSettings.Where(kvp => kvp.Key.StartsWith("Redirect_"))) + foreach (var kvp in currentPortalSettings.Where(kvp => kvp.Key.StartsWith("Redirect_", StringComparison.OrdinalIgnoreCase))) { settings[kvp.Key] = kvp.Value; } @@ -1459,7 +1460,7 @@ public static UserValidStatus ValidateUser(UserInfo objUser, int portalId, bool // Check if Profile needs updating if (validStatus == UserValidStatus.VALID) { - var validProfile = Convert.ToBoolean(UserModuleBase.GetSetting(portalId, "Security_RequireValidProfileAtLogin")); + var validProfile = Convert.ToBoolean(UserModuleBase.GetSetting(portalId, "Security_RequireValidProfileAtLogin"), CultureInfo.InvariantCulture); if (validProfile && (!ProfileController.ValidateProfile(portalId, objUser.Profile))) { validStatus = UserValidStatus.UPDATEPROFILE; @@ -1609,7 +1610,7 @@ public string GetUserProfilePictureUrl(int userId, int width, int height) var childPortalAlias = GetChildPortalAlias(); var cdv = GetProfilePictureCdv(userId); - return childPortalAlias.StartsWith(Globals.ApplicationPath) + return childPortalAlias.StartsWith(Globals.ApplicationPath, StringComparison.OrdinalIgnoreCase) ? childPortalAlias + url + cdv : Globals.ApplicationPath + childPortalAlias + url + cdv; } @@ -1640,7 +1641,7 @@ public string GetUserProfilePictureUrl(int portalId, int userId, int width, int var childPortalAlias = Globals.ResolveUrl(this.GetUserProfilePictureUrl(userId, width, height)); var cdv = GetProfilePictureCdv(portalId, userId); - return childPortalAlias.StartsWith(Globals.ApplicationPath) + return childPortalAlias.StartsWith(Globals.ApplicationPath, StringComparison.OrdinalIgnoreCase) ? childPortalAlias + url + cdv : Globals.ApplicationPath + childPortalAlias + url + cdv; } @@ -1729,7 +1730,7 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) } else { - settings["Display_Mode"] = (DisplayMode)Convert.ToInt32(settings["Display_Mode"]); + settings["Display_Mode"] = (DisplayMode)Convert.ToInt32(settings["Display_Mode"], CultureInfo.InvariantCulture); } if (settings["Display_SuppressPager"] == null) @@ -1748,7 +1749,7 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) } else { - settings["Profile_DefaultVisibility"] = (UserVisibilityMode)Convert.ToInt32(settings["Profile_DefaultVisibility"]); + settings["Profile_DefaultVisibility"] = (UserVisibilityMode)Convert.ToInt32(settings["Profile_DefaultVisibility"], CultureInfo.InvariantCulture); } if (settings["Profile_DisplayVisibility"] == null) @@ -1833,7 +1834,7 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) } else { - settings["Security_UsersControl"] = (UsersControl)Convert.ToInt32(settings["Security_UsersControl"]); + settings["Security_UsersControl"] = (UsersControl)Convert.ToInt32(settings["Security_UsersControl"], CultureInfo.InvariantCulture); } // Display name format @@ -1891,14 +1892,12 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) } /// updates a user. - /// the portalid of the user. + /// the portal ID of the user. /// the user object. - /// whether or not the update calls the eventlog - the eventlogtype must still be enabled for logging to occur. + /// whether the update calls the event log - the event log type must still be enabled for logging to occur. /// Whether to send notification to the user about the update (i.e. a notification if the user was approved). /// Whether clear cache after update user. - /// - /// This method is used internal because it should be use carefully, or it will caught cache doesn't clear correctly. - /// + /// This method is used internal because it should be used carefully, or it will caught cache doesn't clear correctly. internal static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bool sendNotification, bool clearCache) { var originalPortalId = user.PortalID; @@ -1906,7 +1905,7 @@ internal static void UpdateUser(int portalId, UserInfo user, bool loggedAction, user.PortalID = portalId; // clear the cache so that can get original info from database. - DataCache.RemoveCache(string.Format(DataCache.UserProfileCacheKey, portalId, user.Username)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.UserProfileCacheKey, portalId, user.Username)); var oldUser = MembershipProvider.Instance().GetUser(user.PortalID, user.UserID); var oldProfile = oldUser.Profile; // access the profile property to reload data from database. @@ -1914,7 +1913,7 @@ internal static void UpdateUser(int portalId, UserInfo user, bool loggedAction, MembershipProvider.Instance().UpdateUser(user); if (loggedAction) { - // if the httpcontext is null, then get portal settings by portal id. + // if the HttpContext is null, then get portal settings by portal id. IPortalSettings portalSettings = null; if (HttpContext.Current != null) { @@ -2055,7 +2054,7 @@ private static void RestoreUserPermissions(UserInfo user) { FolderID = userFolder.FolderID, UserID = user.UserID, - RoleID = int.Parse(Globals.glbRoleNothing), + RoleID = int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture), AllowAccess = true, }; @@ -2115,7 +2114,7 @@ private static object GetUserCountByPortalCallBack(CacheItemArgs cacheItemArgs) private static SharedDictionary GetUserLookupDictionary(int portalId) { var masterPortalId = GetEffectivePortalId(portalId); - var cacheKey = string.Format(DataCache.UserLookupCacheKey, masterPortalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.UserLookupCacheKey, masterPortalId); return CBO.GetCachedObject>( new CacheItemArgs( cacheKey, diff --git a/DNN Platform/Library/Entities/Users/UserInfo.cs b/DNN Platform/Library/Entities/Users/UserInfo.cs index 39273b66cce..4887d5c4f6a 100644 --- a/DNN Platform/Library/Entities/Users/UserInfo.cs +++ b/DNN Platform/Library/Entities/Users/UserInfo.cs @@ -10,6 +10,7 @@ namespace DotNetNuke.Entities.Users using System; using System.Collections.Concurrent; using System.ComponentModel; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; @@ -250,16 +251,17 @@ public string[] Roles /// requested maximum access level, might be restricted due to user level. /// out: flag, if property could be retrieved. /// current value of the property for this userinfo object. + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { Scope internScope; if (this.UserID == -1 && currentScope > Scope.Configuration) { - internScope = Scope.Configuration; // anonymous users only get access to displayname + internScope = Scope.Configuration; // anonymous users only get access to display name } else if (this.UserID != accessingUser.UserID && !this.IsAdminUser(ref accessingUser) && currentScope > Scope.DefaultSettings) { - internScope = Scope.DefaultSettings; // registerd users can access username and userID as well + internScope = Scope.DefaultSettings; // registered users can access username and userID as well } else { diff --git a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs index 5c4f3713cbc..ff3debc8cf0 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Users { using System; using System.Collections; + using System.Globalization; using System.Web; using DotNetNuke.Common; @@ -250,12 +251,12 @@ private void TrackAuthenticatedUser(HttpContext context) user.PortalID = portalSettings.PortalId; user.TabID = portalSettings.ActiveTab.TabID; user.LastActiveDate = DateTime.Now; - if (userList[objUserInfo.UserID.ToString()] == null) + if (userList[objUserInfo.UserID.ToString(CultureInfo.InvariantCulture)] == null) { user.CreationDate = user.LastActiveDate; } - userList[objUserInfo.UserID.ToString()] = user; + userList[objUserInfo.UserID.ToString(CultureInfo.InvariantCulture)] = user; this.SetUserList(userList); } } diff --git a/DNN Platform/Library/ExtensionPoints/ContextMenuItemExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/ContextMenuItemExtensionControl.cs index 1f9765ebf1e..8e473233d53 100644 --- a/DNN Platform/Library/ExtensionPoints/ContextMenuItemExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/ContextMenuItemExtensionControl.cs @@ -2,52 +2,57 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ExtensionPoints -{ - using System; - using System.ComponentModel; - using System.Text; - using System.Web.UI; - - using DotNetNuke.Common; - - [DefaultProperty("Text")] - [ToolboxData("<{0}:ContextMenuItemExtensionControl runat=server>")] - public class ContextMenuItemExtensionControl : DefaultExtensionControl - { +namespace DotNetNuke.ExtensionPoints +{ + using System; + using System.ComponentModel; + using System.Diagnostics.CodeAnalysis; + using System.Text; + using System.Web.UI; + + using DotNetNuke.Common; + + [DefaultProperty("Text")] + [ToolboxData("<{0}:ContextMenuItemExtensionControl runat=server>")] + public class ContextMenuItemExtensionControl : DefaultExtensionControl + { private string content = string.Empty; /// - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - var extensionPointManager = new ExtensionPointManager(); - - StringBuilder str = new StringBuilder(); - - foreach (var extension in extensionPointManager.GetContextMenuItemExtensionPoints(this.Module, this.Group)) - { - var icon = extension.Icon; - if (icon.StartsWith("~/")) - { - icon = Globals.ResolveUrl(icon); - } - - str.Append(@"
  • - - - " + extension.Text + @" - -
  • "); - } - - this.content = str.ToString(); + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + var extensionPointManager = new ExtensionPointManager(); + + StringBuilder str = new StringBuilder(); + + foreach (var extension in extensionPointManager.GetContextMenuItemExtensionPoints(this.Module, this.Group)) + { + var icon = extension.Icon; + if (icon.StartsWith("~/", StringComparison.Ordinal)) + { + icon = Globals.ResolveUrl(icon); + } + + str.Append( + $""" +
  • + + {extension.AltText} + {extension.Text} + +
  • + """); + } + + this.content = str.ToString(); } /// - protected override void RenderContents(HtmlTextWriter output) - { - output.Write(this.content); - } - } -} + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] + protected override void RenderContents(HtmlTextWriter output) + { + output.Write(this.content); + } + } +} diff --git a/DNN Platform/Library/ExtensionPoints/IExtensionPointData.cs b/DNN Platform/Library/ExtensionPoints/IExtensionPointData.cs index 6344f65b72f..f797351fba5 100644 --- a/DNN Platform/Library/ExtensionPoints/IExtensionPointData.cs +++ b/DNN Platform/Library/ExtensionPoints/IExtensionPointData.cs @@ -2,24 +2,26 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ExtensionPoints -{ - using System.ComponentModel; +namespace DotNetNuke.ExtensionPoints +{ + using System.ComponentModel; + using System.Diagnostics.CodeAnalysis; - public interface IExtensionPointData - { - string Module { get; } - - string Name { get; } - - string Group { get; } - - int Priority { get; } - - [DefaultValue(false)] - bool DisableOnHost { get; } - - [DefaultValue(false)] - bool DisableUnauthenticated { get; } - } -} + public interface IExtensionPointData + { + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + string Module { get; } + + string Name { get; } + + string Group { get; } + + int Priority { get; } + + [DefaultValue(false)] + bool DisableOnHost { get; } + + [DefaultValue(false)] + bool DisableUnauthenticated { get; } + } +} diff --git a/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs index b13b7eadc5d..8ba23ac2b09 100644 --- a/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs @@ -2,26 +2,28 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ExtensionPoints -{ - using System.Web.UI.WebControls; - - public interface IGridColumnExtensionPoint : IExtensionPoint - { - int ColumnAt { get; } - - string UniqueName { get; } - - string DataField { get; } - - string HeaderText { get; } - - Unit HeaderStyleWidth { get; } - - bool ReadOnly { get; } - - bool Reorderable { get; } - - string SortExpression { get; } - } -} +namespace DotNetNuke.ExtensionPoints +{ + using System.Diagnostics.CodeAnalysis; + using System.Web.UI.WebControls; + + public interface IGridColumnExtensionPoint : IExtensionPoint + { + int ColumnAt { get; } + + string UniqueName { get; } + + string DataField { get; } + + string HeaderText { get; } + + Unit HeaderStyleWidth { get; } + + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] + bool ReadOnly { get; } + + bool Reorderable { get; } + + string SortExpression { get; } + } +} diff --git a/DNN Platform/Library/ExtensionPoints/PanelEditPagePanelExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/PanelEditPagePanelExtensionControl.cs index deb2a7481a6..8076c254219 100644 --- a/DNN Platform/Library/ExtensionPoints/PanelEditPagePanelExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/PanelEditPagePanelExtensionControl.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.ExtensionPoints { + using System.Diagnostics.CodeAnalysis; using System.Web.UI; using System.Web.UI.WebControls; @@ -13,13 +14,17 @@ public class PanelEditPagePanelExtensionControl : WebControl public string Text { get; set; } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override void RenderContents(HtmlTextWriter op) { - op.Write(@"
    -

    -" + this.Text + @" -

    -
    "); + op.Write( + $""" +
    +

    + {this.Text} +

    +
    + """); base.RenderContents(op); op.Write("
    "); } diff --git a/DNN Platform/Library/ExtensionPoints/PanelTabExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/PanelTabExtensionControl.cs index 4d909137cd5..1bbdaffda2b 100644 --- a/DNN Platform/Library/ExtensionPoints/PanelTabExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/PanelTabExtensionControl.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.ExtensionPoints { + using System.Diagnostics.CodeAnalysis; using System.Web.UI; using System.Web.UI.WebControls; @@ -23,9 +24,10 @@ public override void RenderEndTag(HtmlTextWriter writer) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override void RenderContents(HtmlTextWriter op) { - op.Write("
    "); + op.Write($"
    "); base.RenderContents(op); op.Write("
    "); } diff --git a/DNN Platform/Library/ExtensionPoints/ToolBarButtonExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/ToolBarButtonExtensionControl.cs index e9f0d86c980..eb8f8c1f68b 100644 --- a/DNN Platform/Library/ExtensionPoints/ToolBarButtonExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/ToolBarButtonExtensionControl.cs @@ -2,58 +2,61 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.ExtensionPoints -{ - using System.ComponentModel; - using System.Text; - using System.Web; - using System.Web.UI; - - using DotNetNuke.ExtensionPoints.Filters; - - [DefaultProperty("Text")] - [ToolboxData("<{0}:ToolBarButtonExtensionControl runat=server>")] - public class ToolBarButtonExtensionControl : DefaultExtensionControl - { - private IExtensionControlRenderer btnRenderer; - - [Bindable(true)] - [DefaultValue(false)] +namespace DotNetNuke.ExtensionPoints +{ + using System.ComponentModel; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; + using System.Text; + using System.Web; + using System.Web.UI; + + using DotNetNuke.ExtensionPoints.Filters; + + [DefaultProperty("Text")] + [ToolboxData("<{0}:ToolBarButtonExtensionControl runat=server>")] + public class ToolBarButtonExtensionControl : DefaultExtensionControl + { + private IExtensionControlRenderer btnRenderer; + + [Bindable(true)] + [DefaultValue(false)] public bool IsHost { get; set; } /// - protected override void RenderContents(HtmlTextWriter output) - { - var extensionPointManager = new ExtensionPointManager(); - - var str = new StringBuilder(); - - var filter = new CompositeFilter() - .And(new FilterByHostMenu(this.IsHost)) - .And(new FilterByUnauthenticated(HttpContext.Current.Request.IsAuthenticated)); - - foreach (var extension in extensionPointManager.GetToolBarButtonExtensionPoints(this.Module, this.Group, filter)) - { - if (extension is IToolBarMenuButtonExtensionPoint) - { - this.btnRenderer = new ToolBarMenuButtonRenderer(); - str.AppendFormat(this.btnRenderer.GetOutput(extension)); - } - else - { - extension.ModuleContext = this.ModuleContext; - this.btnRenderer = new ToolBarButtonRenderer(); - str.AppendFormat(this.btnRenderer.GetOutput(extension)); - } - } - - output.Write(str.ToString()); + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] + protected override void RenderContents(HtmlTextWriter output) + { + var extensionPointManager = new ExtensionPointManager(); + + var str = new StringBuilder(); + + var filter = new CompositeFilter() + .And(new FilterByHostMenu(this.IsHost)) + .And(new FilterByUnauthenticated(HttpContext.Current.Request.IsAuthenticated)); + + foreach (var extension in extensionPointManager.GetToolBarButtonExtensionPoints(this.Module, this.Group, filter)) + { + if (extension is IToolBarMenuButtonExtensionPoint) + { + this.btnRenderer = new ToolBarMenuButtonRenderer(); + } + else + { + extension.ModuleContext = this.ModuleContext; + this.btnRenderer = new ToolBarButtonRenderer(); + } + + str.AppendFormat(CultureInfo.InvariantCulture, this.btnRenderer.GetOutput(extension)); + } + + output.Write(str.ToString()); } /// - protected override void Render(HtmlTextWriter writer) - { - this.RenderContents(writer); - } - } -} + protected override void Render(HtmlTextWriter writer) + { + this.RenderContents(writer); + } + } +} diff --git a/DNN Platform/Library/ExtensionPoints/ToolBarButtonRenderer.cs b/DNN Platform/Library/ExtensionPoints/ToolBarButtonRenderer.cs index 61e0581dcaf..c6749403a16 100644 --- a/DNN Platform/Library/ExtensionPoints/ToolBarButtonRenderer.cs +++ b/DNN Platform/Library/ExtensionPoints/ToolBarButtonRenderer.cs @@ -4,6 +4,9 @@ namespace DotNetNuke.ExtensionPoints { + using System; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Text; using System.Web; @@ -12,6 +15,7 @@ namespace DotNetNuke.ExtensionPoints public class ToolBarButtonRenderer : IExtensionControlRenderer { /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string GetOutput(IExtensionPoint extensionPoint) { var extension = (IToolBarButtonExtensionPoint)extensionPoint; @@ -25,13 +29,14 @@ public string GetOutput(IExtensionPoint extensionPoint) } var icon = extension.Icon; - if (icon.StartsWith("~/")) + if (icon.StartsWith("~/", StringComparison.Ordinal)) { icon = Globals.ResolveUrl(icon); } var str = new StringBuilder(); str.AppendFormat( + CultureInfo.InvariantCulture, ""); - str.AppendFormat("
    ", extension.MenuCssClass); + str.AppendFormat(CultureInfo.InvariantCulture, "
    ", extension.MenuCssClass); str.AppendLine("
    "); str.AppendLine("
      "); foreach (var item in extension.Items) diff --git a/DNN Platform/Library/Framework/BaseHttpHandler.cs b/DNN Platform/Library/Framework/BaseHttpHandler.cs index 74bd8698a1d..fca1bc1934d 100644 --- a/DNN Platform/Library/Framework/BaseHttpHandler.cs +++ b/DNN Platform/Library/Framework/BaseHttpHandler.cs @@ -190,7 +190,7 @@ public void ProcessRequest(HttpContext context) /// /// Sets the cache policy. Unless a handler overrides - /// this method, handlers will not allow a respons to be + /// this method, handlers will not allow a response to be /// cached. /// /// Cache. @@ -207,7 +207,7 @@ public virtual void SetResponseCachePolicy(HttpCachePolicy cache) ///
    protected void RespondFileNotFound() { - this.Response.StatusCode = Convert.ToInt32(HttpStatusCode.NotFound); + this.Response.StatusCode = (int)HttpStatusCode.NotFound; this.Response.End(); } @@ -219,7 +219,7 @@ protected void RespondInternalError() { // It's really too bad that StatusCode property // is not of type HttpStatusCode. - this.Response.StatusCode = Convert.ToInt32(HttpStatusCode.InternalServerError); + this.Response.StatusCode = (int)HttpStatusCode.InternalServerError; this.Response.End(); } @@ -230,7 +230,7 @@ protected void RespondInternalError() /// protected void RespondForbidden() { - this.Response.StatusCode = Convert.ToInt32(HttpStatusCode.Forbidden); + this.Response.StatusCode = (int)HttpStatusCode.Forbidden; this.Response.End(); } } diff --git a/DNN Platform/Library/Framework/CDefault.cs b/DNN Platform/Library/Framework/CDefault.cs index 34e429c8337..860f72ce0ed 100644 --- a/DNN Platform/Library/Framework/CDefault.cs +++ b/DNN Platform/Library/Framework/CDefault.cs @@ -20,18 +20,25 @@ namespace DotNetNuke.Framework public class CDefault : PageBase { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string Author = string.Empty; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string Comment = string.Empty; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string Copyright = string.Empty; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string Description = string.Empty; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string Generator = string.Empty; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string KeyWords = string.Empty; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public new string Title = string.Empty; private static readonly object InstallerFilesRemovedLock = new object(); diff --git a/DNN Platform/Library/Framework/CachePageStatePersister.cs b/DNN Platform/Library/Framework/CachePageStatePersister.cs index 6980e75db3b..e1734043ded 100644 --- a/DNN Platform/Library/Framework/CachePageStatePersister.cs +++ b/DNN Platform/Library/Framework/CachePageStatePersister.cs @@ -30,7 +30,7 @@ public override void Load() string key = this.Page.Request.Params[ViewStateCacheKey]; // Abort if cache key is not available or valid - if (string.IsNullOrEmpty(key) || !key.StartsWith("VS_")) + if (string.IsNullOrEmpty(key) || !key.StartsWith("VS_", StringComparison.OrdinalIgnoreCase)) { throw new InvalidViewStateCacheKeyException("Missing valid " + ViewStateCacheKey); } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs index 42036587e95..2f00957ff2e 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs @@ -121,7 +121,7 @@ public static string Version(IApplicationStatusInfo appStatus, string jsname) appStatus ??= Globals.GetCurrentServiceProvider().GetRequiredService(); var library = GetHighestVersionLibrary(appStatus, jsname); - return library != null ? Convert.ToString(library.Version) : string.Empty; + return library != null ? Convert.ToString(library.Version, CultureInfo.InvariantCulture) : string.Empty; } /// Requests a script to be added to the page. @@ -541,7 +541,7 @@ private static string GetScriptPath(IHostSettings hostSettings, IHostSettingsSer if (!string.IsNullOrEmpty(js.CDNPath)) { var cdnPath = js.CDNPath; - if (cdnPath.StartsWith("//")) + if (cdnPath.StartsWith("//", StringComparison.Ordinal)) { var useSecurePath = request == null || UrlUtils.IsSecureConnectionOrSslOffload(request); cdnPath = $"{(useSecurePath ? "https" : "http")}:{cdnPath}"; @@ -572,15 +572,17 @@ private static string GetScriptLocation(JavaScriptLibrary js) private static List GetScriptVersions(IApplicationStatusInfo appStatus) { - var orderedScripts = (from object item in HttpContextSource.Current.Items.Keys - where item.ToString().StartsWith(ScriptPrefix) - select item.ToString().Substring(4)).ToList(); + var orderedScripts = ( + from object item in HttpContextSource.Current.Items.Keys + where item.ToString().StartsWith(ScriptPrefix, StringComparison.Ordinal) + select item.ToString().Substring(4)) + .ToList(); orderedScripts.Sort(); var finalScripts = orderedScripts.ToList(); foreach (var libraryId in orderedScripts) { // find dependencies - var library = JavaScriptLibraryController.Instance.GetLibrary(l => l.JavaScriptLibraryID.ToString() == libraryId); + var library = JavaScriptLibraryController.Instance.GetLibrary(l => l.JavaScriptLibraryID.ToString(CultureInfo.InvariantCulture) == libraryId); if (library == null) { continue; @@ -590,7 +592,7 @@ where item.ToString().StartsWith(ScriptPrefix) { if (HttpContextSource.Current.Items[ScriptPrefix + "." + dependencyLibrary.JavaScriptLibraryID] == null) { - finalScripts.Add(dependencyLibrary.JavaScriptLibraryID.ToString()); + finalScripts.Add(dependencyLibrary.JavaScriptLibraryID.ToString(CultureInfo.InvariantCulture)); } } } diff --git a/DNN Platform/Library/Framework/Reflections/TypeLocator.cs b/DNN Platform/Library/Framework/Reflections/TypeLocator.cs index efa907fb8be..09540b24946 100644 --- a/DNN Platform/Library/Framework/Reflections/TypeLocator.cs +++ b/DNN Platform/Library/Framework/Reflections/TypeLocator.cs @@ -14,6 +14,37 @@ namespace DotNetNuke.Framework.Reflections public class TypeLocator : ITypeLocator, IAssemblyLocator { + private static readonly HashSet IgnoreAssemblies = new(StringComparer.OrdinalIgnoreCase) + { + "DotNetNuke.Authentication.Facebook", + "DotNetNuke.Authentication.Google", + "DotNetNuke.Authentication.LiveConnect", + "DotNetNuke.Authentication.Twitter", + "DotNetNuke.ASP2MenuNavigationProvider", + "DotNetNuke.DNNDropDownNavigationProvider", + "DotNetNuke.DNNMenuNavigationProvider", + "DotNetNuke.DNNTreeNavigationProvider", + "DotNetNuke.HttpModules", + "DotNetNuke.Instrumentation", + "DotNetNuke.Log4Net", + "DotNetNuke.Modules.Groups", + "DotNetNuke.Modules.Html", + "DotNetNuke.Modules.HtmlEditorManager", + "DotNetNuke.Modules.MobileManagement", + "DotNetNuke.Modules.PreviewProfileManagement", + "DotNetNuke.Modules.RazorHost", + "DotNetNuke.Modules.Taxonomy", + "DotNetNuke.Modules.UrlManagement", + "DotNetNuke.RadEditorProvider", + "DotNetNuke.Services.Syndication", + "DotNetNuke.Web.Client", + "DotNetNuke.Web.DDRMenu", + "DotNetNuke.Web.Razor", + "DotNetNuke.Web.Mvc", + "DotNetNuke.WebControls", + "DotNetNuke.WebUtility", + }; + private IAssemblyLocator assemblyLocator; /// @@ -67,51 +98,26 @@ public IEnumerable GetAllMatchingTypes(Predicate predicate) private static bool CanScan(Assembly assembly) { - string[] ignoreAssemblies = - [ - "DotNetNuke.Authentication.Facebook", - "DotNetNuke.Authentication.Google", - "DotNetNuke.Authentication.LiveConnect", - "DotNetNuke.Authentication.Twitter", - "DotNetNuke.ASP2MenuNavigationProvider", - "DotNetNuke.DNNDropDownNavigationProvider", - "DotNetNuke.DNNMenuNavigationProvider", - "DotNetNuke.DNNTreeNavigationProvider", - "DotNetNuke.HttpModules", - "DotNetNuke.Instrumentation", - "DotNetNuke.Log4Net", - "DotNetNuke.Modules.Groups", - "DotNetNuke.Modules.Html", - "DotNetNuke.Modules.HtmlEditorManager", - "DotNetNuke.Modules.MobileManagement", - "DotNetNuke.Modules.PreviewProfileManagement", - "DotNetNuke.Modules.RazorHost", - "DotNetNuke.Modules.Taxonomy", - "DotNetNuke.Modules.UrlManagement", - "DotNetNuke.RadEditorProvider", - "DotNetNuke.Services.Syndication", - "DotNetNuke.Web.Client", - "DotNetNuke.Web.DDRMenu", - "DotNetNuke.Web.Razor", - "DotNetNuke.Web.Mvc", - "DotNetNuke.WebControls", - "DotNetNuke.WebUtility" - ]; - // First eliminate by "class" - var assemblyName = assembly.FullName.ToLowerInvariant(); - bool canScan = !(assemblyName.StartsWith("clientdependency.core") || assemblyName.StartsWith("countrylistbox") - || assemblyName.StartsWith("icsharpcode") || assemblyName.StartsWith("fiftyone") - || assemblyName.StartsWith("lucene") || assemblyName.StartsWith("microsoft") - || assemblyName.StartsWith("newtonsoft") || assemblyName.StartsWith("petapoco") - || assemblyName.StartsWith("sharpziplib") || assemblyName.StartsWith("system") - || assemblyName.StartsWith("telerik") || assemblyName.StartsWith("webformsmvp") - || assemblyName.StartsWith("webmatrix")); + var assemblyName = assembly.FullName; + bool canScan = !(assemblyName.StartsWith("clientdependency.core", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("countrylistbox", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("icsharpcode", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("fiftyone", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("lucene", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("microsoft", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("newtonsoft", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("petapoco", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("sharpziplib", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("system", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("telerik", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("webformsmvp", StringComparison.OrdinalIgnoreCase) + || assemblyName.StartsWith("webmatrix", StringComparison.OrdinalIgnoreCase)); if (canScan) { // Next eliminate specific assemblies - if (ignoreAssemblies.Any(ignoreAssembly => assemblyName.Equals(ignoreAssembly, StringComparison.OrdinalIgnoreCase))) + if (IgnoreAssemblies.Contains(assemblyName)) { canScan = false; } diff --git a/DNN Platform/Library/Framework/ServiceLocator.cs b/DNN Platform/Library/Framework/ServiceLocator.cs index 77f8616d8c0..382efecbea8 100644 --- a/DNN Platform/Library/Framework/ServiceLocator.cs +++ b/DNN Platform/Library/Framework/ServiceLocator.cs @@ -2,68 +2,72 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Framework -{ - using System; +namespace DotNetNuke.Framework +{ + using System; + using System.Diagnostics.CodeAnalysis; - /// Provides a readily testable way to manage a Singleton. - /// The interface that the controller provides. - /// The type of the controller itself, used to call the GetFactory override. + /// Provides a readily testable way to manage a Singleton. + /// The interface that the controller provides. + /// The type of the controller itself, used to call the GetFactory override. public abstract class ServiceLocator where TSelf : ServiceLocator, new() { private static Lazy instance = new Lazy(InitInstance, true); - private static TContract testableInstance; + private static TContract testableInstance; private static bool useTestable; - /// Gets a singleton of T. - public static TContract Instance - { - get - { - if (useTestable) - { - return testableInstance; - } - - return instance.Value; - } + /// Gets a singleton of T. + [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "Breaking change")] + public static TContract Instance + { + get + { + if (useTestable) + { + return testableInstance; + } + + return instance.Value; + } + } + + /// Gets or sets the service locator factory. + protected static Func Factory { get; set; } + + /// Registers an instance to use for the Singleton. + /// Intended for unit testing purposes, not thread safe. + /// The instance to set. + [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "Breaking change")] + public static void SetTestableInstance(TContract instance) + { + testableInstance = instance; + useTestable = true; } - /// Gets or sets the service locator factory. - protected static Func Factory { get; set; } - - /// Registers an instance to use for the Singleton. - /// Intended for unit testing purposes, not thread safe. - /// The instance to set. - public static void SetTestableInstance(TContract instance) - { - testableInstance = instance; - useTestable = true; - } - - /// Clears the current instance, a new instance will be initialized when next requested. - /// Intended for unit testing purposes, not thread safe. - public static void ClearInstance() - { - useTestable = false; - testableInstance = default(TContract); - instance = new Lazy(InitInstance, true); - } + /// Clears the current instance, a new instance will be initialized when next requested. + /// Intended for unit testing purposes, not thread safe. + [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "Breaking change")] + public static void ClearInstance() + { + useTestable = false; + testableInstance = default(TContract); + instance = new Lazy(InitInstance, true); + } /// Gets the service locator factory. - /// A factory function. + /// A factory function. protected abstract Func GetFactory(); - - private static TContract InitInstance() - { - if (Factory == null) - { - var controllerInstance = new TSelf(); - Factory = controllerInstance.GetFactory(); - } - - return Factory(); - } - } -} + + private static TContract InitInstance() + { + if (Factory == null) + { + var controllerInstance = new TSelf(); + Factory = controllerInstance.GetFactory(); + } + + return Factory(); + } + } +} diff --git a/DNN Platform/Library/Framework/ServicesFramework.cs b/DNN Platform/Library/Framework/ServicesFramework.cs index 98848e0c532..5c1547cfbdd 100644 --- a/DNN Platform/Library/Framework/ServicesFramework.cs +++ b/DNN Platform/Library/Framework/ServicesFramework.cs @@ -2,45 +2,45 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Framework -{ - using System; +namespace DotNetNuke.Framework +{ + using System; - using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Portals; - /// Enables modules to support Services Framework features. - public class ServicesFramework : ServiceLocator - { - public static string GetServiceFrameworkRoot() - { - var portalSettings = PortalSettings.Current; - if (portalSettings == null) - { - return string.Empty; - } - - var path = portalSettings.PortalAlias.HTTPAlias; - var index = path.IndexOf('/'); - if (index > 0) - { - path = path.Substring(index); - if (!path.EndsWith("/")) - { - path += "/"; - } - } - else - { - path = "/"; - } - - return path; + /// Enables modules to support Services Framework features. + public class ServicesFramework : ServiceLocator + { + public static string GetServiceFrameworkRoot() + { + var portalSettings = PortalSettings.Current; + if (portalSettings == null) + { + return string.Empty; + } + + var path = portalSettings.PortalAlias.HTTPAlias; + var index = path.IndexOf('/'); + if (index > 0) + { + path = path.Substring(index); + if (!path.EndsWith("/", StringComparison.Ordinal)) + { + path += "/"; + } + } + else + { + path = "/"; + } + + return path; } /// - protected override Func GetFactory() - { - return () => new ServicesFrameworkImpl(); - } - } -} + protected override Func GetFactory() + { + return () => new ServicesFrameworkImpl(); + } + } +} diff --git a/DNN Platform/Library/Framework/jQuery.cs b/DNN Platform/Library/Framework/jQuery.cs index e047202b6c7..9348bb656f2 100644 --- a/DNN Platform/Library/Framework/jQuery.cs +++ b/DNN Platform/Library/Framework/jQuery.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Framework { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Text.RegularExpressions; using System.Web; @@ -99,7 +100,7 @@ public static void KeepAlive(Page page) JavaScript.RequestRegistration(CommonJs.jQuery); var seconds = ((cookieTimeout * 60) - 30) * 1000; // ping server 30 seconds before cookie is time out. - var scriptBlock = string.Format("(function($){{setInterval(function(){{$.get(location.href)}}, {1});}}(jQuery));", Globals.ApplicationPath, seconds); + var scriptBlock = string.Format(CultureInfo.InvariantCulture, "(function($){{setInterval(function(){{$.get(location.href)}}, {1});}}(jQuery));", Globals.ApplicationPath, seconds); ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "PageKeepAlive", scriptBlock, true); } @@ -111,7 +112,7 @@ private static bool GetSettingAsBoolean(string key, bool defaultValue) object setting = HttpContext.Current.Items[key]; if (setting != null) { - retValue = Convert.ToBoolean(setting); + retValue = Convert.ToBoolean(setting, CultureInfo.InvariantCulture); } } catch (Exception ex) diff --git a/DNN Platform/Library/Modules/NavigationEventArgs.cs b/DNN Platform/Library/Modules/NavigationEventArgs.cs index f82049f2fbf..a8bfa2e6aa0 100644 --- a/DNN Platform/Library/Modules/NavigationEventArgs.cs +++ b/DNN Platform/Library/Modules/NavigationEventArgs.cs @@ -7,12 +7,15 @@ namespace DotNetNuke.Modules.NavigationProvider using DotNetNuke.UI.WebControls; + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public class NavigationEventArgs { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string ID; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public DNNNode Node; /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/Modules/NavigationProvider.cs b/DNN Platform/Library/Modules/NavigationProvider.cs index 84c679628a8..7fc486a3011 100644 --- a/DNN Platform/Library/Modules/NavigationProvider.cs +++ b/DNN Platform/Library/Modules/NavigationProvider.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Modules.NavigationProvider { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Web.UI; using DotNetNuke.Common; @@ -14,6 +15,7 @@ namespace DotNetNuke.Modules.NavigationProvider using DotNetNuke.UI.WebControls; /// Provides a renderer for navigation. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public abstract partial class NavigationProvider : UserControlBase { public delegate void NodeClickEventHandler(NavigationEventArgs args); @@ -1021,6 +1023,7 @@ public virtual void ClearNodes() { } + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] protected void RaiseEvent_NodeClick(DNNNode objNode) { if (this.NodeClick != null) @@ -1029,6 +1032,7 @@ protected void RaiseEvent_NodeClick(DNNNode objNode) } } + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] protected void RaiseEvent_NodeClick(string strID) { if (this.NodeClick != null) @@ -1037,6 +1041,7 @@ protected void RaiseEvent_NodeClick(string strID) } } + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] protected void RaiseEvent_PopulateOnDemand(DNNNode objNode) { if (this.PopulateOnDemand != null) @@ -1045,6 +1050,7 @@ protected void RaiseEvent_PopulateOnDemand(DNNNode objNode) } } + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] protected void RaiseEvent_PopulateOnDemand(string strID) { if (this.PopulateOnDemand != null) diff --git a/DNN Platform/Library/Obsolete/EventLogController.cs b/DNN Platform/Library/Obsolete/EventLogController.cs index 8e83318e480..30e04a3f9b1 100644 --- a/DNN Platform/Library/Obsolete/EventLogController.cs +++ b/DNN Platform/Library/Obsolete/EventLogController.cs @@ -26,6 +26,7 @@ public partial class EventLogController : ServiceLocator USER_CREATED = 0, @@ -496,6 +497,7 @@ public enum EventLogType /// PORTALPERMISSION_UPDATED = 156, +#pragma warning restore CA1707 } [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] diff --git a/DNN Platform/Library/Prompt/ConsoleCommand.cs b/DNN Platform/Library/Prompt/ConsoleCommand.cs index 43bb3661629..41ae944ac9a 100644 --- a/DNN Platform/Library/Prompt/ConsoleCommand.cs +++ b/DNN Platform/Library/Prompt/ConsoleCommand.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Prompt { + using System; using System.Collections.Generic; using System.Reflection; @@ -124,7 +125,7 @@ private static string NormalizeFlagName(string flagName) return string.Empty; } - if (flagName.StartsWith("--")) + if (flagName.StartsWith("--", StringComparison.Ordinal)) { flagName = flagName.Substring(2); } @@ -139,7 +140,7 @@ private void ParseFlags() // loop through arguments, skipping the first one (the command) for (var i = 1; i <= this.Args.Length - 1; i++) { - if (!this.Args[i].StartsWith("--")) + if (!this.Args[i].StartsWith("--", StringComparison.Ordinal)) { continue; } @@ -151,7 +152,7 @@ private void ParseFlags() { if (!string.IsNullOrEmpty(this.Args[i + 1])) { - if (this.Args[i + 1].StartsWith("--")) + if (this.Args[i + 1].StartsWith("--", StringComparison.Ordinal)) { // next value is another flag, so this flag has no value flagValue = string.Empty; diff --git a/DNN Platform/Library/Security/Cookies/PurgeAuthCookiesTask.cs b/DNN Platform/Library/Security/Cookies/PurgeAuthCookiesTask.cs index a8319619569..fb22a86e4f1 100644 --- a/DNN Platform/Library/Security/Cookies/PurgeAuthCookiesTask.cs +++ b/DNN Platform/Library/Security/Cookies/PurgeAuthCookiesTask.cs @@ -1,39 +1,39 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Security.Cookies -{ - using System; - - using DotNetNuke.Services.Exceptions; - using DotNetNuke.Services.Scheduling; - - /// Scheduled task to remove old cookies. - public class PurgeAuthCookiesTask : SchedulerClient - { - /// Initializes a new instance of the class. - /// Object that will get added to the database as a record of this run. - public PurgeAuthCookiesTask(ScheduleHistoryItem objScheduleHistoryItem) - { - this.ScheduleHistoryItem = objScheduleHistoryItem; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Security.Cookies +{ + using System; + + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Scheduling; + + /// Scheduled task to remove old cookies. + public class PurgeAuthCookiesTask : SchedulerClient + { + /// Initializes a new instance of the class. + /// Object that will get added to the database as a record of this run. + public PurgeAuthCookiesTask(ScheduleHistoryItem objScheduleHistoryItem) + { + this.ScheduleHistoryItem = objScheduleHistoryItem; } - /// - public override void DoWork() - { - try - { - AuthCookieController.Instance.DeleteExpired(DateTime.UtcNow); - this.ScheduleHistoryItem.Succeeded = true; - this.ScheduleHistoryItem.AddLogNote("Purging auth cookies completed"); - } - catch (Exception exc) - { - this.ScheduleHistoryItem.Succeeded = false; - this.ScheduleHistoryItem.AddLogNote(string.Format("Purging auth cookies task failed: {0}.", exc.ToString())); - this.Errored(ref exc); - Exceptions.LogException(exc); - } - } - } -} + /// + public override void DoWork() + { + try + { + AuthCookieController.Instance.DeleteExpired(DateTime.UtcNow); + this.ScheduleHistoryItem.Succeeded = true; + this.ScheduleHistoryItem.AddLogNote("Purging auth cookies completed"); + } + catch (Exception exc) + { + this.ScheduleHistoryItem.Succeeded = false; + this.ScheduleHistoryItem.AddLogNote($"Purging auth cookies task failed: {exc.ToString()}."); + this.Errored(ref exc); + Exceptions.LogException(exc); + } + } + } +} diff --git a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs index d5700ce1977..1a82d88d41e 100644 --- a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs +++ b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs @@ -8,6 +8,8 @@ namespace DotNetNuke.Security.Membership using System.Collections.Generic; using System.Configuration.Provider; using System.Data; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Web; @@ -260,8 +262,8 @@ public override UserInfo GetUserByAuthToken(int portalId, string userToken, stri /// public override void AddUserPortal(int portalId, int userId) { - Requires.NotNullOrEmpty("portalId", portalId.ToString()); - Requires.NotNullOrEmpty("userId", userId.ToString()); + Requires.NotNullOrEmpty("portalId", portalId.ToString(CultureInfo.InvariantCulture)); + Requires.NotNullOrEmpty("userId", userId.ToString(CultureInfo.InvariantCulture)); this.dataProvider.AddUserPortal(portalId, userId); } @@ -310,7 +312,7 @@ public override void ChangeUsername(int userId, string newUsername) EventLogController.Instance.AddLog( "userId", - userId.ToString(), + userId.ToString(CultureInfo.InvariantCulture), portalSettings, UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.USERNAME_UPDATED); @@ -545,7 +547,7 @@ public override UserInfo GetUserByUserName(int portalId, string username) { return CBO.GetCachedObject( new CacheItemArgs( - string.Format(DataCache.UserCacheKey, portalId, username), + string.Format(CultureInfo.InvariantCulture, DataCache.UserCacheKey, portalId, username), DataCache.UserCacheTimeOut, DataCache.UserCachePriority), _ => this.GetUserByUserNameFromDataStore(portalId, username)); @@ -641,6 +643,7 @@ public override ArrayList GetUsers(int portalId, int pageIndex, int pageSize, re } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override IList GetUsersAdvancedSearch(int portalId, int userId, int filterUserId, int filterRoleId, int relationshipTypeId, bool isAdmin, int pageIndex, int pageSize, string sortColumn, bool sortAscending, string propertyNames, string propertyValues) { return FillUserList( @@ -795,7 +798,7 @@ public override partial bool IsUserOnline(UserInfo user) if (objUsersOnline.IsEnabled()) { Hashtable userList = objUsersOnline.GetUserList(); - var onlineUser = (OnlineUserInfo)userList[user.UserID.ToString()]; + var onlineUser = (OnlineUserInfo)userList[user.UserID.ToString(CultureInfo.InvariantCulture)]; if (onlineUser != null) { isOnline = true; @@ -1609,7 +1612,7 @@ private static UserCreateStatus ValidateForProfanity(UserInfo user) var createStatus = UserCreateStatus.AddUser; Hashtable settings = UserController.GetUserSettings(user.PortalID); - bool useProfanityFilter = Convert.ToBoolean(settings["Registration_UseProfanityFilter"]); + bool useProfanityFilter = Convert.ToBoolean(settings["Registration_UseProfanityFilter"], CultureInfo.InvariantCulture); // Validate Profanity if (useProfanityFilter) @@ -1688,7 +1691,7 @@ private UserCreateStatus CreateDNNUser(ref UserInfo user) private void ValidateForDuplicateDisplayName(UserInfo user, ref UserCreateStatus createStatus) { Hashtable settings = UserController.GetUserSettings(user.PortalID); - bool requireUniqueDisplayName = Convert.ToBoolean(settings["Registration_RequireUniqueDisplayName"]); + bool requireUniqueDisplayName = Convert.ToBoolean(settings["Registration_RequireUniqueDisplayName"], CultureInfo.InvariantCulture); if (requireUniqueDisplayName) { diff --git a/DNN Platform/Library/Security/Membership/PasswordConfig.cs b/DNN Platform/Library/Security/Membership/PasswordConfig.cs index 02d9b9b31d9..627686e8db9 100644 --- a/DNN Platform/Library/Security/Membership/PasswordConfig.cs +++ b/DNN Platform/Library/Security/Membership/PasswordConfig.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Security.Membership { using System.ComponentModel; + using System.Globalization; using DotNetNuke.Entities.Controllers; using DotNetNuke.Entities.Host; @@ -25,13 +26,13 @@ public static int PasswordExpiry set { - HostController.Instance.Update("PasswordExpiry", value.ToString()); + HostController.Instance.Update("PasswordExpiry", value.ToString(CultureInfo.InvariantCulture)); } } /// - /// Gets or sets and sets the a Reminder time in days (to remind the user that theire password - /// is about to expire. + /// Gets or sets the Reminder time in days (to remind the user that their password + /// is about to expire). /// /// An integer. [SortOrder(1)] @@ -45,7 +46,7 @@ public static int PasswordExpiryReminder set { - HostController.Instance.Update("PasswordExpiryReminder", value.ToString()); + HostController.Instance.Update("PasswordExpiryReminder", value.ToString(CultureInfo.InvariantCulture)); } } } diff --git a/DNN Platform/Library/Security/Membership/UserLoginStatus.cs b/DNN Platform/Library/Security/Membership/UserLoginStatus.cs index 1c50405fe14..a5b435d0152 100644 --- a/DNN Platform/Library/Security/Membership/UserLoginStatus.cs +++ b/DNN Platform/Library/Security/Membership/UserLoginStatus.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Security.Membership public enum UserLoginStatus { +#pragma warning disable CA1707 // Identifiers should not contain underscores /// The login failed. LOGIN_FAILURE = 0, @@ -30,5 +31,6 @@ public enum UserLoginStatus /// The user's password is a well-known default for host users. [Obsolete("Deprecated in DotNetNuke 9.8.1. No alternative method implemented. Scheduled for removal in v11.0.0.")] LOGIN_INSECUREHOSTPASSWORD = 6, +#pragma warning restore CA1707 } } diff --git a/DNN Platform/Library/Security/Permissions/AdvancedPermissionProvider.cs b/DNN Platform/Library/Security/Permissions/AdvancedPermissionProvider.cs index 609fa351a76..720e347dfaa 100644 --- a/DNN Platform/Library/Security/Permissions/AdvancedPermissionProvider.cs +++ b/DNN Platform/Library/Security/Permissions/AdvancedPermissionProvider.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Security.Permissions { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Linq; using DotNetNuke.Abstractions.Security.Permissions; @@ -123,6 +124,7 @@ public override IEnumerable ImplicitRolesForFolders(int portalId) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override FolderPermissionCollection GetFolderPermissionsCollectionByFolder(int portalId, string folder) { var basePermissions = base.GetFolderPermissionsCollectionByFolder(portalId, folder); @@ -172,6 +174,7 @@ public override bool CanViewModule(ModuleInfo module) || base.CanViewModule(module); /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override ModulePermissionCollection GetModulePermissions(int moduleId, int tabId) { var module = this.moduleController.GetModule(moduleId, tabId, false); diff --git a/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs index 1673806871d..0a08722360c 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Security.Permissions.Controls using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Text; @@ -115,7 +116,7 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) { if (objPermission.PermissionKey == "DEPLOY") { - this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture), Null.NullString, user.UserID, user.DisplayName, true); } } } @@ -163,14 +164,14 @@ protected override void LoadViewState(object savedState) // Load DesktopModuleId if (myState[1] != null) { - this.PortalDesktopModuleID = Convert.ToInt32(myState[1]); + this.PortalDesktopModuleID = Convert.ToInt32(myState[1], CultureInfo.InvariantCulture); } // Load DesktopModulePermissions if (myState[2] != null) { this.desktopModulePermissions = new DesktopModulePermissionCollection(); - string state = Convert.ToString(myState[2]); + string state = Convert.ToString(myState[2], CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(state)) { // First Break the String into individual Keys @@ -262,7 +263,7 @@ private DesktopModulePermissionInfo ParseKeys(string[] settings) } else { - objDesktopModulePermission.DesktopModulePermissionID = Convert.ToInt32(settings[2]); + objDesktopModulePermission.DesktopModulePermissionID = Convert.ToInt32(settings[2], CultureInfo.InvariantCulture); } objDesktopModulePermission.PortalDesktopModuleID = this.PortalDesktopModuleID; diff --git a/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs index bcd15279f4b..21232abde23 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs @@ -8,11 +8,13 @@ namespace DotNetNuke.Security.Permissions.Controls using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; + using DotNetNuke.Abstractions.Security.Permissions; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; @@ -23,6 +25,7 @@ public class FolderPermissionsGrid : PermissionsGrid { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected FolderPermissionCollection FolderPermissions; @@ -102,7 +105,7 @@ protected virtual void GetFolderPermissions() protected override void CreateChildControls() { base.CreateChildControls(); - this.rolePermissionsGrid.ItemDataBound += this.RolePermissionsGrid_ItemDataBound; + this.rolePermissionsGrid.ItemDataBound += RolePermissionsGrid_ItemDataBound; } /// @@ -143,7 +146,7 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) { if (objPermission.PermissionKey == "READ") { - this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture), Null.NullString, user.UserID, user.DisplayName, true); } } } @@ -228,14 +231,14 @@ protected override void LoadViewState(object savedState) // Load FolderPath if (myState[1] != null) { - this.folderPath = Convert.ToString(myState[1]); + this.folderPath = Convert.ToString(myState[1], CultureInfo.InvariantCulture); } // Load FolderPermissions if (myState[2] != null) { this.FolderPermissions = new FolderPermissionCollection(); - string state = Convert.ToString(myState[2]); + string state = Convert.ToString(myState[2], CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(state)) { // First Break the String into individual Keys @@ -312,6 +315,23 @@ private static bool IsImplicitRole(int portalId, int roleId) return FolderPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); } + private static void RolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) + { + var item = e.Item; + + if (item.ItemType is ListItemType.Item or ListItemType.AlternatingItem or ListItemType.SelectedItem) + { + var roleId = int.Parse(((DataRowView)item.DataItem)[0].ToString(), CultureInfo.InvariantCulture); + if (IsImplicitRole(PortalSettings.Current.PortalId, roleId)) + { + if (item.Controls.Cast().Last().Controls[0] is ImageButton actionImage) + { + actionImage.Visible = false; + } + } + } + } + /// Parse the Permission Keys used to persist the Permissions in the ViewState. /// A string array of settings. private FolderPermissionInfo ParseKeys(string[] settings) @@ -326,39 +346,21 @@ private FolderPermissionInfo ParseKeys(string[] settings) } else { - objFolderPermission.FolderPermissionID = Convert.ToInt32(settings[2]); + objFolderPermission.FolderPermissionID = Convert.ToInt32(settings[2], CultureInfo.InvariantCulture); } objFolderPermission.FolderPath = this.FolderPath; return objFolderPermission; } - private void RolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) - { - var item = e.Item; - - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (IsImplicitRole(PortalSettings.Current.PortalId, roleID)) - { - var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; - if (actionImage != null) - { - actionImage.Visible = false; - } - } - } - } - private bool IsPermissionAlwaysGrantedToAdmin(PermissionInfo permissionInfo) { return this.IsSystemFolderPermission(permissionInfo); } - private bool IsSystemFolderPermission(PermissionInfo permissionInfo) + private bool IsSystemFolderPermission(IPermissionDefinitionInfo permissionInfo) { - return this.systemFolderPermissions.Any(pi => pi.PermissionID == permissionInfo.PermissionID); + return this.systemFolderPermissions.Any((IPermissionDefinitionInfo pi) => pi.PermissionId == permissionInfo.PermissionId); } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs index f914a58aeda..440a26e13a2 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs @@ -7,11 +7,13 @@ namespace DotNetNuke.Security.Permissions.Controls using System.Collections; using System.Collections.Generic; using System.Data; + using System.Globalization; using System.Linq; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; + using DotNetNuke.Abstractions.Security.Permissions; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; @@ -112,18 +114,17 @@ protected override void CreateChildControls() /// protected override void AddPermission(ArrayList permissions, UserInfo user) { - bool isMatch = this.modulePermissions.Cast() - .Any(objModulePermission => objModulePermission.UserID == user.UserID); + if (this.modulePermissions.Cast().Any(objModulePermission => objModulePermission.UserId == user.UserID)) + { + return; + } // user not found so add new - if (!isMatch) + foreach (PermissionInfo objPermission in permissions) { - foreach (PermissionInfo objPermission in permissions) + if (objPermission.PermissionKey == "VIEW") { - if (objPermission.PermissionKey == "VIEW") - { - this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); - } + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture), Null.NullString, user.UserID, user.DisplayName, true); } } } @@ -132,8 +133,7 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) protected override void AddPermission(ArrayList permissions, RoleInfo role) { // Search TabPermission Collection for the user - if ( - this.modulePermissions.Cast().Any(p => p.RoleID == role.RoleID)) + if (this.modulePermissions.Cast().Any(p => p.RoleId == role.RoleID)) { return; } @@ -313,26 +313,26 @@ protected override void LoadViewState(object savedState) // Load ModuleID if (myState[1] != null) { - this.ModuleID = Convert.ToInt32(myState[1]); + this.ModuleID = Convert.ToInt32(myState[1], CultureInfo.InvariantCulture); } // Load TabId if (myState[2] != null) { - this.TabId = Convert.ToInt32(myState[2]); + this.TabId = Convert.ToInt32(myState[2], CultureInfo.InvariantCulture); } // Load InheritViewPermissionsFromTab if (myState[3] != null) { - this.InheritViewPermissionsFromTab = Convert.ToBoolean(myState[3]); + this.InheritViewPermissionsFromTab = Convert.ToBoolean(myState[3], CultureInfo.InvariantCulture); } // Load ModulePermissions if (myState[4] != null) { this.modulePermissions = new ModulePermissionCollection(); - string state = Convert.ToString(myState[4]); + string state = Convert.ToString(myState[4], CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(state)) { // First Break the String into individual Keys @@ -437,7 +437,7 @@ private ModulePermissionInfo ParseKeys(string[] settings) } else { - objModulePermission.ModulePermissionID = Convert.ToInt32(settings[2]); + objModulePermission.ModulePermissionID = Convert.ToInt32(settings[2], CultureInfo.InvariantCulture); } objModulePermission.ModuleID = this.ModuleID; @@ -448,13 +448,12 @@ private void RolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventA { var item = e.Item; - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + if (item.ItemType is ListItemType.Item or ListItemType.AlternatingItem or ListItemType.SelectedItem) { - var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (IsImplicitRole(PortalSettings.Current.PortalId, roleID)) + var roleId = int.Parse(((DataRowView)item.DataItem)[0].ToString(), CultureInfo.InvariantCulture); + if (IsImplicitRole(PortalSettings.Current.PortalId, roleId)) { - var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; - if (actionImage != null) + if (item.Controls.Cast().Last().Controls[0] is ImageButton actionImage) { actionImage.Visible = false; } diff --git a/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs index bee3321f39a..4abf7767ac5 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs @@ -29,14 +29,19 @@ namespace DotNetNuke.Security.Permissions.Controls public abstract class PermissionsGrid : Control, INamingContainer { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected const string PermissionTypeGrant = "True"; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected const string PermissionTypeDeny = "False"; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected const string PermissionTypeNull = "Null"; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DataGrid rolePermissionsGrid; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DataGrid userPermissionsGrid; private ArrayList permissions; private ArrayList users; @@ -52,9 +57,9 @@ public abstract class PermissionsGrid : Control, INamingContainer private HiddenField hiddenUserIds; private HiddenField roleField; - private int unAuthUsersRoleId = int.Parse(Globals.glbRoleUnauthUser); + private int unAuthUsersRoleId = int.Parse(Globals.glbRoleUnauthUser, CultureInfo.InvariantCulture); - private int allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); + private int allUsersRoleId = int.Parse(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture); /// Initializes a new instance of the class. public PermissionsGrid() @@ -276,11 +281,11 @@ protected string BuildKey(bool allowAccess, int permissionId, int objectPermissi key = "False"; } - key += "|" + Convert.ToString(permissionId); + key += "|" + Convert.ToString(permissionId, CultureInfo.InvariantCulture); key += "|"; if (objectPermissionId > -1) { - key += Convert.ToString(objectPermissionId); + key += Convert.ToString(objectPermissionId, CultureInfo.InvariantCulture); } key += "|" + roleName; @@ -547,11 +552,11 @@ protected override void OnPreRender(EventArgs e) protected virtual void ParsePermissionKeys(PermissionInfoBase permission, string[] settings) { - permission.PermissionID = Convert.ToInt32(settings[1]); - permission.RoleID = Convert.ToInt32(settings[4]); + permission.PermissionID = Convert.ToInt32(settings[1], CultureInfo.InvariantCulture); + permission.RoleID = Convert.ToInt32(settings[4], CultureInfo.InvariantCulture); permission.RoleName = settings[3]; - permission.AllowAccess = Convert.ToBoolean(settings[0]); - permission.UserID = Convert.ToInt32(settings[5]); + permission.AllowAccess = Convert.ToBoolean(settings[0], CultureInfo.InvariantCulture); + permission.UserID = Convert.ToInt32(settings[5], CultureInfo.InvariantCulture); permission.DisplayName = settings[6]; } @@ -611,14 +616,14 @@ protected virtual void UpdatePermission(PermissionInfo permission, string displa /// The permission state. protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, string stateKey) { - this.RemovePermission(permission.PermissionID, int.Parse(Globals.glbRoleNothing), userId); + this.RemovePermission(permission.PermissionID, int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture), userId); switch (stateKey) { case PermissionTypeGrant: - this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, true); + this.AddPermission(permission, int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture), Null.NullString, userId, displayName, true); break; case PermissionTypeDeny: - this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, false); + this.AddPermission(permission, int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture), Null.NullString, userId, displayName, false); break; } } @@ -641,7 +646,7 @@ protected void UpdateRolePermissions() var rolesList = this.Roles.Cast().ToList(); foreach (DataGridItem dgi in this.rolePermissionsGrid.Items) { - var roleId = int.Parse(dgi.Cells[1].Text); + var roleId = int.Parse(dgi.Cells[1].Text, CultureInfo.InvariantCulture); if (rolesList.All(r => r.RoleID != roleId)) { continue; @@ -676,7 +681,7 @@ protected void UpdateUserPermissions() var usersList = this.users.Cast().ToList(); foreach (DataGridItem dgi in this.userPermissionsGrid.Items) { - var userId = int.Parse(dgi.Cells[1].Text); + var userId = int.Parse(dgi.Cells[1].Text, CultureInfo.InvariantCulture); if (usersList.All(u => u.UserID != userId)) { continue; @@ -708,7 +713,7 @@ protected void UpdateUserPermissions() /// The event arguments. protected virtual void RoleGroupsSelectedIndexChanged(object sender, EventArgs e) { - this.FillSelectRoleComboBox(int.Parse(this.cboRoleGroups.SelectedValue)); + this.FillSelectRoleComboBox(int.Parse(this.cboRoleGroups.SelectedValue, CultureInfo.InvariantCulture)); } /// AddUser runs when the Add user linkbutton is clicked. @@ -721,7 +726,7 @@ protected virtual void AddUser(object sender, EventArgs e) { foreach (var id in this.hiddenUserIds.Value.Split(',')) { - var userId = Convert.ToInt32(id); + var userId = Convert.ToInt32(id, CultureInfo.InvariantCulture); var user = UserController.GetUserById(this.PortalId, userId); if (user != null) { @@ -1003,7 +1008,7 @@ private void SetUpGrid(DataGrid grid, string nameColumnDataField, string idColum private void Grid_ItemCommand(object source, DataGridCommandEventArgs e) { - var entityID = int.Parse(e.CommandArgument.ToString()); + var entityId = int.Parse(e.CommandArgument.ToString(), CultureInfo.InvariantCulture); var command = GetGridCommand(e.CommandName); var entityType = GetCommandType(e.CommandName); switch (command) @@ -1011,11 +1016,11 @@ private void Grid_ItemCommand(object source, DataGridCommandEventArgs e) case "DELETE": if (entityType == "ROLE") { - this.DeleteRolePermissions(entityID); + this.DeleteRolePermissions(entityId); } else if (entityType == "USER") { - this.DeleteUserPermissions(entityID); + this.DeleteUserPermissions(entityId); } this.BindData(); @@ -1023,13 +1028,13 @@ private void Grid_ItemCommand(object source, DataGridCommandEventArgs e) } } - private void DeleteRolePermissions(int entityID) + private void DeleteRolePermissions(int entityId) { // PermissionsList.RemoveAll(p => p.RoleID == entityID); - var permissionToDelete = this.PermissionsList.Where(p => p.RoleID == entityID); + var permissionToDelete = this.PermissionsList.Where(p => p.RoleID == entityId); foreach (PermissionInfoBase permission in permissionToDelete) { - this.RemovePermission(permission.PermissionID, entityID, permission.UserID); + this.RemovePermission(permission.PermissionID, entityId, permission.UserID); } } @@ -1080,8 +1085,8 @@ private void FillSelectRoleComboBox(int selectedRoleGroupId) this.cboSelectRole.Items.Add(new ListItem(role.Key, role.Value.ToString(CultureInfo.InvariantCulture))); } - int[] defaultRoleIds = { this.AllUsersRoleId, portalSettings.RegisteredRoleId, portalSettings.AdministratorRoleId }; - var itemToSelect = this.cboSelectRole.Items.Cast().FirstOrDefault(i => !defaultRoleIds.Contains(int.Parse(i.Value))); + int[] defaultRoleIds = [this.AllUsersRoleId, portalSettings.RegisteredRoleId, portalSettings.AdministratorRoleId,]; + var itemToSelect = this.cboSelectRole.Items.Cast().FirstOrDefault(i => !defaultRoleIds.Contains(int.Parse(i.Value, CultureInfo.InvariantCulture))); if (itemToSelect != null) { this.cboSelectRole.SelectedValue = itemToSelect.Value; @@ -1093,7 +1098,7 @@ private void SetErrorMessage(string errorKey) this.lblErrorMessage = new Label { // TODO Remove DEBUG test - Text = "
    " + (errorKey.StartsWith("DEBUG") ? errorKey : Localization.GetString(errorKey)), + Text = "
    " + (errorKey.StartsWith("DEBUG", StringComparison.Ordinal) ? errorKey : Localization.GetString(errorKey)), CssClass = "NormalRed", }; this.pnlPermissions.Controls.Add(this.lblErrorMessage); @@ -1103,13 +1108,12 @@ private void RolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventA { var item = e.Item; - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + if (item.ItemType is ListItemType.Item or ListItemType.AlternatingItem or ListItemType.SelectedItem) { - var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (roleID == PortalSettings.Current.AdministratorRoleId || roleID == this.AllUsersRoleId || roleID == PortalSettings.Current.RegisteredRoleId) + var roleId = int.Parse(((DataRowView)item.DataItem)[0].ToString(), CultureInfo.InvariantCulture); + if (roleId == PortalSettings.Current.AdministratorRoleId || roleId == this.AllUsersRoleId || roleId == PortalSettings.Current.RegisteredRoleId) { - var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; - if (actionImage != null) + if (item.Controls.Cast().Last().Controls[0] is ImageButton actionImage) { actionImage.Visible = false; } @@ -1119,7 +1123,7 @@ private void RolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventA private void CreateAddRoleControls() { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var portalSettings = PortalController.Instance.GetCurrentSettings(); var arrGroups = RoleController.GetRoleGroups(portalSettings.PortalId); var addRoleControls = new Panel { CssClass = "dnnFormItem" }; @@ -1166,8 +1170,7 @@ private void CreateAddRoleControls() private void AddRole(object sender, EventArgs e) { this.UpdatePermissions(); - int selectedRoleId; - if (!int.TryParse(this.roleField.Value, out selectedRoleId)) + if (!int.TryParse(this.roleField.Value, out var selectedRoleId)) { // Role not selected this.SetErrorMessage("InvalidRoleId"); diff --git a/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs index 8d0730ae87e..386696b096e 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Security.Permissions.Controls using System.Collections; using System.Collections.Generic; using System.Data; + using System.Globalization; using System.Linq; using System.Text; using System.Web.UI; @@ -138,7 +139,7 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) { if (objPermission.PermissionKey == "VIEW") { - this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture), Null.NullString, user.UserID, user.DisplayName, true); } } } @@ -211,14 +212,14 @@ protected override void LoadViewState(object savedState) // Load TabId if (myState[1] != null) { - this.TabID = Convert.ToInt32(myState[1]); + this.TabID = Convert.ToInt32(myState[1], CultureInfo.InvariantCulture); } // Load TabPermissions if (myState[2] != null) { this.tabPermissions = new TabPermissionCollection(); - string state = Convert.ToString(myState[2]); + string state = Convert.ToString(myState[2], CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(state)) { // First Break the String into individual Keys @@ -296,10 +297,10 @@ private static void RolePermissionsGrid_ItemDataBound(object sender, DataGridIte { var item = e.Item; - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + if (item.ItemType is ListItemType.Item or ListItemType.AlternatingItem or ListItemType.SelectedItem) { - var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (IsImplicitRole(PortalSettings.Current.PortalId, roleID)) + var roleId = int.Parse(((DataRowView)item.DataItem)[0].ToString(), CultureInfo.InvariantCulture); + if (IsImplicitRole(PortalSettings.Current.PortalId, roleId)) { if (item.Controls.Cast().Last().Controls[0] is ImageButton actionImage) { @@ -335,7 +336,7 @@ private TabPermissionInfo ParseKeys(string[] settings) } else { - objTabPermission.TabPermissionID = Convert.ToInt32(settings[2]); + objTabPermission.TabPermissionID = Convert.ToInt32(settings[2], CultureInfo.InvariantCulture); } objTabPermission.TabID = this.TabID; diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs index bdcc8a81f55..72c2296b296 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs @@ -6,12 +6,15 @@ namespace DotNetNuke.Security.Permissions using System; using System.Collections; using System.Collections.Generic; + using System.Linq; + using DotNetNuke.Abstractions.Security.Permissions; + using DotNetNuke.Collections; using DotNetNuke.Common.Utilities; /// DesktopModulePermissionCollection provides a custom collection for objects. [Serializable] - public class DesktopModulePermissionCollection : CollectionBase + public class DesktopModulePermissionCollection : GenericCollectionBase { /// Initializes a new instance of the class. public DesktopModulePermissionCollection() @@ -46,24 +49,6 @@ public DesktopModulePermissionCollection(ArrayList desktopModulePermissions, int } } - public DesktopModulePermissionInfo this[int index] - { - get - { - return (DesktopModulePermissionInfo)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public int Add(DesktopModulePermissionInfo value) - { - return this.List.Add(value); - } - public int Add(DesktopModulePermissionInfo value, bool checkForDuplicates) { int id = Null.NullInteger; @@ -74,9 +59,9 @@ public int Add(DesktopModulePermissionInfo value, bool checkForDuplicates) else { bool isMatch = false; - foreach (PermissionInfoBase permission in this.List) + foreach (IPermissionInfo permission in this.List) { - if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) + if (permission.PermissionId == value.PermissionID && permission.UserId == value.UserID && permission.RoleId == value.RoleID) { isMatch = true; break; @@ -128,26 +113,6 @@ public bool CompareTo(DesktopModulePermissionCollection objDesktopModulePermissi return true; } - public bool Contains(DesktopModulePermissionInfo value) - { - return this.List.Contains(value); - } - - public int IndexOf(DesktopModulePermissionInfo value) - { - return this.List.IndexOf(value); - } - - public void Insert(int index, DesktopModulePermissionInfo value) - { - this.List.Insert(index, value); - } - - public void Remove(DesktopModulePermissionInfo value) - { - this.List.Remove(value); - } - public void Remove(int permissionID, int roleID, int userID) { foreach (PermissionInfoBase permission in this.List) @@ -162,13 +127,7 @@ public void Remove(int permissionID, int roleID, int userID) public List ToList() { - var list = new List(); - foreach (PermissionInfoBase permission in this.List) - { - list.Add(permission); - } - - return list; + return [..this.List.Cast()]; } public string ToString(string key) diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs index f43aa6329c6..4aa08bf0606 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs @@ -6,11 +6,14 @@ namespace DotNetNuke.Security.Permissions using System; using System.Collections; using System.Collections.Generic; + using System.Linq; + using DotNetNuke.Abstractions.Security.Permissions; + using DotNetNuke.Collections; using DotNetNuke.Common.Utilities; [Serializable] - public class FolderPermissionCollection : CollectionBase + public class FolderPermissionCollection : GenericCollectionBase { /// Initializes a new instance of the class. public FolderPermissionCollection() @@ -45,24 +48,6 @@ public FolderPermissionCollection(ArrayList folderPermissions, string folderPath } } - public FolderPermissionInfo this[int index] - { - get - { - return (FolderPermissionInfo)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public int Add(FolderPermissionInfo value) - { - return this.List.Add(value); - } - public int Add(FolderPermissionInfo value, bool checkForDuplicates) { int id = Null.NullInteger; @@ -73,9 +58,9 @@ public int Add(FolderPermissionInfo value, bool checkForDuplicates) else { bool isMatch = false; - foreach (PermissionInfoBase permission in this.List) + foreach (IPermissionInfo permission in this.List) { - if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) + if (permission.PermissionId == value.PermissionID && permission.UserId == value.UserID && permission.RoleId == value.RoleID) { isMatch = true; break; @@ -115,26 +100,11 @@ public void AddRange(FolderPermissionCollection folderPermissions) } } - public int IndexOf(FolderPermissionInfo value) - { - return this.List.IndexOf(value); - } - - public void Insert(int index, FolderPermissionInfo value) - { - this.List.Insert(index, value); - } - - public void Remove(FolderPermissionInfo value) - { - this.List.Remove(value); - } - public void Remove(int permissionID, int roleID, int userID) { - foreach (PermissionInfoBase permission in this.List) + foreach (IPermissionInfo permission in this.List) { - if (permission.PermissionID == permissionID && permission.UserID == userID && permission.RoleID == roleID) + if (permission.PermissionId == permissionID && permission.UserId == userID && permission.RoleId == roleID) { this.List.Remove(permission); break; @@ -142,17 +112,12 @@ public void Remove(int permissionID, int roleID, int userID) } } - public bool Contains(FolderPermissionInfo value) - { - return this.List.Contains(value); - } - public bool Contains(string key, int folderId, int roleId, int userId) { bool result = Null.NullBoolean; - foreach (FolderPermissionInfo permission in this.List) + foreach (IFolderPermissionInfo permission in this.List) { - if (permission.PermissionKey == key && permission.FolderID == folderId && permission.RoleID == roleId && permission.UserID == userId) + if (permission.PermissionKey == key && permission.FolderId == folderId && permission.RoleId == roleId && permission.UserId == userId) { result = true; break; @@ -173,7 +138,9 @@ public bool CompareTo(FolderPermissionCollection objFolderPermissionCollection) objFolderPermissionCollection.InnerList.Sort(new CompareFolderPermissions()); for (int i = 0; i <= this.Count - 1; i++) { - if (objFolderPermissionCollection[i].FolderPermissionID != this[i].FolderPermissionID || objFolderPermissionCollection[i].AllowAccess != this[i].AllowAccess) + IFolderPermissionInfo otherPermission = objFolderPermissionCollection[i]; + IFolderPermissionInfo thisPermission = this[i]; + if (otherPermission.FolderPermissionId != thisPermission.FolderPermissionId || otherPermission.AllowAccess != thisPermission.AllowAccess) { return false; } @@ -184,13 +151,7 @@ public bool CompareTo(FolderPermissionCollection objFolderPermissionCollection) public List ToList() { - var list = new List(); - foreach (PermissionInfoBase permission in this.List) - { - list.Add(permission); - } - - return list; + return [..this.List.Cast()]; } public string ToString(string key) diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs index e175485872d..eb9bc6362f9 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Security.Permissions { using System; using System.Collections.Generic; + using System.Globalization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Users; @@ -179,11 +180,11 @@ protected override Func GetFactory() return () => new FolderPermissionController(); } - private static void ClearPermissionCache(int portalID) + private static void ClearPermissionCache(int portalId) { - DataCache.ClearFolderPermissionsCache(portalID); - DataCache.ClearCache(string.Format("Folders|{0}|", portalID)); - DataCache.ClearFolderCache(portalID); + DataCache.ClearFolderPermissionsCache(portalId); + DataCache.ClearCache(string.Format(CultureInfo.CurrentCulture, "Folders|{0}|", portalId)); + DataCache.ClearFolderCache(portalId); } private static bool CopyPermissionsToSubfoldersRecursive(IFolderInfo folder, FolderPermissionCollection newPermissions) diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs index 9e0d35db3fb..de33cb332a5 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs @@ -8,12 +8,14 @@ namespace DotNetNuke.Security.Permissions using System.Collections.Generic; using System.Linq; + using DotNetNuke.Abstractions.Security.Permissions; + using DotNetNuke.Collections; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; /// ModulePermissionCollection provides a custom collection for objects. [Serializable] - public class ModulePermissionCollection : CollectionBase + public class ModulePermissionCollection : GenericCollectionBase { /// Initializes a new instance of the class. public ModulePermissionCollection() @@ -61,24 +63,6 @@ public ModulePermissionCollection(ModuleInfo objModule) } } - public ModulePermissionInfo this[int index] - { - get - { - return (ModulePermissionInfo)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public int Add(ModulePermissionInfo value) - { - return this.List.Add(value); - } - public int Add(ModulePermissionInfo value, bool checkForDuplicates) { int id = Null.NullInteger; @@ -89,9 +73,9 @@ public int Add(ModulePermissionInfo value, bool checkForDuplicates) else { bool isMatch = false; - foreach (PermissionInfoBase permission in this.List) + foreach (IPermissionInfo permission in this.List) { - if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) + if (permission.PermissionId == value.PermissionID && permission.UserId == value.UserID && permission.RoleId == value.RoleID) { isMatch = true; break; @@ -143,26 +127,6 @@ public bool CompareTo(ModulePermissionCollection objModulePermissionCollection) return true; } - public bool Contains(ModulePermissionInfo value) - { - return this.List.Contains(value); - } - - public int IndexOf(ModulePermissionInfo value) - { - return this.List.IndexOf(value); - } - - public void Insert(int index, ModulePermissionInfo value) - { - this.List.Insert(index, value); - } - - public void Remove(ModulePermissionInfo value) - { - this.List.Remove(value); - } - public void Remove(int permissionID, int roleID, int userID) { var idx = 0; @@ -180,13 +144,7 @@ public void Remove(int permissionID, int roleID, int userID) public List ToList() { - var list = new List(); - foreach (PermissionInfoBase permission in this.List) - { - list.Add(permission); - } - - return list; + return [..this.List.Cast()]; } public string ToString(string key) diff --git a/DNN Platform/Library/Security/Permissions/PermissionController.cs b/DNN Platform/Library/Security/Permissions/PermissionController.cs index 6cb8273d440..d490e7d28f8 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionController.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Security.Permissions using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Text; @@ -63,7 +64,7 @@ public static string BuildPermissions(IList permissions, string permissionKey) string permissionsString = permissionsBuilder.ToString(); // ensure leading delimiter - if (!permissionsString.StartsWith(";")) + if (!permissionsString.StartsWith(";", StringComparison.Ordinal)) { permissionsString = permissionsString.Insert(0, ";"); } @@ -120,7 +121,7 @@ public void DeletePermission(int permissionID) { EventLogController.Instance.AddLog( "PermissionID", - permissionID.ToString(), + permissionID.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PERMISSION_DELETED); @@ -201,10 +202,10 @@ public T RemapPermission(T permission, int portalId) switch (permission.RoleName) { case Globals.glbRoleAllUsersName: - roleID = Convert.ToInt32(Globals.glbRoleAllUsers); + roleID = Convert.ToInt32(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture); break; case Globals.glbRoleUnauthUserName: - roleID = Convert.ToInt32(Globals.glbRoleUnauthUser); + roleID = Convert.ToInt32(Globals.glbRoleUnauthUser, CultureInfo.InvariantCulture); break; default: RoleInfo role = RoleController.Instance.GetRole(portalId, r => r.RoleName == permission.RoleName); diff --git a/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs b/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs index fe213de2e9c..5828ea0dc8a 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Security.Permissions { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Abstractions.Security.Permissions; @@ -35,7 +36,7 @@ public abstract class PermissionInfoBase : PermissionInfo, IPermissionInfo /// Initializes a new instance of the class. public PermissionInfoBase() { - this.roleId = int.Parse(Globals.glbRoleNothing); + this.roleId = int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture); this.allowAccess = false; this.roleName = Null.NullString; this.userId = Null.NullInteger; @@ -171,7 +172,7 @@ protected override void FillInternal(IDataReader dr) } else { - @this.RoleId = int.Parse(Globals.glbRoleNothing); + @this.RoleId = int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture); @this.RoleName = string.Empty; } diff --git a/DNN Platform/Library/Security/Permissions/PermissionProvider.cs b/DNN Platform/Library/Security/Permissions/PermissionProvider.cs index 01797bf6f18..53711165363 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionProvider.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionProvider.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Security.Permissions using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using DotNetNuke.Collections.Internal; @@ -186,7 +187,7 @@ public virtual FolderPermissionCollection GetFolderPermissionsCollectionByFolder } return folderPermissions; #else - var cacheKey = string.Format(DataCache.FolderPathPermissionCacheKey, portalID, folder); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.FolderPathPermissionCacheKey, portalID, folder); return CBO.GetCachedObject( new CacheItemArgs(cacheKey, DataCache.FolderPermissionCacheTimeOut, DataCache.FolderPermissionCachePriority) { @@ -301,6 +302,7 @@ public virtual void SaveFolderPermissions(IFolderInfo folder) /// Returns a flag indicating whether the current user can administer a module. /// The page. /// A flag indicating whether the user has permission. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual bool CanAdminModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(AdminModulePermissionKey)); @@ -309,6 +311,7 @@ public virtual bool CanAdminModule(ModuleInfo module) /// Returns a flag indicating whether the current user can delete a module. /// The page. /// A flag indicating whether the user has permission. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual bool CanDeleteModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(DeleteModulePermissionKey)); @@ -317,6 +320,7 @@ public virtual bool CanDeleteModule(ModuleInfo module) /// Returns a flag indicating whether the current user can edit module content. /// The page. /// A flag indicating whether the user has permission. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual bool CanEditModuleContent(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(ContentModulePermissionKey)); @@ -325,6 +329,7 @@ public virtual bool CanEditModuleContent(ModuleInfo module) /// Returns a flag indicating whether the current user can export a module. /// The page. /// A flag indicating whether the user has permission. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual bool CanExportModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(ExportModulePermissionKey)); @@ -333,6 +338,7 @@ public virtual bool CanExportModule(ModuleInfo module) /// Returns a flag indicating whether the current user can import a module. /// The page. /// A flag indicating whether the user has permission. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual bool CanImportModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(ImportModulePermissionKey)); @@ -341,6 +347,7 @@ public virtual bool CanImportModule(ModuleInfo module) /// Returns a flag indicating whether the current user can manage a module's settings. /// The page. /// A flag indicating whether the user has permission. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual bool CanManageModule(ModuleInfo module) { return PortalSecurity.IsInRoles(module.ModulePermissions.ToString(ManageModulePermissionKey)); @@ -349,6 +356,7 @@ public virtual bool CanManageModule(ModuleInfo module) /// Returns a flag indicating whether the current user can view a module. /// The page. /// A flag indicating whether the user has permission. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual bool CanViewModule(ModuleInfo module) { bool canView; @@ -503,6 +511,7 @@ public virtual bool HasModulePermission(ModulePermissionCollection modulePermiss /// SaveModulePermissions updates a Module's permissions. /// The Module to update. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] public virtual void SaveModulePermissions(ModuleInfo module) { if (module.ModulePermissions != null) @@ -925,7 +934,7 @@ private static DNNCacheDependency GetCacheDependency(int portalId) if (dependency == null) { var startAt = DateTime.UtcNow; - var cacheKey = string.Format(DataCache.FolderPermissionCacheKey, portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.FolderPermissionCacheKey, portalId); DataCache.SetCache(cacheKey, portalId); // no expiration set for this dependency = new DNNCacheDependency(null, new[] { cacheKey }, startAt); using (cacheDependencyDict.GetWriteLock()) @@ -1000,7 +1009,7 @@ private object GetFolderPermissionsCallBack(CacheItemArgs cacheItemArgs) private Dictionary GetFolderPermissions(int PortalID) { - string cacheKey = string.Format(DataCache.FolderPermissionCacheKey, PortalID); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.FolderPermissionCacheKey, PortalID); return CBO.GetCachedObject>( new CacheItemArgs(cacheKey, DataCache.FolderPermissionCacheTimeOut, DataCache.FolderPermissionCachePriority, PortalID), GetFolderPermissionsCallBack); @@ -1140,7 +1149,7 @@ private static List DefaultImplicitRoles(int portalId) /// The ID of the tab. private Dictionary GetModulePermissions(int tabId) { - string cacheKey = string.Format(DataCache.ModulePermissionCacheKey, tabId); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.ModulePermissionCacheKey, tabId); return CBO.GetCachedObject>( new CacheItemArgs(cacheKey, DataCache.ModulePermissionCacheTimeOut, DataCache.ModulePermissionCachePriority, tabId), this.GetModulePermissionsCallBack); } @@ -1193,7 +1202,7 @@ private object GetModulePermissionsCallBack(CacheItemArgs cacheItemArgs) /// The ID of the portal. private Dictionary GetTabPermissions(int portalID) { - string cacheKey = string.Format(DataCache.TabPermissionCacheKey, portalID); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabPermissionCacheKey, portalID); return CBO.GetCachedObject>( new CacheItemArgs(cacheKey, DataCache.TabPermissionCacheTimeOut, DataCache.TabPermissionCachePriority, portalID), this.GetTabPermissionsCallBack); @@ -1249,7 +1258,7 @@ private object GetTabPermissionsCallBack(CacheItemArgs cacheItemArgs) /// The ID of the portal. private Dictionary GetPortalPermissionsDic(int portalID) { - string cacheKey = string.Format(DataCache.PortalPermissionCacheKey, portalID); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PortalPermissionCacheKey, portalID); return CBO.GetCachedObject>( new CacheItemArgs(cacheKey, DataCache.PortalPermissionCacheTimeOut, DataCache.PortalPermissionCachePriority, portalID), this.GetPortalPermissionsCallBack); diff --git a/DNN Platform/Library/Security/Permissions/PortalPermissionCollection.cs b/DNN Platform/Library/Security/Permissions/PortalPermissionCollection.cs index 2a2f3d88c43..ee350366e73 100644 --- a/DNN Platform/Library/Security/Permissions/PortalPermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/PortalPermissionCollection.cs @@ -9,12 +9,14 @@ namespace DotNetNuke.Security.Permissions using System.Linq; using System.Xml.Serialization; + using DotNetNuke.Abstractions.Security.Permissions; + using DotNetNuke.Collections; using DotNetNuke.Common.Utilities; /// PortalPermissionCollection provides a custom collection for objects. [Serializable] [XmlRoot("portalpermissions")] - public class PortalPermissionCollection : CollectionBase + public class PortalPermissionCollection : GenericCollectionBase { /// Initializes a new instance of the class. public PortalPermissionCollection() @@ -49,24 +51,6 @@ public PortalPermissionCollection(ArrayList portalPermissions, int portalId) } } - public PortalPermissionInfo this[int index] - { - get - { - return (PortalPermissionInfo)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public int Add(PortalPermissionInfo value) - { - return this.List.Add(value); - } - public int Add(PortalPermissionInfo value, bool checkForDuplicates) { int id = Null.NullInteger; @@ -78,9 +62,9 @@ public int Add(PortalPermissionInfo value, bool checkForDuplicates) else { bool isMatch = false; - foreach (PermissionInfoBase permission in this.List) + foreach (IPermissionInfo permission in this.List) { - if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) + if (permission.PermissionId == value.PermissionID && permission.UserId == value.UserID && permission.RoleId == value.RoleID) { isMatch = true; break; @@ -144,26 +128,6 @@ public bool CompareTo(PortalPermissionCollection objPortalPermissionCollection) return true; } - public bool Contains(PortalPermissionInfo value) - { - return this.List.Contains(value); - } - - public int IndexOf(PortalPermissionInfo value) - { - return this.List.IndexOf(value); - } - - public void Insert(int index, PortalPermissionInfo value) - { - this.List.Insert(index, value); - } - - public void Remove(PortalPermissionInfo value) - { - this.List.Remove(value); - } - public void Remove(int permissionID, int roleID, int userID) { foreach (PermissionInfoBase permission in this.List) @@ -178,13 +142,7 @@ public void Remove(int permissionID, int roleID, int userID) public List ToList() { - var list = new List(); - foreach (PermissionInfoBase permission in this.List) - { - list.Add(permission); - } - - return list; + return [..this.List.Cast()]; } public string ToString(string key) diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs b/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs index 8362bec990d..0f4b6545c0c 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs @@ -9,12 +9,14 @@ namespace DotNetNuke.Security.Permissions using System.Linq; using System.Xml.Serialization; + using DotNetNuke.Abstractions.Security.Permissions; + using DotNetNuke.Collections; using DotNetNuke.Common.Utilities; /// TabPermissionCollection provides a custom collection for objects. [Serializable] [XmlRoot("tabpermissions")] - public class TabPermissionCollection : CollectionBase + public class TabPermissionCollection : GenericCollectionBase { /// Initializes a new instance of the class. public TabPermissionCollection() @@ -47,25 +49,7 @@ public TabPermissionCollection(ArrayList tabPermissions, int tabId) this.Add(permission); } } - } - - public TabPermissionInfo this[int index] - { - get - { - return (TabPermissionInfo)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public int Add(TabPermissionInfo value) - { - return this.List.Add(value); - } + } public int Add(TabPermissionInfo value, bool checkForDuplicates) { @@ -78,9 +62,9 @@ public int Add(TabPermissionInfo value, bool checkForDuplicates) else { bool isMatch = false; - foreach (PermissionInfoBase permission in this.List) + foreach (IPermissionInfo permission in this.List) { - if (permission.PermissionID == value.PermissionID && permission.UserID == value.UserID && permission.RoleID == value.RoleID) + if (permission.PermissionId == value.PermissionID && permission.UserId == value.UserID && permission.RoleId == value.RoleID) { isMatch = true; break; @@ -144,26 +128,6 @@ public bool CompareTo(TabPermissionCollection objTabPermissionCollection) return true; } - public bool Contains(TabPermissionInfo value) - { - return this.List.Contains(value); - } - - public int IndexOf(TabPermissionInfo value) - { - return this.List.IndexOf(value); - } - - public void Insert(int index, TabPermissionInfo value) - { - this.List.Insert(index, value); - } - - public void Remove(TabPermissionInfo value) - { - this.List.Remove(value); - } - public void Remove(int permissionID, int roleID, int userID) { foreach (PermissionInfoBase permission in this.List) @@ -178,13 +142,7 @@ public void Remove(int permissionID, int roleID, int userID) public List ToList() { - var list = new List(); - foreach (PermissionInfoBase permission in this.List) - { - list.Add(permission); - } - - return list; + return [..this.List.Cast()]; } public string ToString(string key) diff --git a/DNN Platform/Library/Security/PortalSecurity.cs b/DNN Platform/Library/Security/PortalSecurity.cs index f53cc028fef..383f15b6181 100644 --- a/DNN Platform/Library/Security/PortalSecurity.cs +++ b/DNN Platform/Library/Security/PortalSecurity.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Security using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Security.Cryptography; using System.Text; @@ -84,7 +85,7 @@ public partial class PortalSecurity new Regex("javascript:", RxOptions), new Regex("vbscript:", RxOptions), new Regex("unescape", RxOptions), - new Regex("alert[\\s( )]*\\([\\s( )]*'?[\\s( )]*[\"(")]?", RxOptions), + new Regex(@"alert[\s( )]*\([\s( )]*'?[\s( )]*[""(")]?", RxOptions), new Regex(@"eval*.\(", RxOptions), }; @@ -97,7 +98,8 @@ public partial class PortalSecurity /// enumerated values in a single variable by OR'ing the individual values /// together. /// - [Flags] + [Flags] + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public enum FilterFlag { /// Replaces line breaks with <br> tags. @@ -266,7 +268,7 @@ public static bool IsDenied(UserInfo objUserInfo, PortalSettings settings, strin if (!string.IsNullOrEmpty(role)) { // Deny permission - if (role.StartsWith("!")) + if (role.StartsWith("!", StringComparison.Ordinal)) { // Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) if (settings != null && !(settings.PortalId == objUserInfo.PortalID && objUserInfo.IsInRole(settings.AdministratorRoleName))) @@ -803,11 +805,11 @@ public void SignOut() cookie.Expires = DateTime.Now.AddYears(-30); } - // clear any authentication provider tokens that match *UserToken convention e.g FacebookUserToken ,TwitterUserToken, LiveUserToken and GoogleUserToken + // clear any authentication provider tokens that match *UserToken convention e.g. FacebookUserToken ,TwitterUserToken, LiveUserToken and GoogleUserToken var authCookies = HttpContext.Current.Request.Cookies.AllKeys; foreach (var authCookie in authCookies) { - if (authCookie.EndsWith("UserToken")) + if (authCookie.EndsWith("UserToken", StringComparison.OrdinalIgnoreCase)) { var auth = HttpContext.Current.Response.Cookies[authCookie]; if (auth != null) @@ -929,7 +931,7 @@ private static void ProcessSecurityRole(UserInfo user, IPortalSettings settings, if (!string.IsNullOrEmpty(roleName)) { // Deny permission - if (roleName.StartsWith("!")) + if (roleName.StartsWith("!", StringComparison.Ordinal)) { // Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) if (settings != null && !(settings.PortalId == user.PortalID && user.IsInRole(settings.AdministratorRoleName))) @@ -978,7 +980,7 @@ private static string BytesToHexString(IEnumerable bytes) var hexString = new StringBuilder(); foreach (var b in bytes) { - hexString.Append(string.Format("{0:X2}", b)); + hexString.Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", b)); } return hexString.ToString(); diff --git a/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs b/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs index 66d3316d078..0ca5b9af442 100644 --- a/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs +++ b/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs @@ -59,16 +59,16 @@ public override void GetUserProfile(ref UserInfo user) break; } - int definitionId = Convert.ToInt32(dr["PropertyDefinitionId"]); + int definitionId = Convert.ToInt32(dr["PropertyDefinitionId"], CultureInfo.InvariantCulture); profProperty = properties.GetById(definitionId); if (profProperty != null) { - profProperty.PropertyValue = Convert.ToString(dr["PropertyValue"]); + profProperty.PropertyValue = Convert.ToString(dr["PropertyValue"], CultureInfo.InvariantCulture); var extendedVisibility = string.Empty; var schemaTable = dr.GetSchemaTable(); if (schemaTable != null && schemaTable.Select("ColumnName = 'ExtendedVisibility'").Length > 0) { - extendedVisibility = Convert.ToString(dr["ExtendedVisibility"]); + extendedVisibility = Convert.ToString(dr["ExtendedVisibility"], CultureInfo.InvariantCulture); } profProperty.ProfileVisibility = new ProfileVisibility(portalId, extendedVisibility) @@ -162,7 +162,7 @@ public override void UpdateUserProfile(UserInfo user) private static string GetProfileCacheKey(UserInfo user) { - return string.Format(DataCache.UserProfileCacheKey, user.PortalID, user.Username); + return string.Format(CultureInfo.InvariantCulture, DataCache.UserProfileCacheKey, user.PortalID, user.Username); } private void UpdateTimeZoneInfo(UserInfo user, ProfilePropertyDefinitionCollection properties) diff --git a/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs b/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs index 373868537c7..db07236ac10 100644 --- a/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs +++ b/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Security.Roles using System.Collections.Generic; using System.Data; using System.Data.SqlClient; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; @@ -196,18 +197,18 @@ public override IList GetUserRoles(UserInfo user, bool includePriv } /// GetUserRoles gets a collection of User/Role objects from the Data Store. - /// Id of the portal. + /// ID of the portal. /// The user to fetch roles for. /// The role to fetch users for. /// An ArrayList of UserRoleInfo objects. + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override ArrayList GetUserRoles(int portalId, string userName, string roleName) { return CBO.FillCollection(this.dataProvider.GetUserRolesByUsername(portalId, userName, roleName), typeof(UserRoleInfo)); } /// Get the users in a role (as User objects). - /// Id of the portal (If -1 all roles for all portals are - /// retrieved. + /// ID of the portal (If -1 all roles for all portals are retrieved). /// The role to fetch users for. /// An ArrayList of UserInfo objects. public override ArrayList GetUsersByRoleName(int portalId, string roleName) @@ -269,6 +270,7 @@ public override RoleGroupInfo GetRoleGroup(int portalId, int roleGroupId) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override RoleGroupInfo GetRoleGroupByName(int portalId, string roleGroupName) { roleGroupName = roleGroupName.Trim(); @@ -303,7 +305,7 @@ private static void ClearRoleGroupCache(int portalId) private static string GetRoleGroupsCacheKey(int portalId) { - return string.Format(DataCache.RoleGroupsCacheKey, portalId); + return string.Format(CultureInfo.InvariantCulture, DataCache.RoleGroupsCacheKey, portalId); } private void AddDNNUserRole(UserRoleInfo userRole) diff --git a/DNN Platform/Library/Security/Roles/RoleController.cs b/DNN Platform/Library/Security/Roles/RoleController.cs index f7c4617ebd5..058cbde6888 100644 --- a/DNN Platform/Library/Security/Roles/RoleController.cs +++ b/DNN Platform/Library/Security/Roles/RoleController.cs @@ -497,10 +497,10 @@ public void AddUserRole(int portalId, int userId, int roleId, RoleStatus status, /// public void ClearRoleCache(int portalId) { - DataCache.RemoveCache(string.Format(DataCache.RolesCacheKey, portalId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.RolesCacheKey, portalId)); if (portalId != Null.NullInteger) { - DataCache.RemoveCache(string.Format(DataCache.RolesCacheKey, Null.NullInteger)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.RolesCacheKey, Null.NullInteger)); } } @@ -573,7 +573,7 @@ public RoleInfo GetRoleByName(int portalId, string roleName) /// public IList GetRoles(int portalId) { - var cacheKey = string.Format(DataCache.RolesCacheKey, portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.RolesCacheKey, portalId); return CBO.GetCachedObject>( this.hostSettings, new CacheItemArgs(cacheKey, DataCache.RolesCacheTimeOut, DataCache.RolesCachePriority), diff --git a/DNN Platform/Library/Security/Roles/RoleInfo.cs b/DNN Platform/Library/Security/Roles/RoleInfo.cs index dd0d6d7212e..22fb44f481d 100644 --- a/DNN Platform/Library/Security/Roles/RoleInfo.cs +++ b/DNN Platform/Library/Security/Roles/RoleInfo.cs @@ -80,7 +80,7 @@ public string PhotoURL if (!string.IsNullOrEmpty(this.IconFile)) { IFileInfo fileInfo = - FileManager.Instance.GetFile(int.Parse(this.IconFile.Replace("FileID=", string.Empty))); + FileManager.Instance.GetFile(int.Parse(this.IconFile.Replace("FileID=", string.Empty), CultureInfo.InvariantCulture)); if (fileInfo != null) { photoURL = FileManager.Instance.GetUrl(fileInfo); @@ -282,9 +282,9 @@ public string GetProperty(string propertyName, string format, CultureInfo format switch (propName) { case "roleid": - return PropertyAccess.FormatString(this.RoleID.ToString(), format); + return PropertyAccess.FormatString(this.RoleID.ToString(formatProvider), format); case "groupid": - return PropertyAccess.FormatString(this.RoleID.ToString(), format); + return PropertyAccess.FormatString(this.RoleID.ToString(formatProvider), format); case "status": return PropertyAccess.FormatString(this.Status.ToString(), format); case "groupname": @@ -296,7 +296,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "description": return PropertyAccess.FormatString(this.Description, format); case "usercount": - return PropertyAccess.FormatString(this.UserCount.ToString(), format); + return PropertyAccess.FormatString(this.UserCount.ToString(formatProvider), format); case "street": return PropertyAccess.FormatString(this.GetString("Street", string.Empty), format); case "city": @@ -310,7 +310,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "website": return PropertyAccess.FormatString(this.GetString("Website", string.Empty), format); case "datecreated": - return PropertyAccess.FormatString(this.CreatedOnDate.ToString(), format); + return PropertyAccess.FormatString(this.CreatedOnDate.ToString(formatProvider), format); case "photourl": return PropertyAccess.FormatString(FormatUrl(this.PhotoURL), format); case "stat_status": @@ -564,7 +564,7 @@ public void WriteXml(XmlWriter writer) private static string FormatUrl(string url) { - if (url.StartsWith("/") && HttpContext.Current != null) + if (url.StartsWith("/", StringComparison.Ordinal) && HttpContext.Current != null) { // server absolute path return Globals.AddHTTP(HttpContext.Current.Request.Url.Host) + url; diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs index 0888fc08619..80441726248 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs @@ -1,166 +1,167 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Analytics.Config -{ - using System; - using System.Collections; - using System.IO; - using System.Xml.Serialization; - using System.Xml.XPath; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Instrumentation; - using DotNetNuke.Services.Cache; +namespace DotNetNuke.Services.Analytics.Config +{ + using System; + using System.Collections; + using System.Globalization; + using System.IO; + using System.Xml.Serialization; + using System.Xml.XPath; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Cache; using DotNetNuke.Services.Log.EventLog; [Serializable] - [XmlRoot("AnalyticsConfig")] - public class AnalyticsConfiguration - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AnalyticsConfiguration)); - private AnalyticsRuleCollection rules; - private AnalyticsSettingCollection settings; - - public AnalyticsSettingCollection Settings - { - get - { - return this.settings; - } - - set - { - this.settings = value; - } - } - - public AnalyticsRuleCollection Rules - { - get - { - return this.rules; - } - - set - { - this.rules = value; - } - } - - public static AnalyticsConfiguration GetConfig(string analyticsEngineName) - { - string cacheKey = analyticsEngineName + "." + PortalSettings.Current.PortalId; - - var config = new AnalyticsConfiguration(); - config.Rules = new AnalyticsRuleCollection(); - config.Settings = new AnalyticsSettingCollection(); - - FileStream fileReader = null; - string filePath = string.Empty; - try - { - config = (AnalyticsConfiguration)DataCache.GetCache(cacheKey); - if (config == null) - { - filePath = PortalSettings.Current.HomeDirectoryMapPath + "\\" + analyticsEngineName + ".config"; - - if (!File.Exists(filePath)) - { - return null; - } - - // Create a FileStream for the Config file - fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); - - var doc = new XPathDocument(fileReader); - config = new AnalyticsConfiguration(); - config.Rules = new AnalyticsRuleCollection(); - config.Settings = new AnalyticsSettingCollection(); - - var allSettings = new Hashtable(); - foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsConfig/Settings/AnalyticsSetting")) - { - var setting = new AnalyticsSetting(); - setting.SettingName = nav.SelectSingleNode("SettingName").Value; - setting.SettingValue = nav.SelectSingleNode("SettingValue")?.Value; - config.Settings.Add(setting); - } - - foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsConfig/Rules/AnalyticsRule")) - { - var rule = new AnalyticsRule(); - rule.RoleId = Convert.ToInt32(nav.SelectSingleNode("RoleId").Value); - rule.TabId = Convert.ToInt32(nav.SelectSingleNode("TabId").Value); - rule.Label = nav.SelectSingleNode("Label").Value; - var valueNode = nav.SelectSingleNode("Value"); - if (valueNode != null) - { - rule.Value = valueNode.Value; - } - - config.Rules.Add(rule); - } - - if (File.Exists(filePath)) - { - // Set back into Cache - DataCache.SetCache(cacheKey, config, new DNNCacheDependency(filePath)); - } - } - } - catch (Exception ex) - { - // log it - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString() }; - log.AddProperty("Analytics.AnalyticsConfiguration", "GetConfig Failed"); - log.AddProperty("FilePath", filePath); - log.AddProperty("ExceptionMessage", ex.Message); - LogController.Instance.AddLog(log); - Logger.Error(ex); - } - finally - { - if (fileReader != null) - { - // Close the Reader - fileReader.Close(); - } - } - - return config; - } - - public static void SaveConfig(string analyticsEngineName, AnalyticsConfiguration config) - { - string cacheKey = analyticsEngineName + "." + PortalSettings.Current.PortalId; - if (config.Settings != null) - { - // Create a new Xml Serializer - var ser = new XmlSerializer(typeof(AnalyticsConfiguration)); - string filePath = string.Empty; - - // Create a FileStream for the Config file - filePath = PortalSettings.Current.HomeDirectoryMapPath + "\\" + analyticsEngineName + ".config"; - if (File.Exists(filePath)) - { - File.SetAttributes(filePath, FileAttributes.Normal); - } - - using (var fileWriter = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write)) - using (var writer = new StreamWriter(fileWriter)) - { - // Serialize the AnalyticsConfiguration - ser.Serialize(writer, config); - - // Close the Writers - writer.Close(); - fileWriter.Close(); - } - - DataCache.SetCache(cacheKey, config, new DNNCacheDependency(filePath)); - } - } - } -} + [XmlRoot("AnalyticsConfig")] + public class AnalyticsConfiguration + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AnalyticsConfiguration)); + private AnalyticsRuleCollection rules; + private AnalyticsSettingCollection settings; + + public AnalyticsSettingCollection Settings + { + get + { + return this.settings; + } + + set + { + this.settings = value; + } + } + + public AnalyticsRuleCollection Rules + { + get + { + return this.rules; + } + + set + { + this.rules = value; + } + } + + public static AnalyticsConfiguration GetConfig(string analyticsEngineName) + { + string cacheKey = analyticsEngineName + "." + PortalSettings.Current.PortalId; + + var config = new AnalyticsConfiguration(); + config.Rules = new AnalyticsRuleCollection(); + config.Settings = new AnalyticsSettingCollection(); + + FileStream fileReader = null; + string filePath = string.Empty; + try + { + config = (AnalyticsConfiguration)DataCache.GetCache(cacheKey); + if (config == null) + { + filePath = PortalSettings.Current.HomeDirectoryMapPath + @"\" + analyticsEngineName + ".config"; + + if (!File.Exists(filePath)) + { + return null; + } + + // Create a FileStream for the Config file + fileReader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); + + var doc = new XPathDocument(fileReader); + config = new AnalyticsConfiguration(); + config.Rules = new AnalyticsRuleCollection(); + config.Settings = new AnalyticsSettingCollection(); + + var allSettings = new Hashtable(); + foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsConfig/Settings/AnalyticsSetting")) + { + var setting = new AnalyticsSetting(); + setting.SettingName = nav.SelectSingleNode("SettingName").Value; + setting.SettingValue = nav.SelectSingleNode("SettingValue")?.Value; + config.Settings.Add(setting); + } + + foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsConfig/Rules/AnalyticsRule")) + { + var rule = new AnalyticsRule(); + rule.RoleId = Convert.ToInt32(nav.SelectSingleNode("RoleId").Value, CultureInfo.InvariantCulture); + rule.TabId = Convert.ToInt32(nav.SelectSingleNode("TabId").Value, CultureInfo.InvariantCulture); + rule.Label = nav.SelectSingleNode("Label").Value; + var valueNode = nav.SelectSingleNode("Value"); + if (valueNode != null) + { + rule.Value = valueNode.Value; + } + + config.Rules.Add(rule); + } + + if (File.Exists(filePath)) + { + // Set back into Cache + DataCache.SetCache(cacheKey, config, new DNNCacheDependency(filePath)); + } + } + } + catch (Exception ex) + { + // log it + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString() }; + log.AddProperty("Analytics.AnalyticsConfiguration", "GetConfig Failed"); + log.AddProperty("FilePath", filePath); + log.AddProperty("ExceptionMessage", ex.Message); + LogController.Instance.AddLog(log); + Logger.Error(ex); + } + finally + { + if (fileReader != null) + { + // Close the Reader + fileReader.Close(); + } + } + + return config; + } + + public static void SaveConfig(string analyticsEngineName, AnalyticsConfiguration config) + { + string cacheKey = analyticsEngineName + "." + PortalSettings.Current.PortalId; + if (config.Settings != null) + { + // Create a new Xml Serializer + var ser = new XmlSerializer(typeof(AnalyticsConfiguration)); + string filePath = string.Empty; + + // Create a FileStream for the Config file + filePath = PortalSettings.Current.HomeDirectoryMapPath + @"\" + analyticsEngineName + ".config"; + if (File.Exists(filePath)) + { + File.SetAttributes(filePath, FileAttributes.Normal); + } + + using (var fileWriter = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write)) + using (var writer = new StreamWriter(fileWriter)) + { + // Serialize the AnalyticsConfiguration + ser.Serialize(writer, config); + + // Close the Writers + writer.Close(); + fileWriter.Close(); + } + + DataCache.SetCache(cacheKey, config, new DNNCacheDependency(filePath)); + } + } + } +} diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs index f5432022c48..0bc0702dff7 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs @@ -1,30 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Analytics.Config -{ - using System; - using System.Collections; +namespace DotNetNuke.Services.Analytics.Config; - [Serializable] - public class AnalyticsRuleCollection : CollectionBase - { - public virtual AnalyticsRule this[int index] - { - get - { - return (AnalyticsRule)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public void Add(AnalyticsRule r) - { - this.InnerList.Add(r); - } - } -} +using System; + +using DotNetNuke.Collections; + +[Serializable] +public class AnalyticsRuleCollection : GenericCollectionBase +{ + public new void Add(AnalyticsRule r) => base.Add(r); +} diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs index f9277e82b6a..79e42643bb4 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs @@ -1,30 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Analytics.Config -{ - using System; - using System.Collections; +namespace DotNetNuke.Services.Analytics.Config; - [Serializable] - public class AnalyticsSettingCollection : CollectionBase - { - public virtual AnalyticsSetting this[int index] - { - get - { - return (AnalyticsSetting)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public void Add(AnalyticsSetting r) - { - this.InnerList.Add(r); - } - } -} +using System; + +using DotNetNuke.Collections; + +[Serializable] +public class AnalyticsSettingCollection : GenericCollectionBase +{ + public new void Add(AnalyticsSetting r) => base.Add(r); +} diff --git a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs index 17110302455..c0ffca3ced7 100644 --- a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs +++ b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs @@ -1,143 +1,144 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Analytics -{ - using System; +namespace DotNetNuke.Services.Analytics +{ + using System; + using System.Globalization; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; using DotNetNuke.Services.Analytics.Config; - public class GoogleAnalyticsEngine : AnalyticsEngineBase + public class GoogleAnalyticsEngine : AnalyticsEngineBase { /// - public override string EngineName - { - get - { - return "GoogleAnalytics"; - } + public override string EngineName + { + get + { + return "GoogleAnalytics"; + } } /// - public override string RenderScript(string scriptTemplate) - { - AnalyticsConfiguration config = this.GetConfig(); - - if (config == null) - { - return string.Empty; - } - - var trackingId = string.Empty; - var urlParameter = string.Empty; - var trackForAdmin = true; - - foreach (AnalyticsSetting setting in config.Settings) - { - switch (setting.SettingName.ToLowerInvariant()) - { - case "trackingid": - trackingId = setting.SettingValue; - break; - case "urlparameter": - urlParameter = setting.SettingValue; - break; - case "trackforadmin": - if (!bool.TryParse(setting.SettingValue, out trackForAdmin)) - { - trackForAdmin = true; - } - - break; - } - } - - if (string.IsNullOrEmpty(trackingId)) - { - return string.Empty; - } - - // check whether setting to not track traffic if current user is host user or website administrator. - if (!trackForAdmin && - (UserController.Instance.GetCurrentUserInfo().IsSuperUser - || - (PortalSettings.Current != null && - UserController.Instance.GetCurrentUserInfo().IsInRole(PortalSettings.Current.AdministratorRoleName)))) - { - return string.Empty; - } - - scriptTemplate = scriptTemplate.Replace("[TRACKING_ID]", trackingId); - if (!string.IsNullOrEmpty(urlParameter)) - { - scriptTemplate = scriptTemplate.Replace("[PAGE_URL]", urlParameter); - } - else - { - scriptTemplate = scriptTemplate.Replace("[PAGE_URL]", string.Empty); - } - - scriptTemplate = scriptTemplate.Replace("[CUSTOM_SCRIPT]", this.RenderCustomScript(config)); - - return scriptTemplate; + public override string RenderScript(string scriptTemplate) + { + AnalyticsConfiguration config = this.GetConfig(); + + if (config == null) + { + return string.Empty; + } + + var trackingId = string.Empty; + var urlParameter = string.Empty; + var trackForAdmin = true; + + foreach (AnalyticsSetting setting in config.Settings) + { + switch (setting.SettingName.ToLowerInvariant()) + { + case "trackingid": + trackingId = setting.SettingValue; + break; + case "urlparameter": + urlParameter = setting.SettingValue; + break; + case "trackforadmin": + if (!bool.TryParse(setting.SettingValue, out trackForAdmin)) + { + trackForAdmin = true; + } + + break; + } + } + + if (string.IsNullOrEmpty(trackingId)) + { + return string.Empty; + } + + // check whether setting to not track traffic if current user is host user or website administrator. + if (!trackForAdmin && + (UserController.Instance.GetCurrentUserInfo().IsSuperUser + || + (PortalSettings.Current != null && + UserController.Instance.GetCurrentUserInfo().IsInRole(PortalSettings.Current.AdministratorRoleName)))) + { + return string.Empty; + } + + scriptTemplate = scriptTemplate.Replace("[TRACKING_ID]", trackingId); + if (!string.IsNullOrEmpty(urlParameter)) + { + scriptTemplate = scriptTemplate.Replace("[PAGE_URL]", urlParameter); + } + else + { + scriptTemplate = scriptTemplate.Replace("[PAGE_URL]", string.Empty); + } + + scriptTemplate = scriptTemplate.Replace("[CUSTOM_SCRIPT]", this.RenderCustomScript(config)); + + return scriptTemplate; } /// - public override string RenderCustomScript(AnalyticsConfiguration config) - { - try - { - var anonymize = false; - var trackingUserId = false; - - foreach (AnalyticsSetting setting in config.Settings) - { - switch (setting.SettingName.ToLowerInvariant()) - { - case "anonymizeip": - { - if (!bool.TryParse(setting.SettingValue, out anonymize)) - { - anonymize = false; - } - - break; - } - - case "trackinguser": - { - if (!bool.TryParse(setting.SettingValue, out trackingUserId)) - { - trackingUserId = false; - } - - break; - } - } - } - - var customScripts = new System.Text.StringBuilder(); - - if (anonymize || PortalSettings.Current.DataConsentActive) - { - customScripts.Append("ga('set', 'anonymizeIp', true);"); - } - - if (trackingUserId) - { - customScripts.AppendFormat("ga('set', 'userId', {0});", UserController.Instance.GetCurrentUserInfo().UserID); - } - - return customScripts.ToString(); - } - catch (Exception ex) - { - Exceptions.Exceptions.LogException(ex); - - return string.Empty; - } - } - } -} + public override string RenderCustomScript(AnalyticsConfiguration config) + { + try + { + var anonymize = false; + var trackingUserId = false; + + foreach (AnalyticsSetting setting in config.Settings) + { + switch (setting.SettingName.ToLowerInvariant()) + { + case "anonymizeip": + { + if (!bool.TryParse(setting.SettingValue, out anonymize)) + { + anonymize = false; + } + + break; + } + + case "trackinguser": + { + if (!bool.TryParse(setting.SettingValue, out trackingUserId)) + { + trackingUserId = false; + } + + break; + } + } + } + + var customScripts = new System.Text.StringBuilder(); + + if (anonymize || PortalSettings.Current.DataConsentActive) + { + customScripts.Append("ga('set', 'anonymizeIp', true);"); + } + + if (trackingUserId) + { + customScripts.AppendFormat(CultureInfo.InvariantCulture, "ga('set', 'userId', {0});", UserController.Instance.GetCurrentUserInfo().UserID); + } + + return customScripts.ToString(); + } + catch (Exception ex) + { + Exceptions.Exceptions.LogException(ex); + + return string.Empty; + } + } + } +} diff --git a/DNN Platform/Library/Services/Assets/AssetManager.cs b/DNN Platform/Library/Services/Assets/AssetManager.cs index ea7ee1c44b9..dd570007a1e 100644 --- a/DNN Platform/Library/Services/Assets/AssetManager.cs +++ b/DNN Platform/Library/Services/Assets/AssetManager.cs @@ -280,7 +280,7 @@ public IFolderInfo CreateFolder(string folderName, int folderParentId, int folde var folderPath = PathUtils.Instance.FormatFolderPath( PathUtils.Instance.FormatFolderPath( - PathUtils.Instance.StripFolderPath(parentFolder.FolderPath).Replace("\\", "/")) + filterFolderName); + PathUtils.Instance.StripFolderPath(parentFolder.FolderPath).Replace(@"\", "/")) + filterFolderName); mappedPath = PathUtils.Instance.FormatFolderPath(mappedPath); @@ -292,7 +292,7 @@ public IFolderInfo CreateFolder(string folderName, int folderParentId, int folde try { var folderMapping = FolderMappingController.Instance.GetFolderMapping(parentFolder.PortalID, folderMappingId); - return FolderManager.Instance.AddFolder(folderMapping, folderPath, mappedPath.Replace("\\", "/")); + return FolderManager.Instance.AddFolder(folderMapping, folderPath, mappedPath.Replace(@"\", "/")); } catch (FolderAlreadyExistsException) { diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs index d196ebcb256..39ad87ec4cf 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs @@ -26,6 +26,7 @@ protected AuthenticationLoginBase() this.Mode = AuthMode.Login; } + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public delegate void UserAuthenticatedEventHandler(object sender, UserAuthenticatedEventArgs e); public event UserAuthenticatedEventHandler UserAuthenticated; diff --git a/DNN Platform/Library/Services/Authentication/OAuth/AuthExtensions.cs b/DNN Platform/Library/Services/Authentication/OAuth/AuthExtensions.cs index eaa075731c5..ea2a087e6c6 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/AuthExtensions.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/AuthExtensions.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Authentication.OAuth { using System.Collections.Generic; + using System.Globalization; using System.Text; internal static class AuthExtensions @@ -14,12 +15,12 @@ public static string ToAuthorizationString(this IList parameters var sb = new StringBuilder(); sb.Append("OAuth "); - for (int i = 0; i < parameters.Count; i++) + for (var i = 0; i < parameters.Count; i++) { - string format = "{0}=\"{1}\""; + const string format = "{0}=\"{1}\""; - QueryParameter p = parameters[i]; - sb.AppendFormat(format, OAuthClientBase.UrlEncode(p.Name), OAuthClientBase.UrlEncode(p.Value)); + var p = parameters[i]; + sb.AppendFormat(CultureInfo.InvariantCulture, format, OAuthClientBase.UrlEncode(p.Name), OAuthClientBase.UrlEncode(p.Value)); if (i < parameters.Count - 1) { @@ -33,10 +34,10 @@ public static string ToAuthorizationString(this IList parameters public static string ToNormalizedString(this IList parameters) { var sb = new StringBuilder(); - for (int i = 0; i < parameters.Count; i++) + for (var i = 0; i < parameters.Count; i++) { - QueryParameter p = parameters[i]; - sb.AppendFormat("{0}={1}", p.Name, p.Value); + var p = parameters[i]; + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", p.Name, p.Value); if (i < parameters.Count - 1) { diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs index 07f5802c542..fdb1ccf8b6b 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs @@ -161,7 +161,7 @@ public static string UrlEncode(string value) } else { - result.Append('%' + string.Format("{0:X2}", (int)symbol)); + result.Append('%' + string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol)); } } @@ -426,7 +426,7 @@ private static string GenerateSignatureUsingHash(string signatureBase, HashAlgor private static List GetQueryParameters(string parameters) { - if (parameters.StartsWith("?")) + if (parameters.StartsWith("?", StringComparison.Ordinal)) { parameters = parameters.Remove(0, 1); } @@ -438,7 +438,7 @@ private static List GetQueryParameters(string parameters) string[] p = parameters.Split('&'); foreach (string s in p) { - if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix)) + if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix, StringComparison.OrdinalIgnoreCase)) { if (s.IndexOf('=') > -1) { @@ -698,15 +698,11 @@ private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, } catch (WebException ex) { - using (Stream responseStream = ex.Response.GetResponseStream()) + using var responseStream = ex.Response.GetResponseStream(); + if (responseStream != null) { - if (responseStream != null) - { - using (var responseReader = new StreamReader(responseStream)) - { - Logger.ErrorFormat("WebResponse exception: {0}", responseReader.ReadToEnd()); - } - } + using var responseReader = new StreamReader(responseStream); + Logger.ErrorFormat(CultureInfo.InvariantCulture, "WebResponse exception: {0}", responseReader.ReadToEnd()); } } @@ -759,9 +755,9 @@ private string GenerateSignatureBase(Uri url, string token, string callbackUrl, string normalizedRequestParameters = requestParameters.ToNormalizedString(); var signatureBase = new StringBuilder(); - signatureBase.AppendFormat("{0}&", httpMethod.ToUpperInvariant()); - signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl)); - signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters)); + signatureBase.AppendFormat(CultureInfo.InvariantCulture, "{0}&", httpMethod.ToUpperInvariant()); + signatureBase.AppendFormat(CultureInfo.InvariantCulture, "{0}&", UrlEncode(normalizedUrl)); + signatureBase.AppendFormat(CultureInfo.InvariantCulture, "{0}", UrlEncode(normalizedRequestParameters)); return signatureBase.ToString(); } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs index 52b7b50c04e..f37311a6c09 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs @@ -13,6 +13,7 @@ public class OAuthSettingsBase : AuthenticationSettingsBase { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected PropertyEditorControl SettingsEditor; diff --git a/DNN Platform/Library/Services/Cache/CachingProvider.cs b/DNN Platform/Library/Services/Cache/CachingProvider.cs index 9ac00faa54f..34000c76f6c 100644 --- a/DNN Platform/Library/Services/Cache/CachingProvider.cs +++ b/DNN Platform/Library/Services/Cache/CachingProvider.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Services.Cache using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Web; using System.Web.Caching; @@ -234,22 +235,22 @@ protected void ClearCacheInternal(string cacheType, string data, bool clearRunti this.ClearHostCacheInternal(clearRuntime); break; case "Folder": - this.ClearFolderCacheInternal(int.Parse(data), clearRuntime); + this.ClearFolderCacheInternal(int.Parse(data, CultureInfo.InvariantCulture), clearRuntime); break; case "Module": - this.ClearModuleCacheInternal(int.Parse(data), clearRuntime); + this.ClearModuleCacheInternal(int.Parse(data, CultureInfo.InvariantCulture), clearRuntime); break; case "ModulePermissionsByPortal": - this.ClearModulePermissionsCachesByPortalInternal(int.Parse(data), clearRuntime); + this.ClearModulePermissionsCachesByPortalInternal(int.Parse(data, CultureInfo.InvariantCulture), clearRuntime); break; case "Portal": - this.ClearPortalCacheInternal(int.Parse(data), false, clearRuntime); + this.ClearPortalCacheInternal(int.Parse(data, CultureInfo.InvariantCulture), false, clearRuntime); break; case "PortalCascade": - this.ClearPortalCacheInternal(int.Parse(data), true, clearRuntime); + this.ClearPortalCacheInternal(int.Parse(data, CultureInfo.InvariantCulture), true, clearRuntime); break; case "Tab": - this.ClearTabCacheInternal(int.Parse(data), clearRuntime); + this.ClearTabCacheInternal(int.Parse(data, CultureInfo.InvariantCulture), clearRuntime); break; case "ServiceFrameworkRoutes": ReloadServicesFrameworkRoutes(); @@ -284,17 +285,17 @@ private void ClearCacheInternal(string prefix, bool clearRuntime) { foreach (DictionaryEntry objDictionaryEntry in HttpRuntime.Cache) { - if (Convert.ToString(objDictionaryEntry.Key).StartsWith(prefix)) + if (Convert.ToString(objDictionaryEntry.Key, CultureInfo.InvariantCulture).StartsWith(prefix, StringComparison.Ordinal)) { if (clearRuntime) { // remove item from runtime cache - this.RemoveInternal(Convert.ToString(objDictionaryEntry.Key)); + this.RemoveInternal(Convert.ToString(objDictionaryEntry.Key, CultureInfo.InvariantCulture)); } else { // Call provider's remove method - this.Remove(Convert.ToString(objDictionaryEntry.Key)); + this.Remove(Convert.ToString(objDictionaryEntry.Key, CultureInfo.InvariantCulture)); } } } @@ -325,9 +326,9 @@ private void ClearFolderCacheInternal(int portalId, bool clearRuntime) { this.RemoveFormattedCacheKey(DataCache.FolderCacheKey, clearRuntime, portalId); - // FolderUserCacheKey also includes permissions and userId but we don't have that information + // FolderUserCacheKey also includes permissions and userId, but we don't have that information // here so we remove them using a prefix - var folderUserCachePrefix = GetCacheKey(string.Format("Folders|{0}|", portalId)); + var folderUserCachePrefix = GetCacheKey(string.Format(CultureInfo.InvariantCulture, "Folders|{0}|", portalId)); this.ClearCacheInternal(folderUserCachePrefix, clearRuntime); PermissionProvider.ResetCacheDependency( @@ -361,13 +362,13 @@ private void ClearHostCacheInternal(bool clearRuntime) private void ClearModuleCacheInternal(int tabId, bool clearRuntime) { - var cacheKey = string.Format(DataCache.TabModuleCacheKey, tabId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.TabModuleCacheKey, tabId); var tabModules = Cache.Get(cacheKey) as Dictionary; if (tabModules != null && tabModules.Count != 0) { foreach (var moduleInfo in tabModules.Values) { - cacheKey = string.Format(DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID); + cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID); if (clearRuntime) { this.RemoveInternal(cacheKey); @@ -402,19 +403,19 @@ private void ClearPortalCacheInternal(int portalId, bool cascade, bool clearRunt { // At least attempt to remove default locale string defaultLocale = PortalController.GetPortalDefaultLanguage(this.hostSettings, portalId); - this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, defaultLocale), clearRuntime); - this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.PortalCacheKey, portalId, defaultLocale), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, defaultLocale); } else { foreach (Locale portalLocale in LocaleController.Instance.GetLocales(portalId).Values) { - this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, portalLocale.Code), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.PortalCacheKey, portalId, portalLocale.Code), clearRuntime); this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, portalLocale.Code); } - this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, Null.NullString); } @@ -437,8 +438,8 @@ private void ClearPortalCacheInternal(int portalId, bool cascade, bool clearRunt this.ClearDesktopModuleCacheInternal(portalId, clearRuntime); this.ClearTabCacheInternal(portalId, clearRuntime); - this.RemoveCacheKey(string.Format(DataCache.RolesCacheKey, portalId), clearRuntime); - this.RemoveCacheKey(string.Format(DataCache.JournalTypesCacheKey, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.RolesCacheKey, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.JournalTypesCacheKey, portalId), clearRuntime); } private void ClearTabCacheInternal(int portalId, bool clearRuntime) @@ -453,18 +454,18 @@ private void ClearTabCacheInternal(int portalId, bool clearRuntime) { // At least attempt to remove default locale string defaultLocale = PortalController.GetPortalDefaultLanguage(this.hostSettings, portalId); - this.RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, defaultLocale, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.TabPathCacheKey, defaultLocale, portalId), clearRuntime); } else { foreach (Locale portalLocale in LocaleController.Instance.GetLocales(portalId).Values) { - this.RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, portalLocale.Code, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.TabPathCacheKey, portalLocale.Code, portalId), clearRuntime); } } - this.RemoveCacheKey(string.Format(DataCache.TabPathCacheKey, Null.NullString, portalId), clearRuntime); - this.RemoveCacheKey(string.Format(DataCache.TabSettingsCacheKey, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.TabPathCacheKey, Null.NullString, portalId), clearRuntime); + this.RemoveCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.TabSettingsCacheKey, portalId), clearRuntime); } private void RemoveCacheKey(string cacheKey, bool clearRuntime) @@ -486,12 +487,12 @@ private void RemoveFormattedCacheKey(string cacheKeyBase, bool clearRuntime, par if (clearRuntime) { // remove item from runtime cache - this.RemoveInternal(string.Format(GetCacheKey(cacheKeyBase), parameters)); + this.RemoveInternal(string.Format(CultureInfo.InvariantCulture, GetCacheKey(cacheKeyBase), parameters)); } else { // Call provider's remove method - this.Remove(string.Format(GetCacheKey(cacheKeyBase), parameters)); + this.Remove(string.Format(CultureInfo.InvariantCulture, GetCacheKey(cacheKeyBase), parameters)); } } } diff --git a/DNN Platform/Library/Services/Cache/FBCachingProvider.cs b/DNN Platform/Library/Services/Cache/FBCachingProvider.cs index d7f109ef3ab..24968c51ea6 100644 --- a/DNN Platform/Library/Services/Cache/FBCachingProvider.cs +++ b/DNN Platform/Library/Services/Cache/FBCachingProvider.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Cache { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; @@ -81,6 +82,7 @@ public override string PurgeCache() } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override void Remove(string key) { base.Remove(key); @@ -102,7 +104,7 @@ private static string ByteArrayToString(byte[] arrInput) var sOutput = new StringBuilder(arrInput.Length); for (i = 0; i <= arrInput.Length - 1; i++) { - sOutput.Append(arrInput[i].ToString("X2")); + sOutput.Append(arrInput[i].ToString("X2", CultureInfo.InvariantCulture)); } return sOutput.ToString(); @@ -213,7 +215,7 @@ private static string PurgeCacheFiles(string folder) } // return a summary message for the job - return string.Format("Cache Synchronization Files Processed: " + f.Length + ", Purged: " + purgedFiles + ", Errors: " + purgeErrors); + return $"Cache Synchronization Files Processed: {f.Length}, Purged: {purgedFiles}, Errors: {purgeErrors}"; } } } diff --git a/DNN Platform/Library/Services/Cache/PurgeCache.cs b/DNN Platform/Library/Services/Cache/PurgeCache.cs index e69f0b5e077..c4a5a0a5fc3 100644 --- a/DNN Platform/Library/Services/Cache/PurgeCache.cs +++ b/DNN Platform/Library/Services/Cache/PurgeCache.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Cache { using System; + using System.Globalization; using DotNetNuke.Services.Scheduling; @@ -30,7 +31,7 @@ public override void DoWork() { this.ScheduleHistoryItem.Succeeded = false; // REQUIRED - this.ScheduleHistoryItem.AddLogNote(string.Format("Purging cache task failed: {0}.", exc.ToString())); + this.ScheduleHistoryItem.AddLogNote(string.Format(CultureInfo.InvariantCulture, "Purging cache task failed: {0}.", exc.ToString())); // notification that we have errored this.Errored(ref exc); // REQUIRED diff --git a/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs b/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs index e6395f13d87..66030b61a56 100644 --- a/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs +++ b/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.ClientCapability { using System; + using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; using System.Text; using System.Web; @@ -15,8 +16,10 @@ public class FacebookRequestController { private const string SignedRequestParameter = "signed_request"; + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] public static string API_SECRET { get; set; } + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] public static string APP_ID { get; set; } public string AccessToken { get; set; } diff --git a/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs b/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs index df3a1f48b05..e724a568cb5 100644 --- a/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs +++ b/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs @@ -22,7 +22,7 @@ public override void DoWork() { try { - string[] filePaths = Directory.GetFiles(string.Format("{0}/App_Data/ClientDependency", Common.Globals.ApplicationMapPath)); + string[] filePaths = Directory.GetFiles($"{Common.Globals.ApplicationMapPath}/App_Data/ClientDependency"); foreach (string filePath in filePaths) { File.Delete(filePath); @@ -35,7 +35,7 @@ public override void DoWork() { this.ScheduleHistoryItem.Succeeded = false; // REQUIRED - this.ScheduleHistoryItem.AddLogNote(string.Format("Purging client dependency files task failed: {0}.", exc.ToString())); + this.ScheduleHistoryItem.AddLogNote($"Purging client dependency files task failed: {exc.ToString()}."); // notification that we have errored this.Errored(ref exc); // REQUIRED diff --git a/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs b/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs index 49324593f1e..581dd984982 100644 --- a/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs +++ b/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs @@ -9,6 +9,7 @@ namespace DotNetNuke.Services.Connections using System.Collections.Generic; using System.Collections.ObjectModel; using System.Dynamic; + using System.Globalization; using System.Linq; using System.Text; using System.Web; @@ -120,7 +121,11 @@ private void ToString(StringBuilder sb) var name = pair.Key; if (value is string stringValue) { - sb.AppendFormat("{0}:{1}", HttpUtility.JavaScriptStringEncode(name, addDoubleQuotes: true), HttpUtility.JavaScriptStringEncode(stringValue, addDoubleQuotes: true)); + sb.AppendFormat( + CultureInfo.InvariantCulture, + "{0}:{1}", + HttpUtility.JavaScriptStringEncode(name, addDoubleQuotes: true), + HttpUtility.JavaScriptStringEncode(stringValue, addDoubleQuotes: true)); } else if (value is IDictionary dictValue) { @@ -157,7 +162,7 @@ private void ToString(StringBuilder sb) } else { - sb.AppendFormat("{0}:{1}", name, value); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}:{1}", name, value); } } diff --git a/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs b/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs index 4f707de7163..91e4c79f081 100644 --- a/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs +++ b/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs @@ -1,28 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.EventQueue -{ - using System.Collections; +namespace DotNetNuke.Services.EventQueue; - public class EventMessageCollection : CollectionBase - { - public virtual EventMessage this[int index] - { - get - { - return (EventMessage)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - public void Add(EventMessage message) - { - this.InnerList.Add(message); - } - } -} +using DotNetNuke.Collections; + +public class EventMessageCollection : GenericCollectionBase +{ + public new void Add(EventMessage message) => base.Add(message); +} diff --git a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs index a8b0fdfb937..2033275c765 100644 --- a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs +++ b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.EventQueue { using System; using System.Data; + using System.Globalization; using DotNetNuke.Abstractions.Logging; using DotNetNuke.Common.Utilities; @@ -230,21 +231,21 @@ private static EventMessage FillMessage(IDataReader dr, bool checkForOpenDataRea if (canContinue) { message = new EventMessage(); - message.EventMessageID = Convert.ToInt32(Null.SetNull(dr["EventMessageID"], message.EventMessageID)); - message.Priority = (MessagePriority)Enum.Parse(typeof(MessagePriority), Convert.ToString(Null.SetNull(dr["Priority"], message.Priority))); - message.ProcessorType = Convert.ToString(Null.SetNull(dr["ProcessorType"], message.ProcessorType)); - message.ProcessorCommand = Convert.ToString(Null.SetNull(dr["ProcessorCommand"], message.ProcessorCommand)); - message.Body = Convert.ToString(Null.SetNull(dr["Body"], message.Body)); - message.Sender = Convert.ToString(Null.SetNull(dr["Sender"], message.Sender)); - message.Subscribers = Convert.ToString(Null.SetNull(dr["Subscriber"], message.Subscribers)); - message.AuthorizedRoles = Convert.ToString(Null.SetNull(dr["AuthorizedRoles"], message.AuthorizedRoles)); - message.ExceptionMessage = Convert.ToString(Null.SetNull(dr["ExceptionMessage"], message.ExceptionMessage)); - message.SentDate = Convert.ToDateTime(Null.SetNull(dr["SentDate"], message.SentDate)); - message.ExpirationDate = Convert.ToDateTime(Null.SetNull(dr["ExpirationDate"], message.ExpirationDate)); + message.EventMessageID = Convert.ToInt32(Null.SetNull(dr["EventMessageID"], message.EventMessageID), CultureInfo.InvariantCulture); + message.Priority = (MessagePriority)Enum.Parse(typeof(MessagePriority), Convert.ToString(Null.SetNull(dr["Priority"], message.Priority), CultureInfo.InvariantCulture)); + message.ProcessorType = Convert.ToString(Null.SetNull(dr["ProcessorType"], message.ProcessorType), CultureInfo.InvariantCulture); + message.ProcessorCommand = Convert.ToString(Null.SetNull(dr["ProcessorCommand"], message.ProcessorCommand), CultureInfo.InvariantCulture); + message.Body = Convert.ToString(Null.SetNull(dr["Body"], message.Body), CultureInfo.InvariantCulture); + message.Sender = Convert.ToString(Null.SetNull(dr["Sender"], message.Sender), CultureInfo.InvariantCulture); + message.Subscribers = Convert.ToString(Null.SetNull(dr["Subscriber"], message.Subscribers), CultureInfo.InvariantCulture); + message.AuthorizedRoles = Convert.ToString(Null.SetNull(dr["AuthorizedRoles"], message.AuthorizedRoles), CultureInfo.InvariantCulture); + message.ExceptionMessage = Convert.ToString(Null.SetNull(dr["ExceptionMessage"], message.ExceptionMessage), CultureInfo.InvariantCulture); + message.SentDate = Convert.ToDateTime(Null.SetNull(dr["SentDate"], message.SentDate), CultureInfo.InvariantCulture); + message.ExpirationDate = Convert.ToDateTime(Null.SetNull(dr["ExpirationDate"], message.ExpirationDate), CultureInfo.InvariantCulture); // Deserialize Attributes string xmlAttributes = Null.NullString; - xmlAttributes = Convert.ToString(Null.SetNull(dr["Attributes"], xmlAttributes)); + xmlAttributes = Convert.ToString(Null.SetNull(dr["Attributes"], xmlAttributes), CultureInfo.InvariantCulture); message.DeserializeAttributes(xmlAttributes); } else diff --git a/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs b/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs index 06f31836831..3d060014b0f 100644 --- a/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs +++ b/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Exceptions { using System; + using System.Globalization; using System.IO; using System.Net; using System.Text; @@ -207,9 +208,9 @@ public void WriteXml(XmlWriter writer) { writer.WriteStartElement("Exception"); writer.WriteElementString("AssemblyVersion", this.AssemblyVersion); - writer.WriteElementString("PortalId", this.PortalId.ToString()); - writer.WriteElementString("UserId", this.UserId.ToString()); - writer.WriteElementString("TabId", this.TabId.ToString()); + writer.WriteElementString("PortalId", this.PortalId.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("UserId", this.UserId.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("TabId", this.TabId.ToString(CultureInfo.InvariantCulture)); writer.WriteElementString("RawUrl", this.RawUrl); writer.WriteElementString("Referrer", this.Referrer); writer.WriteElementString("UserAgent", this.UserAgent); @@ -220,8 +221,8 @@ public void WriteXml(XmlWriter writer) writer.WriteElementString("InnerStackTrace", this.InnerStackTrace); writer.WriteElementString("Source", this.Source); writer.WriteElementString("FileName", this.FileName); - writer.WriteElementString("FileLineNumber", this.FileLineNumber.ToString()); - writer.WriteElementString("FileColumnNumber", this.FileColumnNumber.ToString()); + writer.WriteElementString("FileLineNumber", this.FileLineNumber.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("FileColumnNumber", this.FileColumnNumber.ToString(CultureInfo.InvariantCulture)); writer.WriteElementString("Method", this.Method); writer.WriteEndElement(); } diff --git a/DNN Platform/Library/Services/Exceptions/Exceptions.cs b/DNN Platform/Library/Services/Exceptions/Exceptions.cs index ceda3099b3f..f5d0c80a3c1 100644 --- a/DNN Platform/Library/Services/Exceptions/Exceptions.cs +++ b/DNN Platform/Library/Services/Exceptions/Exceptions.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Exceptions { using System; using System.Diagnostics; + using System.Globalization; using System.Reflection; using System.Threading; using System.Web; @@ -192,7 +193,7 @@ public static void ProcessModuleLoadException(Control ctrl, Exception exc, bool moduleTitle = ctrlModule.ModuleContext.Configuration.ModuleTitle; } - friendlyMessage = string.Format(Localization.GetString("ModuleUnavailable"), moduleTitle); + friendlyMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString("ModuleUnavailable"), moduleTitle); } ProcessModuleLoadException(friendlyMessage, ctrl, exc, displayErrorMessage); @@ -289,7 +290,7 @@ public static void ProcessModuleLoadException(string friendlyMessage, Control ct ProcessPageLoadException(exc2); } - Logger.ErrorFormat("FriendlyMessage=\"{0}\" ctrl=\"{1}\" exc=\"{2}\"", friendlyMessage, ctrl, exc); + Logger.ErrorFormat(CultureInfo.InvariantCulture, "FriendlyMessage=\"{0}\" ctrl=\"{1}\" exc=\"{2}\"", friendlyMessage, ctrl, exc); } /// Processes the page load exception. @@ -298,7 +299,7 @@ public static void ProcessPageLoadException(Exception exc) { PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); string appURL = Globals.ApplicationURL(); - if (appURL.IndexOf("?") == Null.NullInteger) + if (appURL.IndexOf("?", StringComparison.Ordinal) == Null.NullInteger) { appURL += "?def=ErrorMessage"; } @@ -336,7 +337,7 @@ public static void ProcessPageLoadException(Exception exc, string url) if (!string.IsNullOrEmpty(url)) { // redirect - if (url.IndexOf("error=terminate") != -1) + if (url.Contains("error=terminate", StringComparison.OrdinalIgnoreCase)) { HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer("~/ErrorPage.aspx"); diff --git a/DNN Platform/Library/Services/FileSystem/FileInfo.cs b/DNN Platform/Library/Services/FileSystem/FileInfo.cs index 8a7468ca9e5..f5b831f8722 100644 --- a/DNN Platform/Library/Services/FileSystem/FileInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FileInfo.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.FileSystem using System; using System.Data; using System.Drawing; + using System.Globalization; using System.IO; using System.Web; using System.Xml.Serialization; @@ -168,7 +169,7 @@ public string PhysicalPath if (!string.IsNullOrEmpty(physicalPath)) { - physicalPath = physicalPath.Replace("/", "\\"); + physicalPath = physicalPath.Replace("/", @"\"); } return physicalPath; @@ -274,7 +275,7 @@ public string Folder set { // Make sure folder name ends with / - if (!string.IsNullOrEmpty(value) && !value.EndsWith("/")) + if (!string.IsNullOrEmpty(value) && !value.EndsWith("/", StringComparison.Ordinal)) { value = value + "/"; } @@ -481,7 +482,7 @@ public void Fill(IDataReader dr) this.EndDate = Null.SetNullDateTime(dr["EndDate"]); this.ContentItemID = Null.SetNullInteger(dr["ContentItemID"]); this.PublishedVersion = Null.SetNullInteger(dr["PublishedVersion"]); - this.HasBeenPublished = Convert.ToBoolean(dr["HasBeenPublished"]); + this.HasBeenPublished = Convert.ToBoolean(dr["HasBeenPublished"], CultureInfo.InvariantCulture); this.FillBaseProperties(dr); } diff --git a/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs b/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs index 6c3b14fe9d8..1963418461c 100644 --- a/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs +++ b/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.FileSystem { using System; using System.Collections.Specialized; + using System.Globalization; using DotNetNuke.Common; using DotNetNuke.Common.Internal; @@ -20,9 +21,9 @@ public string GetFileLinkClick(IFileInfo file) { Requires.NotNull("file", file); var portalId = file.PortalId; - var linkClickPortalSettigns = GetPortalSettingsForLinkClick(portalId); + var linkClickPortalSettings = GetPortalSettingsForLinkClick(portalId); - return TestableGlobals.Instance.LinkClick(string.Format("fileid={0}", file.FileId), Null.NullInteger, Null.NullInteger, true, false, portalId, linkClickPortalSettigns.EnableUrlLanguage, linkClickPortalSettigns.PortalGUID); + return TestableGlobals.Instance.LinkClick(string.Format(CultureInfo.InvariantCulture, "fileid={0}", file.FileId), Null.NullInteger, Null.NullInteger, true, false, portalId, linkClickPortalSettings.EnableUrlLanguage, linkClickPortalSettings.PortalGUID); } /// @@ -30,8 +31,7 @@ public int GetFileIdFromLinkClick(NameValueCollection queryParams) { var linkClickPortalSettings = GetPortalSettingsForLinkClick(GetPortalIdFromLinkClick(queryParams)); var strFileId = UrlUtils.DecryptParameter(queryParams["fileticket"], linkClickPortalSettings.PortalGUID); - int fileId; - return int.TryParse(strFileId, out fileId) ? fileId : -1; + return int.TryParse(strFileId, out var fileId) ? fileId : -1; } /// diff --git a/DNN Platform/Library/Services/FileSystem/FileManager.cs b/DNN Platform/Library/Services/FileSystem/FileManager.cs index 595423170fd..73f56ccd80a 100644 --- a/DNN Platform/Library/Services/FileSystem/FileManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FileManager.cs @@ -521,7 +521,7 @@ public virtual IFileInfo GetFile(int fileID) /// The IFileInfo object with the metadata of the specified file. public virtual IFileInfo GetFile(int fileID, bool retrieveUnpublishedFiles) { - if (fileID == 0 || fileID == -1) + if (fileID is 0 or -1) { return null; } @@ -533,7 +533,7 @@ public virtual IFileInfo GetFile(int fileID, bool retrieveUnpublishedFiles) file = CBO.Instance.FillObject(DataProvider.Instance().GetFileById(fileID, retrieveUnpublishedFiles)); if (file != null) { - var intCacheTimeout = 20 * Convert.ToInt32(this.GetPerformanceSetting()); + var intCacheTimeout = 20 * (int)this.GetPerformanceSetting(); DataCache.SetCache(strCacheKey, file, TimeSpan.FromMinutes(intCacheTimeout)); } } @@ -695,7 +695,7 @@ public string GetUrl(IFileInfo file) /// The flag as a boolean value. public virtual bool IsImageFile(IFileInfo file) { - return (Globals.glbImageFileTypes + ",").IndexOf(file.Extension.ToLowerInvariant().Replace(".", string.Empty) + ",") > -1; + return (Globals.ImageFileTypes + ",").Contains(file.Extension.Replace(".", string.Empty) + ",", StringComparison.OrdinalIgnoreCase); } /// Moves the specified file into the specified folder. @@ -799,12 +799,12 @@ public virtual IFileInfo RenameFile(IFileInfo file, string newFileName) if (!this.IsAllowedExtension(newFileName)) { - throw new InvalidFileExtensionException(string.Format(Localization.GetExceptionMessage("AddFileExtensionNotAllowed", "The extension '{0}' is not allowed. The file has not been added."), Path.GetExtension(newFileName))); + throw new InvalidFileExtensionException(string.Format(CultureInfo.CurrentCulture, Localization.GetExceptionMessage("AddFileExtensionNotAllowed", "The extension '{0}' is not allowed. The file has not been added."), Path.GetExtension(newFileName))); } if (!this.IsValidFilename(newFileName)) { - throw new InvalidFilenameException(string.Format(Localization.GetExceptionMessage("AddFilenameNotAllowed", "The file name '{0}' is not allowed. The file has not been added."), newFileName)); + throw new InvalidFilenameException(string.Format(CultureInfo.CurrentCulture, Localization.GetExceptionMessage("AddFilenameNotAllowed", "The file name '{0}' is not allowed. The file has not been added."), newFileName)); } var folder = FolderManager.Instance.GetFolder(file.FolderId); @@ -1225,7 +1225,7 @@ internal void EnsureZipFolder(string fileName, IFolderInfo destinationFolder) var folderPath = PathUtils.Instance.RemoveTrailingSlash(zipFolder); - if (folderPath.IndexOf("/") == -1) + if (!folderPath.Contains("/", StringComparison.Ordinal)) { var newFolderPath = destinationFolder.FolderPath + PathUtils.Instance.FormatFolderPath(folderPath); if (!folderManager.FolderExists(destinationFolder.PortalID, newFolderPath)) @@ -1279,7 +1279,7 @@ internal virtual string GetHash(Stream stream) var hashData = hasher.ComputeHash(stream); foreach (var b in hashData) { - hashText.Append(b.ToString("x2")); + hashText.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } } @@ -1592,7 +1592,7 @@ private static bool ValidMetadata(IFileInfo file, out string exceptionMessage) private static RotateFlipType OrientationToFlipType(string orientation) { - switch (int.Parse(orientation)) + switch (int.Parse(orientation, CultureInfo.InvariantCulture)) { case 1: return RotateFlipType.RotateNoneFlipNone; @@ -1839,7 +1839,7 @@ private void RotateFlipImage(ref Stream content) return; } - var flip = OrientationToFlipType(orientation.Value[0].ToString()); + var flip = OrientationToFlipType(orientation.Value[0].ToString(CultureInfo.InvariantCulture)); if (flip == RotateFlipType.RotateNoneFlipNone) { return; // No rotation or flip required @@ -1872,6 +1872,7 @@ private void CheckFileAddingRestrictions(IFolderInfo folder, string fileName, bo { throw new InvalidFileExtensionException( string.Format( + CultureInfo.CurrentCulture, Localization.GetExceptionMessage( "AddFileExtensionNotAllowed", "The extension '{0}' is not allowed. The file has not been added."), @@ -1882,6 +1883,7 @@ private void CheckFileAddingRestrictions(IFolderInfo folder, string fileName, bo { throw new InvalidFilenameException( string.Format( + CultureInfo.CurrentCulture, Localization.GetExceptionMessage( "AddFilenameNotAllowed", "The file name '{0}' is not allowed. The file has not been added."), @@ -1956,31 +1958,31 @@ private void CheckFileWritingRestrictions(IFolderInfo folder, string fileName, S { var defaultMessage = "The content of '{0}' is not valid. The file has not been added."; var errorMessage = Localization.GetExceptionMessage("AddFileInvalidContent", defaultMessage); - throw new InvalidFileContentException(string.Format(errorMessage, fileName)); + throw new InvalidFileContentException(string.Format(CultureInfo.CurrentCulture, errorMessage, fileName)); } var checkWhiteList = !(UserController.Instance.GetCurrentUserInfo().IsSuperUser && ignoreWhiteList); if (checkWhiteList && !this.WhiteList.IsAllowedExtension(".exe") && !FileSecurityController.Instance.ValidateNotExectuable(fileContent)) { - var defaultMessage = "The content of '{0}' is not valid. The file has not been added."; + const string defaultMessage = "The content of '{0}' is not valid. The file has not been added."; var errorMessage = Localization.GetExceptionMessage("AddFileInvalidContent", defaultMessage); - throw new InvalidFileContentException(string.Format(errorMessage, fileName)); + throw new InvalidFileContentException(string.Format(CultureInfo.CurrentCulture, errorMessage, fileName)); } } - private void ManageFileAdding(int createdByUserID, Workflow folderWorkflow, bool fileExists, FileInfo file) + private void ManageFileAdding(int createdByUserId, Workflow folderWorkflow, bool fileExists, FileInfo file) { if (folderWorkflow == null || !fileExists) { - AddFile(file, createdByUserID); + AddFile(file, createdByUserId); } else { - // File Events for updating will not be fired. Only events for adding nust be fired + // File Events for updating will not be fired. Only events for adding must be fired this.UpdateFile(file, true, false); } - if (folderWorkflow != null && StartWorkflow(createdByUserID, folderWorkflow, fileExists, file.ContentItemID)) + if (folderWorkflow != null && StartWorkflow(createdByUserId, folderWorkflow, fileExists, file.ContentItemID)) { // if file exists it could have been published. So We don't have to update the field if (!fileExists) diff --git a/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs b/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs index 0b03319b7cf..9fc00c85138 100644 --- a/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs +++ b/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs @@ -113,8 +113,8 @@ public void ProcessRequest(HttpContext context) TabType urlType = Globals.GetURLType(url); if (urlType == TabType.Tab) { - // verify whether the tab is exist, otherwise throw out 404. - if (TabController.Instance.GetTab(int.Parse(url), portalSettings.PortalId, false) == null) + // verify whether the tab exists, otherwise throw out 404. + if (TabController.Instance.GetTab(int.Parse(url, CultureInfo.InvariantCulture), portalSettings.PortalId, false) == null) { Handle404Exception(context, context.Request.RawUrl); } @@ -125,7 +125,7 @@ public void ProcessRequest(HttpContext context) url = Globals.LinkClick(url, tabId, moduleId, false); } - if (urlType == TabType.File && url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) == false) + if (urlType == TabType.File && !url.StartsWith("fileid=", StringComparison.OrdinalIgnoreCase)) { // to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(url); @@ -159,7 +159,7 @@ public void ProcessRequest(HttpContext context) { case TabType.File: var download = false; - var file = fileManager.GetFile(int.Parse(UrlUtils.GetParameterValue(url))); + var file = fileManager.GetFile(int.Parse(UrlUtils.GetParameterValue(url), CultureInfo.InvariantCulture)); if (file != null) { if (!file.IsEnabled || !HasAPublishedVersion(file)) diff --git a/DNN Platform/Library/Services/FileSystem/FileSizeFormatProvider.cs b/DNN Platform/Library/Services/FileSystem/FileSizeFormatProvider.cs index 923af15d769..4f381bec5fd 100644 --- a/DNN Platform/Library/Services/FileSystem/FileSizeFormatProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/FileSizeFormatProvider.cs @@ -2,82 +2,81 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.FileSystem -{ - using System; +namespace DotNetNuke.Services.FileSystem +{ + using System; - using Localization = DotNetNuke.Services.Localization.Localization; + using Localization = DotNetNuke.Services.Localization.Localization; - public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter - { - private const string FileSizeFormat = "fs"; - private const decimal OneKiloByte = 1024; - private const decimal OneMegaByte = OneKiloByte * 1024; + public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter + { + private const string FileSizeFormat = "fs"; + private const decimal OneKiloByte = 1024; + private const decimal OneMegaByte = OneKiloByte * 1024; private const decimal OneGigaByte = OneMegaByte * 1024; /// - public object GetFormat(Type formatType) - { - return formatType == typeof(ICustomFormatter) ? this : null; + public object GetFormat(Type formatType) + { + return formatType == typeof(ICustomFormatter) ? this : null; } /// - public string Format(string format, object arg, IFormatProvider formatProvider) - { - if (format == null || !format.StartsWith(FileSizeFormat)) - { - return DefaultFormat(format, arg, formatProvider); - } - - if (arg is string) - { - return DefaultFormat(format, arg, formatProvider); - } - - decimal size; - - try - { - size = Convert.ToDecimal(arg); - } - catch (InvalidCastException) - { - return DefaultFormat(format, arg, formatProvider); - } - - string suffix; - if (size >= OneGigaByte) - { - size /= OneGigaByte; - suffix = Localization.GetString("SizeGb"); - } - else if (size >= OneMegaByte) - { - size /= OneMegaByte; - suffix = Localization.GetString("SizeMb"); - } - else if (size >= OneKiloByte) - { - size /= OneKiloByte; - suffix = Localization.GetString("SizeKb"); - } - else - { - suffix = Localization.GetString("SizeB"); - } - - return string.Format("{0:N1} {1}", size, suffix); - } - - private static string DefaultFormat(string format, object arg, IFormatProvider formatProvider) - { - var formattableArg = arg as IFormattable; - if (formattableArg != null) - { - return formattableArg.ToString(format, formatProvider); - } - - return arg.ToString(); - } - } -} + public string Format(string format, object arg, IFormatProvider formatProvider) + { + if (format == null || !format.StartsWith(FileSizeFormat, StringComparison.Ordinal)) + { + return DefaultFormat(format, arg, formatProvider); + } + + if (arg is string) + { + return DefaultFormat(format, arg, formatProvider); + } + + decimal size; + + try + { + size = Convert.ToDecimal(arg, formatProvider); + } + catch (InvalidCastException) + { + return DefaultFormat(format, arg, formatProvider); + } + + string suffix; + if (size >= OneGigaByte) + { + size /= OneGigaByte; + suffix = Localization.GetString("SizeGb"); + } + else if (size >= OneMegaByte) + { + size /= OneMegaByte; + suffix = Localization.GetString("SizeMb"); + } + else if (size >= OneKiloByte) + { + size /= OneKiloByte; + suffix = Localization.GetString("SizeKb"); + } + else + { + suffix = Localization.GetString("SizeB"); + } + + return string.Format(formatProvider, "{0:N1} {1}", size, suffix); + } + + private static string DefaultFormat(string format, object arg, IFormatProvider formatProvider) + { + if (arg is IFormattable formattableArg) + { + return formattableArg.ToString(format, formatProvider); + } + + return arg.ToString(); + } + } +} diff --git a/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs b/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs index caab420bce5..d506da68099 100644 --- a/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs +++ b/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs @@ -2,52 +2,53 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.FileSystem -{ - using System; - using System.Collections.Specialized; - using System.Text.RegularExpressions; - - using DotNetNuke.Common.Utilities; - - public class FileUrlHelper - { - private static readonly Regex RegexStandardFile = - new Regex(@"^/portals/(?[0-9]+|_default)/(?.*\.[a-z0-9]*)$", RegexOptions.Compiled); - - public static bool IsStandardFileURLFormat(string requestPath, out IFileInfo fileRequested) - { - var match = RegexStandardFile.Match(requestPath.ToLowerInvariant()); - if (match.Success) - { - var filePath = match.Groups["filePath"].Value; - var portal = match.Groups["portal"].Value; - - var portalId = Null.NullInteger; - if (portal != "_default") - { - portalId = int.Parse(portal); - } - - fileRequested = FileManager.Instance.GetFile(portalId, filePath); - return true; - } - - fileRequested = null; - return false; - } - - public static bool IsLinkClickURLFormat(string requestPath, NameValueCollection requestQueryString, out IFileInfo fileRequested) - { - if (requestPath.EndsWith(@"/LinkClick.aspx", StringComparison.OrdinalIgnoreCase) && requestQueryString["fileticket"] != null) - { - int fileId = FileLinkClickController.Instance.GetFileIdFromLinkClick(requestQueryString); - fileRequested = FileManager.Instance.GetFile(fileId); - return true; - } - - fileRequested = null; - return false; - } - } -} +namespace DotNetNuke.Services.FileSystem +{ + using System; + using System.Collections.Specialized; + using System.Globalization; + using System.Text.RegularExpressions; + + using DotNetNuke.Common.Utilities; + + public class FileUrlHelper + { + private static readonly Regex RegexStandardFile = + new Regex(@"^/portals/(?[0-9]+|_default)/(?.*\.[a-z0-9]*)$", RegexOptions.Compiled); + + public static bool IsStandardFileURLFormat(string requestPath, out IFileInfo fileRequested) + { + var match = RegexStandardFile.Match(requestPath.ToLowerInvariant()); + if (match.Success) + { + var filePath = match.Groups["filePath"].Value; + var portal = match.Groups["portal"].Value; + + var portalId = Null.NullInteger; + if (portal != "_default") + { + portalId = int.Parse(portal, CultureInfo.InvariantCulture); + } + + fileRequested = FileManager.Instance.GetFile(portalId, filePath); + return true; + } + + fileRequested = null; + return false; + } + + public static bool IsLinkClickURLFormat(string requestPath, NameValueCollection requestQueryString, out IFileInfo fileRequested) + { + if (requestPath.EndsWith(@"/LinkClick.aspx", StringComparison.OrdinalIgnoreCase) && requestQueryString["fileticket"] != null) + { + int fileId = FileLinkClickController.Instance.GetFileIdFromLinkClick(requestQueryString); + fileRequested = FileManager.Instance.GetFile(fileId); + return true; + } + + fileRequested = null; + return false; + } + } +} diff --git a/DNN Platform/Library/Services/FileSystem/FileVersionController.cs b/DNN Platform/Library/Services/FileSystem/FileVersionController.cs index c2568f56e13..93b3bf696cf 100644 --- a/DNN Platform/Library/Services/FileSystem/FileVersionController.cs +++ b/DNN Platform/Library/Services/FileSystem/FileVersionController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.FileSystem { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; @@ -82,6 +83,7 @@ public string AddFileVersion(IFileInfo file, int userId, bool published, bool re } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void SetPublishedVersion(IFileInfo file, int newPublishedVersion) { DataProvider.Instance().SetPublishedVersion(file.FileId, newPublishedVersion); diff --git a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs index b7826bc7b22..9056cc4f800 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.FileSystem @@ -121,7 +121,7 @@ public string PhysicalPath } } - return physicalPath.Replace("/", "\\"); + return physicalPath.Replace("/", @"\"); } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderManager.cs b/DNN Platform/Library/Services/FileSystem/FolderManager.cs index 403a5a940d6..d0b4df3183e 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderManager.cs @@ -334,7 +334,7 @@ public virtual IEnumerable GetFolders(int portalId) { var folders = new List(); - var cacheKey = string.Format(DataCache.FolderCacheKey, portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.FolderCacheKey, portalId); CBO.Instance.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.FolderCacheTimeOut, DataCache.FolderCachePriority, portalId), this.GetFoldersSortedCallBack, false).ForEach(folders.Add); return folders; @@ -349,7 +349,7 @@ public virtual IEnumerable GetFolders(int portalId, string permissi { var folders = new List(); - var cacheKey = string.Format(DataCache.FolderUserCacheKey, portalId, permissions, userId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.FolderUserCacheKey, portalId, permissions, userId); var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.FolderUserCacheTimeOut, DataCache.FolderUserCachePriority, portalId, permissions, userId); CBO.Instance.GetCachedObject>(cacheItemArgs, this.GetFoldersByPermissionSortedCallBack, false).ForEach(folders.Add); @@ -428,12 +428,11 @@ public virtual IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinatio if (this.FolderExists(folder.PortalID, newFolderPath)) { - throw new InvalidOperationException(string.Format( - Localization.GetExceptionMessage( - "CannotMoveFolderAlreadyExists", - "The folder with name '{0}' cannot be moved. A folder with that name already exists under the folder '{1}'.", - folder.FolderName, - destinationFolder.FolderName))); + throw new InvalidOperationException(Localization.GetExceptionMessage( + "CannotMoveFolderAlreadyExists", + "The folder with name '{0}' cannot be moved. A folder with that name already exists under the folder '{1}'.", + folder.FolderName, + destinationFolder.FolderName)); } var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); @@ -441,11 +440,10 @@ public virtual IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinatio if (!this.CanMoveBetweenFolderMappings(folderMapping, destinationFolderMapping)) { - throw new InvalidOperationException(string.Format( - Localization.GetExceptionMessage( - "CannotMoveFolderBetweenFolderType", - "The folder with name '{0}' cannot be moved. Move Folder operation between this two folder types is not allowed", - folder.FolderName))); + throw new InvalidOperationException(Localization.GetExceptionMessage( + "CannotMoveFolderBetweenFolderType", + "The folder with name '{0}' cannot be moved. Move Folder operation between this two folder types is not allowed", + folder.FolderName)); } if (!this.IsMoveOperationValid(folder, destinationFolder, newFolderPath)) @@ -652,7 +650,7 @@ public virtual IFolderInfo UpdateFolder(IFolderInfo folder) /// Used as base class for FolderPermissionInfo when there is no read permission already defined. public virtual void AddAllUserReadPermission(IFolderInfo folder, PermissionInfo permission) { - var roleId = int.Parse(Globals.glbRoleAllUsers); + var roleId = int.Parse(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture); var folderPermission = (from FolderPermissionInfo p in folder.FolderPermissions @@ -760,7 +758,7 @@ public virtual void SetFolderPermissions(IFolderInfo folder, int administratorRo internal virtual bool IsValidFolderPath(string folderPath) { var illegalInFolderPath = new Regex($"[{Regex.Escape(new string(Path.GetInvalidPathChars()))}]", RegexOptions.Compiled); - return !illegalInFolderPath.IsMatch(folderPath) && !folderPath.TrimEnd('/', '\\').EndsWith("."); + return !illegalInFolderPath.IsMatch(folderPath) && !folderPath.TrimEnd('/', '\\').EndsWith(".", StringComparison.Ordinal); } /// Adds a log entry. @@ -785,7 +783,7 @@ internal virtual void AddLogEntry(string propertyName, string propertyValue, Eve /// The new folder path. internal void DeleteFilesFromCache(int portalId, string newFolderPath) { - var folders = this.GetFolders(portalId).Where(f => f.FolderPath.StartsWith(newFolderPath)); + var folders = this.GetFolders(portalId).Where(f => f.FolderPath.StartsWith(newFolderPath, StringComparison.OrdinalIgnoreCase)); foreach (var folderInfo in folders) { var fileIds = this.GetFiles(folderInfo).Select(f => f.FileId); @@ -848,7 +846,7 @@ internal virtual IFolderInfo AddUserFolder(UserInfo user) var folderPermission = new FolderPermissionInfo(permission); ((IFolderPermissionInfo)folderPermission).FolderId = folder.FolderID; ((IFolderPermissionInfo)folderPermission).UserId = user.UserID; - ((IFolderPermissionInfo)folderPermission).RoleId = int.Parse(Globals.glbRoleNothing); + ((IFolderPermissionInfo)folderPermission).RoleId = int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture); folderPermission.AllowAccess = true; folder.FolderPermissions.Add(folderPermission); @@ -1199,7 +1197,7 @@ internal virtual SortedList GetFileSystemFoldersRecursiv foreach (var dn in DirectoryWrapper.Instance.GetDirectories(dir)) { - if (((FileWrapper.Instance.GetAttributes(dn) & FileAttributes.Hidden) == FileAttributes.Hidden || dn.StartsWith("_")) && hideFoldersEnabled) + if (((FileWrapper.Instance.GetAttributes(dn) & FileAttributes.Hidden) == FileAttributes.Hidden || dn.StartsWith("_", StringComparison.Ordinal)) && hideFoldersEnabled) { continue; } @@ -1357,7 +1355,7 @@ internal virtual SortedList GetMergedTree(int portalId, // Update ExistsInFolderMapping if the Parent Does Not ExistsInFolderMapping var mergedTreeItems = mergedTree.Values; foreach (var mergedItem in mergedTreeItems.Where(m => m.ExistsInFolderMapping - && mergedTreeItems.Any(mt2 => !mt2.ExistsInFolderMapping && m.FolderPath.StartsWith(mt2.FolderPath)))) + && mergedTreeItems.Any(mt2 => !mt2.ExistsInFolderMapping && m.FolderPath.StartsWith(mt2.FolderPath, StringComparison.OrdinalIgnoreCase)))) { mergedItem.ExistsInFolderMapping = false; } @@ -1395,7 +1393,7 @@ internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, IFolderInfo } // Destination folder cannot be a child mapped folder from the folder to move - return !destinationFolder.MappedPath.StartsWith(folderToMove.MappedPath) && this.IsMoveOperationValid(folderToMove, newFolderPath); + return !destinationFolder.MappedPath.StartsWith(folderToMove.MappedPath, StringComparison.OrdinalIgnoreCase) && this.IsMoveOperationValid(folderToMove, newFolderPath); } /// This member is reserved for internal use and is not intended to be used directly from your code. @@ -1411,7 +1409,7 @@ internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, string newF } // newParentFolder cannot be a child of folderToMove - return !newFolderPath.StartsWith(folderToMove.FolderPath); + return !newFolderPath.StartsWith(folderToMove.FolderPath, StringComparison.OrdinalIgnoreCase); } /// This member is reserved for internal use and is not intended to be used directly from your code. @@ -1518,7 +1516,7 @@ internal virtual void MoveFolderBetweenProviders(IFolderInfo folder, string newF { this.RenameFolderInFileSystem(folder, newFolderPath); - var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(folder.FolderPath)).ToArray(); + var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(folder.FolderPath, StringComparison.OrdinalIgnoreCase)).ToArray(); var tmpFolderPath = folder.FolderPath; foreach (var folderInfo in folderInfos) @@ -1784,14 +1782,14 @@ internal virtual void UpdateChildFolders(IFolderInfo folder, string newFolderPat { var originalFolderPath = folder.FolderPath; - var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(originalFolderPath)).ToArray(); + var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(originalFolderPath, StringComparison.OrdinalIgnoreCase)).ToArray(); foreach (var folderInfo in folderInfos) { var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folderInfo.FolderMappingID); var provider = FolderProvider.Instance(folderMapping.FolderProviderType); - var folderPath = newFolderPath + (newFolderPath.EndsWith("/") ? string.Empty : "/") + folderInfo.FolderPath.Substring(originalFolderPath.Length); + var folderPath = newFolderPath + (newFolderPath.EndsWith("/", StringComparison.Ordinal) ? string.Empty : "/") + folderInfo.FolderPath.Substring(originalFolderPath.Length); var parentFolder = this.GetParentFolder(folder.PortalID, folderPath); folderInfo.ParentID = parentFolder.FolderID; @@ -2122,7 +2120,7 @@ private IEnumerable SearchFiles(IFolderInfo folder, Regex regex, bool // Pre-compute allowed folders once var allowedFolderPaths = this.GetFolders(folder.PortalID) - .Where(f => f.FolderPath.StartsWith(folder.FolderPath) && + .Where(f => f.FolderPath.StartsWith(folder.FolderPath, StringComparison.OrdinalIgnoreCase) && FolderPermissionController.Instance.CanViewFolder(f)) .Select(f => f.FolderPath) .ToHashSet(); diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs index 86574013c8e..65fe89e6a16 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs @@ -8,6 +8,8 @@ namespace DotNetNuke.Services.FileSystem using System.Collections; using System.Collections.Generic; using System.Data; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using DotNetNuke.Common.Utilities; @@ -53,6 +55,7 @@ public int AddFolderMapping(FolderMappingInfo objFolderMapping) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void DeleteFolderMapping(int portalID, int folderMappingID) { var folderManager = FolderManager.Instance; @@ -69,8 +72,12 @@ public void DeleteFolderMapping(int portalID, int folderMappingID) // Remove the folders with the provided mapping that doesn't have child folders with other mapping (only in the database and filesystem) var folders1 = folders; // copy the variable to not access a modified closure - var removableFolders = folders.Where(f => f.FolderMappingID == folderMappingID && !folders1.Any(f2 => f2.FolderID != f.FolderID && - f2.FolderPath.StartsWith(f.FolderPath) && f2.FolderMappingID != folderMappingID)); + var removableFolders = folders.Where(f => + f.FolderMappingID == folderMappingID && + !folders1.Any(f2 => + f2.FolderID != f.FolderID && + f2.FolderPath.StartsWith(f.FolderPath, StringComparison.OrdinalIgnoreCase) && + f2.FolderMappingID != folderMappingID)); if (removableFolders.Any()) { @@ -117,12 +124,14 @@ public void UpdateFolderMapping(FolderMappingInfo objFolderMapping) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public FolderMappingInfo GetFolderMapping(int folderMappingID) { return CBO.FillObject(DataProvider.GetFolderMapping(folderMappingID)); } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public FolderMappingInfo GetFolderMapping(int portalId, int folderMappingID) { return this.GetFolderMappings(portalId).SingleOrDefault(fm => fm.FolderMappingID == folderMappingID); @@ -137,7 +146,7 @@ public FolderMappingInfo GetFolderMapping(int portalId, string mappingName) /// public List GetFolderMappings(int portalId) { - var cacheKey = string.Format(DataCache.FolderMappingCacheKey, portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.FolderMappingCacheKey, portalId); return CBO.GetCachedObject>( new CacheItemArgs( cacheKey, @@ -147,12 +156,14 @@ public List GetFolderMappings(int portalId) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void AddDefaultFolderTypes(int portalID) { DataProvider.AddDefaultFolderTypes(portalID); } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public Hashtable GetFolderMappingSettings(int folderMappingID) { var strCacheKey = CacheKeyPrefix + folderMappingID; @@ -185,7 +196,7 @@ public Hashtable GetFolderMappingSettings(int folderMappingID) CBO.CloseDataReader(dr, true); } - var intCacheTimeout = 20 * Convert.ToInt32(Host.PerformanceSetting); + var intCacheTimeout = 20 * (int)Host.PerformanceSetting; DataCache.SetCache(strCacheKey, objSettings, TimeSpan.FromMinutes(intCacheTimeout)); } @@ -196,25 +207,25 @@ private static void UpdateFolderMappingSettings(FolderMappingInfo objFolderMappi { foreach (string sKey in objFolderMapping.FolderMappingSettings.Keys) { - UpdateFolderMappingSetting(objFolderMapping.FolderMappingID, sKey, Convert.ToString(objFolderMapping.FolderMappingSettings[sKey])); + UpdateFolderMappingSetting(objFolderMapping.FolderMappingID, sKey, Convert.ToString(objFolderMapping.FolderMappingSettings[sKey], CultureInfo.InvariantCulture)); } ClearFolderMappingSettingsCache(objFolderMapping.FolderMappingID); } - private static void UpdateFolderMappingSetting(int folderMappingID, string settingName, string settingValue) + private static void UpdateFolderMappingSetting(int folderMappingId, string settingName, string settingValue) { IDataReader dr = null; try { - dr = DataProvider.GetFolderMappingSetting(folderMappingID, settingName); + dr = DataProvider.GetFolderMappingSetting(folderMappingId, settingName); if (dr.Read()) { - DataProvider.UpdateFolderMappingSetting(folderMappingID, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID); + DataProvider.UpdateFolderMappingSetting(folderMappingId, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID); } else { - DataProvider.AddFolderMappingSetting(folderMappingID, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID); + DataProvider.AddFolderMappingSetting(folderMappingId, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID); } } catch (Exception ex) @@ -230,7 +241,7 @@ private static void UpdateFolderMappingSetting(int folderMappingID, string setti private static void ClearFolderMappingCache(int portalId) { - var cacheKey = string.Format(DataCache.FolderMappingCacheKey, portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.FolderMappingCacheKey, portalId); DataCache.RemoveCache(cacheKey); } diff --git a/DNN Platform/Library/Services/FileSystem/FolderProvider.cs b/DNN Platform/Library/Services/FileSystem/FolderProvider.cs index 851137e5b82..44210740bf2 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderProvider.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Services.FileSystem using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -254,7 +255,7 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) var hashData = hasher.ComputeHash(fileContent); foreach (var b in hashData) { - hashText.Append(b.ToString("x2")); + hashText.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } } diff --git a/DNN Platform/Library/Services/FileSystem/LinkClickPortalSettings.cs b/DNN Platform/Library/Services/FileSystem/LinkClickPortalSettings.cs index 34022ec46ca..95dcbcfca5a 100644 --- a/DNN Platform/Library/Services/FileSystem/LinkClickPortalSettings.cs +++ b/DNN Platform/Library/Services/FileSystem/LinkClickPortalSettings.cs @@ -8,8 +8,10 @@ namespace DotNetNuke.Services.FileSystem internal class LinkClickPortalSettings { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string PortalGUID; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool EnableUrlLanguage; } } diff --git a/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs b/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs index 507bde8e3f2..0c97dbede40 100644 --- a/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs @@ -10,6 +10,7 @@ namespace DotNetNuke.Services.FileSystem using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Linq; @@ -211,14 +212,14 @@ public override string GetFileUrl(IFileInfo file) portalSettings.GUID.ToString()); } - // Does site management want the cachebuster parameter? + // Does site management want the cache-buster parameter? if (portalSettings.AddCachebusterToResourceUris) { - var cachebusterToken = UrlUtils.EncryptParameter( - file.LastModificationTime.GetHashCode().ToString(), + var cacheBusterToken = UrlUtils.EncryptParameter( + file.LastModificationTime.GetHashCode().ToString(CultureInfo.InvariantCulture), portalSettings.GUID.ToString()); - return TestableGlobals.Instance.ResolveUrl(fullPath + "?ver=" + cachebusterToken); + return TestableGlobals.Instance.ResolveUrl(fullPath + "?ver=" + cacheBusterToken); } return TestableGlobals.Instance.ResolveUrl(fullPath); diff --git a/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs b/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs index 710e7cf7ea9..15abd736db9 100644 --- a/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs @@ -131,11 +131,11 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) string format = string.IsNullOrEmpty(parameters["format"]) ? "jpg" : parameters["format"].ToLowerInvariant(); // Lets retrieve the color - Color color = string.IsNullOrEmpty(parameters["color"]) ? Color.White : (parameters["color"].StartsWith("#") ? ColorTranslator.FromHtml(parameters["color"]) : Color.FromName(parameters["color"])); - Color backColor = string.IsNullOrEmpty(parameters["backcolor"]) ? Color.White : (parameters["backcolor"].StartsWith("#") ? ColorTranslator.FromHtml(parameters["backcolor"]) : Color.FromName(parameters["backcolor"])); + Color color = string.IsNullOrEmpty(parameters["color"]) ? Color.White : (parameters["color"].StartsWith("#", StringComparison.Ordinal) ? ColorTranslator.FromHtml(parameters["color"]) : Color.FromName(parameters["color"])); + Color backColor = string.IsNullOrEmpty(parameters["backcolor"]) ? Color.White : (parameters["backcolor"].StartsWith("#", StringComparison.Ordinal) ? ColorTranslator.FromHtml(parameters["backcolor"]) : Color.FromName(parameters["backcolor"])); // Do we have a border ? - int border = string.IsNullOrEmpty(parameters["border"]) ? 0 : Convert.ToInt32(parameters["border"]); + int border = string.IsNullOrEmpty(parameters["border"]) ? 0 : Convert.ToInt32(parameters["border"], CultureInfo.InvariantCulture); // Do we have a resizemode defined ? var resizeMode = string.IsNullOrEmpty(parameters["resizemode"]) ? ImageResizeMode.Fit : (ImageResizeMode)Enum.Parse(typeof(ImageResizeMode), parameters["ResizeMode"], true); @@ -215,7 +215,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) var secureFileTrans = new SecureFileTransform(); if (!string.IsNullOrEmpty(parameters["FileId"])) { - var fileId = Convert.ToInt32(parameters["FileId"]); + var fileId = Convert.ToInt32(parameters["FileId"], CultureInfo.InvariantCulture); var file = FileManager.Instance.GetFile(fileId); if (file == null) { @@ -260,7 +260,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) // allow only site resources when using the url parameter IPortalAliasController portalAliasController = PortalAliasController.Instance; var uriValidator = new UriValidator(portalAliasController); - if (!url.StartsWith("http") || !uriValidator.UriBelongsToSite(new Uri(url))) + if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase) || !uriValidator.UriBelongsToSite(new Uri(url))) { return this.GetEmptyImageInfo(); } @@ -316,7 +316,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) switch (pi.PropertyType.Name) { case "Int32": - pi.SetValue(imageTransform, Convert.ToInt32(parameters[key]), null); + pi.SetValue(imageTransform, Convert.ToInt32(parameters[key], CultureInfo.InvariantCulture), null); break; case "String": pi.SetValue(imageTransform, parameters[key], null); @@ -479,7 +479,7 @@ private static bool IsAllowedFilePathImage(string filePath) var normalizeFilePath = NormalizeFilePath(filePath.Trim()); // Resources file cannot be served - if (filePath.EndsWith(".resources")) + if (filePath.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) { return false; } @@ -490,8 +490,8 @@ private static bool IsAllowedFilePathImage(string filePath) private static string NormalizeFilePath(string filePath) { - var normalizeFilePath = filePath.Replace("\\", "/"); - if (!normalizeFilePath.StartsWith("/")) + var normalizeFilePath = filePath.Replace(@"\", "/"); + if (!normalizeFilePath.StartsWith("/", StringComparison.Ordinal)) { normalizeFilePath = "/" + normalizeFilePath; } @@ -584,37 +584,37 @@ private void ReadSettings() switch (name) { case "enableclientcache": - this.EnableClientCache = Convert.ToBoolean(setting[1]); + this.EnableClientCache = Convert.ToBoolean(setting[1], CultureInfo.InvariantCulture); break; case "clientcacheexpiration": - this.ClientCacheExpiration = TimeSpan.FromSeconds(Convert.ToInt32(setting[1])); + this.ClientCacheExpiration = TimeSpan.FromSeconds(Convert.ToInt32(setting[1], CultureInfo.InvariantCulture)); break; case "enableservercache": - this.EnableServerCache = Convert.ToBoolean(setting[1]); + this.EnableServerCache = Convert.ToBoolean(setting[1], CultureInfo.InvariantCulture); break; case "servercacheexpiration": - DiskImageStore.PurgeInterval = TimeSpan.FromSeconds(Convert.ToInt32(setting[1])); + DiskImageStore.PurgeInterval = TimeSpan.FromSeconds(Convert.ToInt32(setting[1], CultureInfo.InvariantCulture)); break; case "allowstandalone": - this.AllowStandalone = Convert.ToBoolean(setting[1]); + this.AllowStandalone = Convert.ToBoolean(setting[1], CultureInfo.InvariantCulture); break; case "logsecurity": - this.LogSecurity = Convert.ToBoolean(setting[1]); + this.LogSecurity = Convert.ToBoolean(setting[1], CultureInfo.InvariantCulture); break; case "imagecompression": - this.ImageCompression = Convert.ToInt32(setting[1]); + this.ImageCompression = Convert.ToInt32(setting[1], CultureInfo.InvariantCulture); break; case "alloweddomains": this.AllowedDomains = setting[1].Split(','); break; case "enableipcount": - this.EnableIPCount = Convert.ToBoolean(setting[1]); + this.EnableIPCount = Convert.ToBoolean(setting[1], CultureInfo.InvariantCulture); break; case "ipcountmax": - this.IPCountMaxCount = Convert.ToInt32(setting[1]); + this.IPCountMaxCount = Convert.ToInt32(setting[1], CultureInfo.InvariantCulture); break; case "ipcountpurgeinterval": - this.IPCountPurgeInterval = TimeSpan.FromSeconds(Convert.ToInt32(setting[1])); + this.IPCountPurgeInterval = TimeSpan.FromSeconds(Convert.ToInt32(setting[1], CultureInfo.InvariantCulture)); break; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs index 99eb4310b38..6aa7897d56f 100644 --- a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs +++ b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.GeneratedImage { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Threading; using System.Web; @@ -171,7 +172,7 @@ public static bool CheckIp(string ipAddress) } } - File.WriteAllText(path, count.ToString()); + File.WriteAllText(path, count.ToString(CultureInfo.InvariantCulture)); return true; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs b/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs index a5f4c62f106..b021d986184 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs @@ -396,7 +396,7 @@ private static string GetIDFromBytes(byte[] buffer) var sb = new StringBuilder(); foreach (var b in result) { - sb.Append(b.ToString("X2")); + sb.Append(b.ToString("X2", CultureInfo.InvariantCulture)); } return sb.ToString(); @@ -468,7 +468,7 @@ private Image GetImageThroughTransforms(Image image) // Clear the user image disk cache if userid is found in clear list and is within ClientCacheExpiration time. private bool ClearDiskImageCacheIfNecessary(int userId, int portalId, string cacheId) { - var cacheKey = string.Format(DataCache.UserIdListToClearDiskImageCacheKey, portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.UserIdListToClearDiskImageCacheKey, portalId); Dictionary userIds; if ((userIds = DataCache.GetCache>(cacheKey)) == null || !userIds.ContainsKey(userId)) { diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs index f724c2253a3..787b5eea486 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs @@ -17,6 +17,7 @@ public class PaletteQuantizer : Quantizer /// List of all colors in the palette. [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1309:FieldNamesMustNotBeginWithUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected Color[] _colors; @@ -110,6 +111,7 @@ protected override byte QuantizePixel(Color32 pixel) /// Retrieve the palette for the quantized image. /// Any old palette, this is overwritten. /// The new color palette. + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override ColorPalette GetPalette(ColorPalette palette) { for (int index = 0; index < this._colors.Length; index++) diff --git a/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs b/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs index a0e3b1b3e48..f78b7bd735c 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs @@ -7,6 +7,8 @@ namespace DotNetNuke.Services.GeneratedImage using System; using System.Collections.Generic; using System.ComponentModel.Composition; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Profile; @@ -14,11 +16,13 @@ namespace DotNetNuke.Services.GeneratedImage /// this class handles profile changes. [Export(typeof(IProfileEventHandlers))] [ExportMetadata("MessageType", "ProfileEventHandler")] + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public class ProfileEventHandler : IProfileEventHandlers { /// This method add the updated user id into cache to clear image from disk before returning to UI. /// The event sender. /// The event arguments. + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void ProfileUpdated(object sender, ProfileEventArgs profileArgs) { if (profileArgs?.User == null || profileArgs.OldProfile == null) @@ -34,7 +38,7 @@ public void ProfileUpdated(object sender, ProfileEventArgs profileArgs) var oldPhotoVisibilityMode = oldProfile.GetProperty(Entities.Users.UserProfile.USERPROFILE_Photo)?.ProfileVisibility.VisibilityMode; if (newProfile.Photo != oldProfile.Photo || newPhotoVisibilityMode != oldPhotoVisibilityMode) { - var cacheKey = string.Format(DataCache.UserIdListToClearDiskImageCacheKey, user.PortalID); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.UserIdListToClearDiskImageCacheKey, user.PortalID); Dictionary userIds; if ((userIds = DataCache.GetCache>(cacheKey)) == null) { @@ -42,10 +46,7 @@ public void ProfileUpdated(object sender, ProfileEventArgs profileArgs) } // Add the userid to the clear cache list, if not already in the list. - if (userIds.ContainsKey(user.UserID)) - { - userIds.Remove(user.UserID); - } + userIds.Remove(user.UserID); userIds.Add(user.UserID, DateTime.UtcNow); DataCache.SetCache(cacheKey, userIds); diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs index 75f8e4ebf02..61c7ebf7d18 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs @@ -68,7 +68,7 @@ public bool DoesHaveReadFolderPermission(IFolderInfo folder) private static bool IsImageExtension(string extension) { - if (!extension.StartsWith(".")) + if (!extension.StartsWith(".", StringComparison.Ordinal)) { extension = $".{extension}"; } diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs index 19526063467..7eb57160de8 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Services.GeneratedImage.StartTransform using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Drawing2D; + using System.Globalization; using System.IO; using DotNetNuke.Common; @@ -92,7 +93,7 @@ public bool TryGetPhotoFile(out IFileInfo photoFile) if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) { - photoFile = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); + photoFile = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue, CultureInfo.InvariantCulture)); if (photoFile == null) { isVisible = false; @@ -108,7 +109,7 @@ public bool TryGetPhotoFile(out IFileInfo photoFile) private static bool IsImageExtension(string extension) { - if (!extension.StartsWith(".")) + if (!extension.StartsWith(".", StringComparison.Ordinal)) { extension = $".{extension}"; } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs index f9ea5488c56..ca37e605d81 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs @@ -1,45 +1,40 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Installer.Dependencies -{ - using System; - using System.Reflection; - using System.Xml.XPath; +namespace DotNetNuke.Services.Installer.Dependencies +{ + using System; + using System.Globalization; + using System.Reflection; + using System.Xml.XPath; - /// The CoreVersionDependency determines whether the CoreVersion is correct. - public class CoreVersionDependency : DependencyBase - { + /// The CoreVersionDependency determines whether the CoreVersion is correct. + public class CoreVersionDependency : DependencyBase + { private Version minVersion; /// - public override string ErrorMessage - { - get - { - return string.Format(Util.INSTALL_Compatibility, this.minVersion); - } - } + public override string ErrorMessage => string.Format(CultureInfo.InvariantCulture, Util.INSTALL_Compatibility, this.minVersion); /// - public override bool IsValid - { - get - { - bool isValid = true; - if (Assembly.GetExecutingAssembly().GetName().Version < this.minVersion) - { - isValid = false; - } - - return isValid; - } + public override bool IsValid + { + get + { + bool isValid = true; + if (Assembly.GetExecutingAssembly().GetName().Version < this.minVersion) + { + isValid = false; + } + + return isValid; + } } /// - public override void ReadManifest(XPathNavigator dependencyNav) - { - this.minVersion = new Version(dependencyNav.Value); - } - } -} + public override void ReadManifest(XPathNavigator dependencyNav) + { + this.minVersion = new Version(dependencyNav.Value); + } + } +} diff --git a/DNN Platform/Library/Services/Installer/InstallFile.cs b/DNN Platform/Library/Services/Installer/InstallFile.cs index dad71c7422f..7d165adabef 100644 --- a/DNN Platform/Library/Services/Installer/InstallFile.cs +++ b/DNN Platform/Library/Services/Installer/InstallFile.cs @@ -180,7 +180,7 @@ public void SetVersion(Version version) /// A String representing the file name. private void ParseFileName(string fileName) { - int i = fileName.Replace("\\", "/").LastIndexOf("/", StringComparison.Ordinal); + int i = fileName.Replace(@"\", "/").LastIndexOf("/", StringComparison.Ordinal); if (i < 0) { this.Name = fileName.Substring(0); @@ -192,7 +192,7 @@ private void ParseFileName(string fileName) this.Path = fileName.Substring(0, i); } - if (string.IsNullOrEmpty(this.Path) && fileName.StartsWith("[app_code]")) + if (string.IsNullOrEmpty(this.Path) && fileName.StartsWith("[app_code]", StringComparison.OrdinalIgnoreCase)) { this.Name = fileName.Substring(10); this.Path = fileName.Substring(0, 10); @@ -230,7 +230,7 @@ private void ParseFileName(string fileName) { this.Type = InstallFileType.Script; } - else if (this.Path.StartsWith("[app_code]")) + else if (this.Path.StartsWith("[app_code]", StringComparison.OrdinalIgnoreCase)) { this.Type = InstallFileType.AppCode; } @@ -247,7 +247,7 @@ private void ParseFileName(string fileName) this.Path = this.Path.Replace("[app_code]", string.Empty); // remove starting "\" - if (this.Path.StartsWith("\\")) + if (this.Path.StartsWith(@"\", StringComparison.Ordinal)) { this.Path = this.Path.Substring(1); } diff --git a/DNN Platform/Library/Services/Installer/Installer.cs b/DNN Platform/Library/Services/Installer/Installer.cs index 4aaa2808b35..fdf45f0aa35 100644 --- a/DNN Platform/Library/Services/Installer/Installer.cs +++ b/DNN Platform/Library/Services/Installer/Installer.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -23,10 +24,10 @@ namespace DotNetNuke.Services.Installer using DotNetNuke.Services.Log.EventLog; /// The Installer class provides a single entrypoint for Package Installation. - public class Installer + public class Installer : IDisposable { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Installer)); - private readonly Stream inputStream; + private readonly MemoryStream inputStream; /// /// Initializes a new instance of the class. @@ -34,7 +35,7 @@ public class Installer /// the physical path to the temporary install folder and a string representing /// the physical path to the root of the site. /// - /// The physical path to the zip file containg the package. + /// The physical path to the zip file containing the package. /// The manifest filename. /// The physical path to the root of the site. /// Flag that determines whether the manifest will be loaded. @@ -296,7 +297,7 @@ public bool Install() // Clear Host Cache DataCache.ClearHostCache(true); - if (Config.GetFcnMode() == Config.FcnMode.Disabled.ToString()) + if (Config.GetFcnMode() == nameof(Config.FcnMode.Disabled)) { // force application restart after the new changes only when FCN is disabled Config.Touch(); @@ -355,7 +356,22 @@ public bool UnInstall(bool deleteFiles) return true; } - private static void BackupStreamIntoFile(Stream stream, PackageInfo package) + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.inputStream?.Dispose(); + } + } + + private static void BackupStreamIntoFile(MemoryStream stream, PackageInfo package) { try { @@ -451,7 +467,7 @@ private void ProcessPackages(XPathNavigator rootNav) string installOrder = Util.ReadAttribute(nav, "installOrder"); if (!string.IsNullOrEmpty(installOrder)) { - order = int.Parse(installOrder); + order = int.Parse(installOrder, CultureInfo.InvariantCulture); } this.Packages.Add(order, new PackageInstaller(nav.OuterXml, this.InstallerInfo)); diff --git a/DNN Platform/Library/Services/Installer/InstallerInfo.cs b/DNN Platform/Library/Services/Installer/InstallerInfo.cs index bf8eddb68e1..b924af11b0e 100644 --- a/DNN Platform/Library/Services/Installer/InstallerInfo.cs +++ b/DNN Platform/Library/Services/Installer/InstallerInfo.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; @@ -264,7 +265,7 @@ private void ReadZipStream(Stream inputStream, bool isEmbeddedZip) } } - this.Log.AddInfo(string.Format(Util.FILE_ReadSuccess, file.FullName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.FILE_ReadSuccess, file.FullName)); } if (this.ManifestFile == null) @@ -272,16 +273,13 @@ private void ReadZipStream(Stream inputStream, bool isEmbeddedZip) this.Log.AddFailure(Util.EXCEPTION_MissingDnn); } - if (this.Log.Valid) - { - this.Log.EndJob(Util.FILES_ReadingEnd); - } - else + if (!this.Log.Valid) { this.Log.AddFailure(new ReadManifestException(Util.EXCEPTION_FileLoad)); - this.Log.EndJob(Util.FILES_ReadingEnd); } + this.Log.EndJob(Util.FILES_ReadingEnd); + // Close the Zip Input Stream as we have finished with it inputStream.Close(); } diff --git a/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs index 4b2ad90d5df..173c4f3dc44 100644 --- a/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; + using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Security; @@ -33,9 +34,10 @@ public class AssemblyInstaller : FileInstaller protected override string ItemNodeName => "assembly"; /// Gets the PhysicalBasePath for the assemblies. - protected override string PhysicalBasePath => this.PhysicalSitePath + "\\"; - + protected override string PhysicalBasePath => this.PhysicalSitePath + @"\"; + /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override void DeleteFile(InstallFile file) { // Attempt to unregister assembly @@ -63,6 +65,7 @@ protected override bool IsCorrectType(InstallFileType type) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override bool InstallFile(InstallFile file) { bool bSuccess = true; diff --git a/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs index b3da5c93b06..1ab03bea1d6 100644 --- a/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; + using System.Globalization; using System.Xml.XPath; using DotNetNuke.Common.Utilities; @@ -65,7 +66,7 @@ public override void Install() } this.Completed = true; - this.Log.AddInfo(string.Format(Util.AUTHENTICATION_Registered, this.authSystem.AuthenticationType)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.AUTHENTICATION_Registered, this.authSystem.AuthenticationType)); } catch (Exception ex) { @@ -107,7 +108,7 @@ public override void Rollback() if (this.tempAuthSystem == null) { // No Temp Auth System - Delete newly added system - this.DeleteAuthentiation(); + this.DeleteAuthentication(); } else { @@ -119,14 +120,14 @@ public override void Rollback() /// The UnInstall method uninstalls the authentication component. public override void UnInstall() { - this.DeleteAuthentiation(); + this.DeleteAuthentication(); } /// - /// The DeleteAuthentiation method deletes the Authentication System + /// The DeleteAuthentication method deletes the Authentication System /// from the data Store. /// - private void DeleteAuthentiation() + private void DeleteAuthentication() { try { @@ -136,7 +137,7 @@ private void DeleteAuthentiation() AuthenticationController.DeleteAuthentication(authSystem); } - this.Log.AddInfo(string.Format(Util.AUTHENTICATION_UnRegistered, authSystem.AuthenticationType)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.AUTHENTICATION_UnRegistered, authSystem.AuthenticationType)); } catch (Exception ex) { diff --git a/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs index 73cb4ece724..afb32184f04 100644 --- a/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Xml.XPath; @@ -153,12 +154,12 @@ internal bool IsValidFolderPath(string path, out string validPath) return false; // no rooted paths } - if (path.StartsWith(Path.DirectorySeparatorChar.ToString())) + if (path.StartsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { return false; // no absolute paths } - if (path.IndexOf("..", StringComparison.InvariantCultureIgnoreCase) >= 0) + if (path.Contains("..", StringComparison.Ordinal)) { return false; // no relative paths outside the app root } @@ -278,7 +279,7 @@ protected override void RollbackFile(InstallFile installFile) private bool ProcessCleanupFile() { - this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.CLEANUP_Processing, this.Version.ToString(3))); try { var strListFile = Path.Combine(this.Package.InstallerInfo.TempInstallFolder, this.fileName); @@ -289,19 +290,19 @@ private bool ProcessCleanupFile() } catch (Exception ex) { - this.Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); + this.Log.AddWarning(string.Format(CultureInfo.InvariantCulture, Util.CLEANUP_ProcessError, ex.Message)); // DNN-9202: MUST NOT fail installation when cleanup files deletion fails // return false; } - this.Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, this.Version.ToString(3))); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.CLEANUP_ProcessComplete, this.Version.ToString(3))); return true; } private bool ProcessGlob() { - this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.CLEANUP_Processing, this.Version.ToString(3))); try { if (this.glob.Contains("..")) @@ -318,10 +319,10 @@ private bool ProcessGlob() } catch (Exception ex) { - this.Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); + this.Log.AddWarning(string.Format(CultureInfo.InvariantCulture, Util.CLEANUP_ProcessError, ex.Message)); } - this.Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, this.Version.ToString(3))); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.CLEANUP_ProcessComplete, this.Version.ToString(3))); return true; } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs b/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs index 919fe4c037e..3ad9c8050ca 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; using System.Collections.Generic; + using System.Globalization; using System.Xml.XPath; using DotNetNuke.Common; @@ -142,7 +143,7 @@ public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) } catch (FormatException) { - this.Log.AddWarning(string.Format(Util.MODULE_InvalidVersion, version)); + this.Log.AddWarning(string.Format(CultureInfo.InvariantCulture, Util.MODULE_InvalidVersion, version)); } if (upgradeVersion != null && (Globals.Status == Globals.UpgradeStatus.Install)) diff --git a/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs index 069be016796..fced96c85f5 100644 --- a/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Xml.XPath; @@ -36,13 +37,13 @@ protected virtual string PhysicalBasePath { get { - string physicalBasePath = this.PhysicalSitePath + "\\" + this.BasePath; - if (!physicalBasePath.EndsWith("\\")) + string physicalBasePath = this.PhysicalSitePath + @"\" + this.BasePath; + if (!physicalBasePath.EndsWith(@"\", StringComparison.Ordinal)) { - physicalBasePath += "\\"; + physicalBasePath += @"\"; } - return physicalBasePath.Replace("/", "\\"); + return physicalBasePath.Replace("/", @"\"); } } @@ -187,7 +188,7 @@ protected virtual bool InstallFile(InstallFile insFile) } else { - this.Log.AddFailure(string.Format(Util.FILE_NotAllowed, insFile.FullName)); + this.Log.AddFailure(string.Format(CultureInfo.InvariantCulture, Util.FILE_NotAllowed, insFile.FullName)); return false; } } @@ -242,7 +243,7 @@ protected virtual InstallFile ReadManifestItem(XPathNavigator nav, bool checkFil } else { - fileName = pathNav.Value + "\\"; + fileName = pathNav.Value + @"\"; } // Get the name @@ -284,7 +285,7 @@ protected virtual InstallFile ReadManifestItem(XPathNavigator nav, bool checkFil { if (File.Exists(file.TempFileName)) { - this.Log.AddInfo(string.Format(Util.FILE_Found, file.Path, file.Name)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.FILE_Found, file.Path, file.Name)); } else { diff --git a/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs index d672cacd83e..196f454fd5a 100644 --- a/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs @@ -2,56 +2,57 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Installer.Installers -{ - using System.Xml.XPath; +namespace DotNetNuke.Services.Installer.Installers +{ + using System.Xml.XPath; - using DotNetNuke.Common; + using DotNetNuke.Common; - public class JavaScriptFileInstaller : FileInstaller - { - /// Gets a list of allowable file extensions (in addition to the Host's List). - /// A String. - public override string AllowableFiles - { - get - { - return "js"; - } - } - - /// Gets the name of the Collection Node ("jsfiles"). - /// A String. - protected override string CollectionNodeName - { - get - { - return "jsfiles"; - } - } - - /// Gets the name of the Item Node ("jsfile"). - /// A String. - protected override string ItemNodeName - { - get - { - return "jsfile"; - } - } - - /// - /// The ReadCustomManifest method reads the custom manifest items (that subclasses - /// of FileInstaller may need). - /// - /// The XPathNavigator representing the node. - protected override void ReadCustomManifest(XPathNavigator nav) - { - XPathNavigator libraryNav = nav.SelectSingleNode("libraryFolderName"); - if (libraryNav != null) - { - this.BasePath = string.Format("Resources\\Libraries\\{0}\\{1}", libraryNav.Value, Globals.FormatVersion(this.Package.Version, "00", 3, "_")); - } - } - } -} + public class JavaScriptFileInstaller : FileInstaller + { + /// Gets a list of allowable file extensions (in addition to the Host's List). + /// A String. + public override string AllowableFiles + { + get + { + return "js"; + } + } + + /// Gets the name of the Collection Node ("jsfiles"). + /// A String. + protected override string CollectionNodeName + { + get + { + return "jsfiles"; + } + } + + /// Gets the name of the Item Node ("jsfile"). + /// A String. + protected override string ItemNodeName + { + get + { + return "jsfile"; + } + } + + /// + /// The ReadCustomManifest method reads the custom manifest items (that subclasses + /// of FileInstaller may need). + /// + /// The XPathNavigator representing the node. + protected override void ReadCustomManifest(XPathNavigator nav) + { + var libraryNav = nav.SelectSingleNode("libraryFolderName"); + if (libraryNav != null) + { + var version = Globals.FormatVersion(this.Package.Version, "00", 3, "_"); + this.BasePath = $@"Resources\Libraries\{libraryNav.Value}\{version}"; + } + } + } +} diff --git a/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs index 0add955e131..c24cd34fa5b 100644 --- a/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs @@ -2,104 +2,105 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Installer.Installers -{ - using System; - using System.IO; - using System.Xml.XPath; +namespace DotNetNuke.Services.Installer.Installers +{ + using System; + using System.Globalization; + using System.IO; + using System.Xml.XPath; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.JavaScriptLibraries; - public class JavaScriptLibraryInstaller : ComponentInstallerBase - { - private JavaScriptLibrary library; + public class JavaScriptLibraryInstaller : ComponentInstallerBase + { + private JavaScriptLibrary library; private JavaScriptLibrary installedLibrary; /// - public override void Commit() - { + public override void Commit() + { } /// - public override void Install() - { - try - { - // Attempt to get the JavaScript Library - this.installedLibrary = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == this.library.LibraryName && l.Version == this.library.Version); - - if (this.installedLibrary != null) - { - this.library.JavaScriptLibraryID = this.installedLibrary.JavaScriptLibraryID; - } - - // Save JavaScript Library to database - this.library.PackageID = this.Package.PackageID; - JavaScriptLibraryController.Instance.SaveLibrary(this.library); - - this.Completed = true; - this.Log.AddInfo(string.Format(Util.LIBRARY_Registered, this.library.LibraryName)); - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } + public override void Install() + { + try + { + // Attempt to get the JavaScript Library + this.installedLibrary = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == this.library.LibraryName && l.Version == this.library.Version); + + if (this.installedLibrary != null) + { + this.library.JavaScriptLibraryID = this.installedLibrary.JavaScriptLibraryID; + } + + // Save JavaScript Library to database + this.library.PackageID = this.Package.PackageID; + JavaScriptLibraryController.Instance.SaveLibrary(this.library); + + this.Completed = true; + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.LIBRARY_Registered, this.library.LibraryName)); + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } } /// - public override void ReadManifest(XPathNavigator manifestNav) - { - // Load the JavaScript Library from the manifest - this.library = CBO.DeserializeObject(new StringReader(manifestNav.InnerXml)); - this.library.Version = this.Package.Version; - - if (this.Log.Valid) - { - this.Log.AddInfo(Util.LIBRARY_ReadSuccess); - } + public override void ReadManifest(XPathNavigator manifestNav) + { + // Load the JavaScript Library from the manifest + this.library = CBO.DeserializeObject(new StringReader(manifestNav.InnerXml)); + this.library.Version = this.Package.Version; + + if (this.Log.Valid) + { + this.Log.AddInfo(Util.LIBRARY_ReadSuccess); + } } /// - public override void Rollback() - { - // If Temp Library exists then we need to update the DataStore with this - if (this.installedLibrary == null) - { - // No Temp Library - Delete newly added library - this.DeleteLibrary(); - } - else - { - // Temp Library - Rollback to Temp - JavaScriptLibraryController.Instance.SaveLibrary(this.installedLibrary); - } + public override void Rollback() + { + // If Temp Library exists then we need to update the DataStore with this + if (this.installedLibrary == null) + { + // No Temp Library - Delete newly added library + this.DeleteLibrary(); + } + else + { + // Temp Library - Rollback to Temp + JavaScriptLibraryController.Instance.SaveLibrary(this.installedLibrary); + } } /// - public override void UnInstall() - { - this.DeleteLibrary(); - } - - private void DeleteLibrary() - { - try - { - // Attempt to get the Library - var library = JavaScriptLibraryController.Instance.GetLibrary(l => l.PackageID == this.Package.PackageID); - - if (library != null) - { - JavaScriptLibraryController.Instance.DeleteLibrary(library); - - this.Log.AddInfo(string.Format(Util.LIBRARY_UnRegistered, library.LibraryName)); - } - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } - } - } -} + public override void UnInstall() + { + this.DeleteLibrary(); + } + + private void DeleteLibrary() + { + try + { + // Attempt to get the Library + var library = JavaScriptLibraryController.Instance.GetLibrary(l => l.PackageID == this.Package.PackageID); + + if (library != null) + { + JavaScriptLibraryController.Instance.DeleteLibrary(library); + + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.LIBRARY_UnRegistered, library.LibraryName)); + } + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } + } +} diff --git a/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs index cd728729e2f..a219f62e06a 100644 --- a/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; + using System.Globalization; using System.Xml.XPath; using DotNetNuke.Common.Utilities; @@ -102,7 +103,7 @@ public override void Install() // Update LanguagePack LanguagePackController.SaveLanguagePack(this.languagePack); - this.Log.AddInfo(string.Format(Util.LANGUAGE_Registered, this.language.Text)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.LANGUAGE_Registered, this.language.Text)); // install (copy the files) by calling the base class base.Install(); @@ -204,7 +205,7 @@ private void DeleteLanguage() // { // Localization.DeleteLanguage(language); // } - this.Log.AddInfo(string.Format(Util.LANGUAGE_UnRegistered, language.Text)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.LANGUAGE_UnRegistered, language.Text)); } catch (Exception ex) { diff --git a/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs index 57c1e57d9b7..f9b6a4538fe 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; + using System.Globalization; using System.IO; using System.Xml.XPath; @@ -60,7 +61,7 @@ public override void Commit() // Add custom Attributes for this message oAppStartMessage.Attributes.Add("BusinessControllerClass", this.desktopModule.BusinessControllerClass); - oAppStartMessage.Attributes.Add("desktopModuleID", this.desktopModule.DesktopModuleID.ToString()); + oAppStartMessage.Attributes.Add("desktopModuleID", this.desktopModule.DesktopModuleID.ToString(CultureInfo.InvariantCulture)); // send it to occur on next App_Start Event EventQueueController.SendMessage(oAppStartMessage, "Application_Start_FirstRequest"); @@ -71,7 +72,7 @@ public override void Commit() { if (!string.IsNullOrEmpty(this.eventMessage.Attributes["UpgradeVersionsList"])) { - this.eventMessage.Attributes.Set("desktopModuleID", this.desktopModule.DesktopModuleID.ToString()); + this.eventMessage.Attributes.Set("desktopModuleID", this.desktopModule.DesktopModuleID.ToString(CultureInfo.InvariantCulture)); EventQueueController.SendMessage(this.eventMessage, "Application_Start"); } } @@ -85,19 +86,19 @@ public override void Commit() // Add DesktopModule to all portals if (!string.IsNullOrEmpty(this.desktopModule.AdminPage)) { - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + foreach (IPortalInfo portal in PortalController.Instance.GetPortals()) { bool createdNewPage = false, addedNewModule = false; - DesktopModuleController.AddDesktopModulePageToPortal(this.desktopModule, this.desktopModule.AdminPage, portal.PortalID, ref createdNewPage, ref addedNewModule); + DesktopModuleController.AddDesktopModulePageToPortal(this.desktopModule, this.desktopModule.AdminPage, portal.PortalId, ref createdNewPage, ref addedNewModule); if (createdNewPage) { - this.Log.AddInfo(string.Format(Util.MODULE_AdminPageAdded, this.desktopModule.AdminPage, portal.PortalID)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_AdminPageAdded, this.desktopModule.AdminPage, portal.PortalId)); } if (addedNewModule) { - this.Log.AddInfo(string.Format(Util.MODULE_AdminPagemoduleAdded, this.desktopModule.AdminPage, portal.PortalID)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_AdminPagemoduleAdded, this.desktopModule.AdminPage, portal.PortalId)); } } } @@ -110,12 +111,12 @@ public override void Commit() if (createdNewPage) { - this.Log.AddInfo(string.Format(Util.MODULE_HostPageAdded, this.desktopModule.HostPage)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_HostPageAdded, this.desktopModule.HostPage)); } if (addedNewModule) { - this.Log.AddInfo(string.Format(Util.MODULE_HostPagemoduleAdded, this.desktopModule.HostPage)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_HostPagemoduleAdded, this.desktopModule.HostPage)); } } } @@ -136,7 +137,7 @@ public override void Install() this.desktopModule.Category = this.installedDesktopModule.Category; } - // Clear ModuleControls and Module Definitions caches in case script has modifed the contents + // Clear ModuleControls and Module Definitions caches in case script has modified the contents DataCache.RemoveCache(DataCache.ModuleDefinitionCacheKey); DataCache.RemoveCache(DataCache.ModuleControlsCacheKey); @@ -145,7 +146,7 @@ public override void Install() this.desktopModule.DesktopModuleID = DesktopModuleController.SaveDesktopModule(this.desktopModule, true, false); this.Completed = true; - this.Log.AddInfo(string.Format(Util.MODULE_Registered, this.desktopModule.ModuleName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_Registered, this.desktopModule.ModuleName)); } catch (Exception ex) { @@ -252,7 +253,7 @@ private void DeleteModule() var controller = new DesktopModuleController(); - this.Log.AddInfo(string.Format(Util.MODULE_UnRegistered, tempDesktopModule.ModuleName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_UnRegistered, tempDesktopModule.ModuleName)); // remove admin/host pages if (!string.IsNullOrEmpty(tempDesktopModule.AdminPage)) @@ -283,11 +284,11 @@ private void DeleteModule() if (noOtherTabModule) { - this.Log.AddInfo(string.Format(Util.MODULE_AdminPageRemoved, tempDesktopModule.AdminPage, portal.PortalId)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_AdminPageRemoved, tempDesktopModule.AdminPage, portal.PortalId)); TabController.Instance.DeleteTab(moduleAdminTabId, portal.PortalId); } - this.Log.AddInfo(string.Format(Util.MODULE_AdminPagemoduleRemoved, tempDesktopModule.AdminPage, portal.PortalId)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_AdminPagemoduleRemoved, tempDesktopModule.AdminPage, portal.PortalId)); } } } @@ -295,8 +296,8 @@ private void DeleteModule() if (!string.IsNullOrEmpty(tempDesktopModule.HostPage)) { Upgrade.Upgrade.RemoveHostPage(tempDesktopModule.HostPage); - this.Log.AddInfo(string.Format(Util.MODULE_HostPageRemoved, tempDesktopModule.HostPage)); - this.Log.AddInfo(string.Format(Util.MODULE_HostPagemoduleRemoved, tempDesktopModule.HostPage)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_HostPageRemoved, tempDesktopModule.HostPage)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_HostPagemoduleRemoved, tempDesktopModule.HostPage)); } controller.DeleteDesktopModule(tempDesktopModule); diff --git a/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs index 3271bb1196b..4bcf70dd70d 100644 --- a/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Xml.XPath; @@ -99,7 +100,7 @@ public override void Commit() // Add Event Message if (this.eventMessage != null && !string.IsNullOrEmpty(this.eventMessage.Attributes["UpgradeVersionsList"])) { - this.eventMessage.Attributes.Set("desktopModuleID", Null.NullInteger.ToString()); + this.eventMessage.Attributes.Set("desktopModuleID", Null.NullInteger.ToString(CultureInfo.InvariantCulture)); EventQueueController.SendMessage(this.eventMessage, "Application_Start"); } @@ -309,18 +310,18 @@ public override void ReadManifest(XPathNavigator manifestNav) { if (iconFileNav.Value != string.Empty) { - if (iconFileNav.Value.StartsWith("~/")) + if (iconFileNav.Value.StartsWith("~/", StringComparison.Ordinal)) { this.Package.IconFile = iconFileNav.Value; } - else if (iconFileNav.Value.StartsWith("DesktopModules", StringComparison.InvariantCultureIgnoreCase)) + else if (iconFileNav.Value.StartsWith("DesktopModules", StringComparison.OrdinalIgnoreCase)) { - this.Package.IconFile = string.Format("~/{0}", iconFileNav.Value); + this.Package.IconFile = $"~/{iconFileNav.Value}"; } else { this.Package.IconFile = (string.IsNullOrEmpty(this.Package.FolderName) ? string.Empty : this.Package.FolderName + "/") + iconFileNav.Value; - this.Package.IconFile = (!this.Package.IconFile.StartsWith("~/")) ? "~/" + this.Package.IconFile : this.Package.IconFile; + this.Package.IconFile = (!this.Package.IconFile.StartsWith("~/", StringComparison.Ordinal)) ? "~/" + this.Package.IconFile : this.Package.IconFile; } } } @@ -503,7 +504,7 @@ private void ReadComponents(XPathNavigator manifestNav) string installOrder = componentNav.GetAttribute("installOrder", string.Empty); if (!string.IsNullOrEmpty(installOrder)) { - order = int.Parse(installOrder); + order = int.Parse(installOrder, CultureInfo.InvariantCulture); } } else @@ -511,7 +512,7 @@ private void ReadComponents(XPathNavigator manifestNav) string unInstallOrder = componentNav.GetAttribute("unInstallOrder", string.Empty); if (!string.IsNullOrEmpty(unInstallOrder)) { - order = int.Parse(unInstallOrder); + order = int.Parse(unInstallOrder, CultureInfo.InvariantCulture); } } @@ -542,7 +543,7 @@ private string ReadTextFromFile(string source) try { - return FileSystemUtils.ReadFile(this.Package.InstallerInfo.TempInstallFolder + "\\" + source); + return FileSystemUtils.ReadFile(this.Package.InstallerInfo.TempInstallFolder + @"\" + source); } catch (PathNotFoundException) { diff --git a/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs index a9b4bf70b78..d198c072c64 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.IO.Compression; using System.Xml; @@ -17,6 +18,7 @@ namespace DotNetNuke.Services.Installer.Installers public class ResourceFileInstaller : FileInstaller { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming public const string DEFAULT_MANIFESTEXT = ".manifest"; @@ -65,6 +67,7 @@ protected override void CommitFile(InstallFile insFile) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override void DeleteFile(InstallFile file) { } @@ -113,7 +116,7 @@ protected override bool InstallFile(InstallFile insFile) // Write path writer.WriteElementString( "path", - entry.FullName.Substring(0, entry.FullName.IndexOf(fileName))); + entry.FullName.Substring(0, entry.FullName.IndexOf(fileName, StringComparison.OrdinalIgnoreCase))); // Write name writer.WriteElementString("name", fileName); @@ -132,7 +135,7 @@ protected override bool InstallFile(InstallFile insFile) // Close files Element writer.WriteEndElement(); - this.Log.AddInfo(string.Format(Util.FILE_Created, entry.FullName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.FILE_Created, entry.FullName)); } // Close files Element @@ -175,23 +178,22 @@ protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFi } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override void RollbackFile(InstallFile insFile) { - using (var unzip = new ZipArchive(new FileStream(insFile.InstallerInfo.TempInstallFolder + insFile.FullName, FileMode.Open))) + using var unzip = new ZipArchive(new FileStream(insFile.InstallerInfo.TempInstallFolder + insFile.FullName, FileMode.Open)); + foreach (var entry in unzip.FileEntries()) { - foreach (var entry in unzip.FileEntries()) + // Check for Backups + if (File.Exists(insFile.BackupPath + entry.FullName)) { - // Check for Backups - if (File.Exists(insFile.BackupPath + entry.FullName)) - { - // Restore File - Util.RestoreFile(new InstallFile(entry, this.Package.InstallerInfo), this.PhysicalBasePath, this.Log); - } - else - { - // Delete File - Util.DeleteFile(entry.FullName, this.PhysicalBasePath, this.Log); - } + // Restore File + Util.RestoreFile(new InstallFile(entry, this.Package.InstallerInfo), this.PhysicalBasePath, this.Log); + } + else + { + // Delete File + Util.DeleteFile(entry.FullName, this.PhysicalBasePath, this.Log); } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs index 573582213fc..85c2ad0d8a9 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Installer.Installers using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Xml.XPath; @@ -208,7 +209,7 @@ protected override void ProcessFile(InstallFile file, XPathNavigator nav) else { // we couldn't determine the file type - this.Log.AddFailure(string.Format(Util.SQL_Manifest_BadFile, file.Name)); + this.Log.AddFailure(string.Format(CultureInfo.InvariantCulture, Util.SQL_Manifest_BadFile, file.Name)); return; } } @@ -224,6 +225,7 @@ protected override void ProcessFile(InstallFile file, XPathNavigator nav) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override void UnInstallFile(InstallFile scriptFile) { // Process the file if it is an UnInstall Script @@ -245,33 +247,33 @@ private bool ExecuteSql(InstallFile scriptFile) { bool bSuccess = true; - this.Log.AddInfo(string.Format(Util.SQL_BeginFile, scriptFile.Name)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.SQL_BeginFile, scriptFile.Name)); // read script file for installation string strScript = FileSystemUtils.ReadFile(this.PhysicalBasePath + scriptFile.FullName); - // This check needs to be included because the unicode Byte Order mark results in an extra character at the start of the file + // This check needs to be included because the Unicode Byte Order mark results in an extra character at the start of the file // The extra character - '?' - causes an error with the database. - if (strScript.StartsWith("?")) + if (strScript.StartsWith("?", StringComparison.Ordinal)) { strScript = strScript.Substring(1); } - string strSQLExceptions = DataProvider.Instance().ExecuteScript(strScript); - if (!string.IsNullOrEmpty(strSQLExceptions)) + string strSqlExceptions = DataProvider.Instance().ExecuteScript(strScript); + if (!string.IsNullOrEmpty(strSqlExceptions)) { if (this.Package.InstallerInfo.IsLegacyMode) { - this.Log.AddWarning(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); + this.Log.AddWarning(string.Format(CultureInfo.InvariantCulture, Util.SQL_Exceptions, Environment.NewLine, strSqlExceptions)); } else { - this.Log.AddFailure(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); + this.Log.AddFailure(string.Format(CultureInfo.InvariantCulture, Util.SQL_Exceptions, Environment.NewLine, strSqlExceptions)); bSuccess = false; } } - this.Log.AddInfo(string.Format(Util.SQL_EndFile, scriptFile.Name)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.SQL_EndFile, scriptFile.Name)); return bSuccess; } diff --git a/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs index a88c07efa68..38a5c87cb4a 100644 --- a/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; + using System.Globalization; using System.IO; using System.Xml.XPath; @@ -50,7 +51,7 @@ public override void Install() this.skinControl.SkinControlID = SkinControlController.SaveSkinControl(this.skinControl); this.Completed = true; - this.Log.AddInfo(string.Format(Util.MODULE_Registered, this.skinControl.ControlKey)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_Registered, this.skinControl.ControlKey)); } catch (Exception ex) { @@ -108,7 +109,7 @@ private void DeleteSkinControl() SkinControlController.DeleteSkinControl(skinControl); } - this.Log.AddInfo(string.Format(Util.MODULE_UnRegistered, skinControl.ControlKey)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.MODULE_UnRegistered, skinControl.ControlKey)); } catch (Exception ex) { diff --git a/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs index bfb179ccdc6..208f8bb11cd 100644 --- a/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; using System.Collections; + using System.Globalization; using System.IO; using System.Xml.XPath; @@ -59,13 +60,13 @@ protected override string PhysicalBasePath { get { - string physicalBasePath = this.RootPath + this.SkinRoot + "\\" + this.skinPackage.SkinName; - if (!physicalBasePath.EndsWith("\\")) + string physicalBasePath = this.RootPath + this.SkinRoot + @"\" + this.skinPackage.SkinName; + if (!physicalBasePath.EndsWith(@"\", StringComparison.Ordinal)) { - physicalBasePath += "\\"; + physicalBasePath += @"\"; } - return physicalBasePath.Replace("/", "\\"); + return physicalBasePath.Replace("/", @"\"); } } @@ -169,7 +170,7 @@ public override void Install() SkinController.UpdateSkinPackage(this.skinPackage); } - this.Log.AddInfo(string.Format(Util.SKIN_Registered, this.skinPackage.SkinName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.SKIN_Registered, this.skinPackage.SkinName)); // install (copy the files) by calling the base class base.Install(); @@ -314,7 +315,7 @@ private void DeleteSkinPackage() SkinController.DeleteSkinPackage(skinPackage); } - this.Log.AddInfo(string.Format(Util.SKIN_UnRegistered, skinPackage.SkinName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.SKIN_UnRegistered, skinPackage.SkinName)); } catch (Exception ex) { diff --git a/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs index 485b2879732..aaad0c3ee97 100644 --- a/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Installer.Installers { using System; + using System.Globalization; using System.Linq; using System.Xml.XPath; @@ -38,7 +39,7 @@ public override void Install() try { // Ensure DesktopModule Cache is cleared - DataCache.RemoveCache(string.Format(DataCache.DesktopModuleCacheKey, Null.NullInteger)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.DesktopModuleCacheKey, Null.NullInteger)); var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(this.desktopModuleName, Null.NullInteger); if (desktopModule != null) @@ -58,7 +59,7 @@ public override void Install() ExtensionUrlProviderController.SaveProvider(this.extensionUrlProvider); this.Completed = true; - this.Log.AddInfo(string.Format(Util.URLPROVIDER_Registered, this.extensionUrlProvider.ProviderName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.URLPROVIDER_Registered, this.extensionUrlProvider.ProviderName)); } catch (Exception ex) { @@ -122,7 +123,7 @@ private void DeleteProvider() { ExtensionUrlProviderController.DeleteProvider(tempUrlProvider); - this.Log.AddInfo(string.Format(Util.URLPROVIDER_UnRegistered, tempUrlProvider.ProviderName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.URLPROVIDER_UnRegistered, tempUrlProvider.ProviderName)); } } catch (Exception ex) diff --git a/DNN Platform/Library/Services/Installer/LegacyUtil.cs b/DNN Platform/Library/Services/Installer/LegacyUtil.cs index a93e36fe612..7057a2701b6 100644 --- a/DNN Platform/Library/Services/Installer/LegacyUtil.cs +++ b/DNN Platform/Library/Services/Installer/LegacyUtil.cs @@ -64,19 +64,19 @@ public static string CreateSkinManifest(string skinFolder, string skinType, stri if (Directory.Exists(Path.Combine(tempInstallFolder, "Skins"))) { // Add Skin Package Fragment - CreateSkinManifest(writer, skinFolder, "Skin", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Skins"); + CreateSkinManifest(writer, skinFolder, "Skin", tempInstallFolder.Replace(Globals.ApplicationMapPath + @"\", string.Empty), "Skins"); } if (Directory.Exists(Path.Combine(tempInstallFolder, "Containers"))) { // Add Container PAckage Fragment - CreateSkinManifest(writer, skinFolder, "Container", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Containers"); + CreateSkinManifest(writer, skinFolder, "Container", tempInstallFolder.Replace(Globals.ApplicationMapPath + @"\", string.Empty), "Containers"); } } else { // Add Package Fragment - CreateSkinManifest(writer, skinFolder, skinType, tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), string.Empty); + CreateSkinManifest(writer, skinFolder, skinType, tempInstallFolder.Replace(Globals.ApplicationMapPath + @"\", string.Empty), string.Empty); } PackageWriterBase.WriteManifestEndElement(writer); @@ -94,7 +94,7 @@ public static void ParsePackageName(PackageInfo package) ParsePackageName(package, "."); if (string.IsNullOrEmpty(package.Owner)) { - ParsePackageName(package, "\\"); + ParsePackageName(package, @"\"); } if (string.IsNullOrEmpty(package.Owner)) @@ -181,7 +181,7 @@ private static void CreateSkinManifest(XmlWriter writer, string skinFolder, stri private static void ParsePackageName(PackageInfo package, string separator) { // See if the Module is using a "Namespace" for its name - int ownerIndex = package.Name.IndexOf(separator); + int ownerIndex = package.Name.IndexOf(separator, StringComparison.Ordinal); if (ownerIndex > 0) { package.Owner = package.Name.Substring(0, ownerIndex); diff --git a/DNN Platform/Library/Services/Installer/Log/LogEntry.cs b/DNN Platform/Library/Services/Installer/Log/LogEntry.cs index 5c36b47e606..0f2995a6006 100644 --- a/DNN Platform/Library/Services/Installer/Log/LogEntry.cs +++ b/DNN Platform/Library/Services/Installer/Log/LogEntry.cs @@ -1,51 +1,51 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Installer.Log -{ +namespace DotNetNuke.Services.Installer.Log +{ using System; - /// The LogEntry class provides a single entry for the Installer Log. - [Serializable] - public class LogEntry - { - private readonly string description; - - /// - /// Initializes a new instance of the class. - /// This Constructor builds a LogEntry from its type and description. - /// - /// The description (detail) of the entry. - /// The type of LogEntry. - public LogEntry(LogType type, string description) - { - this.Type = type; - this.description = description; - } - - /// Gets the description of LogEntry. - /// A String. - public string Description - { - get - { - if (this.description == null) - { - return "..."; - } - - return this.description; - } - } - - /// Gets the type of LogEntry. - /// A LogType. + /// The LogEntry class provides a single entry for the Installer Log. + [Serializable] + public class LogEntry + { + private readonly string description; + + /// + /// Initializes a new instance of the class. + /// This Constructor builds a LogEntry from its type and description. + /// + /// The description (detail) of the entry. + /// The type of LogEntry. + public LogEntry(LogType type, string description) + { + this.Type = type; + this.description = description; + } + + /// Gets the description of LogEntry. + /// A String. + public string Description + { + get + { + if (this.description == null) + { + return "..."; + } + + return this.description; + } + } + + /// Gets the type of LogEntry. + /// A LogType. public LogType Type { get; private set; } /// - public override string ToString() - { - return string.Format("{0}: {1}", this.Type, this.Description); - } - } -} + public override string ToString() + { + return $"{this.Type}: {this.Description}"; + } + } +} diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs index 6af27fd5f02..dff91136fe7 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer.Packages { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; @@ -166,13 +167,13 @@ public static void ParsePackage(string file, string installPath, Dictionary pre /// public IList GetExtensionPackages(int portalId) { - var cacheKey = string.Format(DataCache.PackagesCacheKey, portalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PackagesCacheKey, portalId); var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.PackagesCacheTimeout, DataCache.PackagesCachePriority, portalId); return CBO.GetCachedObject>( cacheItemArgs, @@ -378,14 +379,14 @@ public IList GetPackageDependencies(FuncThe PackageCreatedEventHandler delegate defines a custom event handler for a Package Created Event. - /// The event sender. - /// The event arguments. - public delegate void PackageCreatedEventHandler(object sender, PackageCreatedEventArgs e); -} +namespace DotNetNuke.Services.Installer.Packages; + +using System.Diagnostics.CodeAnalysis; + +/// The PackageCreatedEventHandler delegate defines a custom event handler for a Package Created Event. +/// The event sender. +/// The event arguments. +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] +public delegate void PackageCreatedEventHandler(object sender, PackageCreatedEventArgs e); diff --git a/DNN Platform/Library/Services/Installer/Util.cs b/DNN Platform/Library/Services/Installer/Util.cs index 2466d1a8f7f..ccf367b152b 100644 --- a/DNN Platform/Library/Services/Installer/Util.cs +++ b/DNN Platform/Library/Services/Installer/Util.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Net; using System.Text; @@ -30,406 +31,543 @@ public class Util { // ReSharper disable InconsistentNaming [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] public const string DEFAULT_MANIFESTEXT = ".manifest"; public const string BackupInstallPackageFolder = "App_Data/ExtensionPackages/"; + +#pragma warning disable CA1707 // Identifiers should not contain underscores [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string ASSEMBLY_Added = GetLocalizedString("ASSEMBLY_Added"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string ASSEMBLY_AddedBindingRedirect = GetLocalizedString("ASSEMBLY_AddedBindingRedirect"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string ASSEMBLY_RemovedBindingRedirect = GetLocalizedString("ASSEMBLY_RemovedBindingRedirect"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string ASSEMBLY_InUse = GetLocalizedString("ASSEMBLY_InUse"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string ASSEMBLY_Registered = GetLocalizedString("ASSEMBLY_Registered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string ASSEMBLY_UnRegistered = GetLocalizedString("ASSEMBLY_UnRegistered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string ASSEMBLY_Updated = GetLocalizedString("ASSEMBLY_Updated"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string AUTHENTICATION_ReadSuccess = GetLocalizedString("AUTHENTICATION_ReadSuccess"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string AUTHENTICATION_LoginSrcMissing = GetLocalizedString("AUTHENTICATION_LoginSrcMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string AUTHENTICATION_Registered = GetLocalizedString("AUTHENTICATION_Registered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string AUTHENTICATION_SettingsSrcMissing = GetLocalizedString("AUTHENTICATION_SettingsSrcMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string AUTHENTICATION_TypeMissing = GetLocalizedString("AUTHENTICATION_TypeMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string AUTHENTICATION_UnRegistered = GetLocalizedString("AUTHENTICATION_UnRegistered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string CLEANUP_Processing = GetLocalizedString("CLEANUP_Processing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string CLEANUP_ProcessComplete = GetLocalizedString("CLEANUP_ProcessComplete"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string CLEANUP_ProcessError = GetLocalizedString("CLEANUP_ProcessError"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string COMPONENT_Installed = GetLocalizedString("COMPONENT_Installed"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string COMPONENT_Skipped = GetLocalizedString("COMPONENT_Skipped"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string COMPONENT_RolledBack = GetLocalizedString("COMPONENT_RolledBack"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string COMPONENT_RollingBack = GetLocalizedString("COMPONENT_RollingBack"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string COMPONENT_UnInstalled = GetLocalizedString("COMPONENT_UnInstalled"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string CONFIG_Committed = GetLocalizedString("CONFIG_Committed"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string CONFIG_RolledBack = GetLocalizedString("CONFIG_RolledBack"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string CONFIG_Updated = GetLocalizedString("CONFIG_Updated"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string DNN_Reading = GetLocalizedString("DNN_Reading"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string DNN_ReadingComponent = GetLocalizedString("DNN_ReadingComponent"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string DNN_ReadingPackage = GetLocalizedString("DNN_ReadingPackage"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string DNN_Success = GetLocalizedString("DNN_Success"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EVENTMESSAGE_CommandMissing = GetLocalizedString("EVENTMESSAGE_CommandMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EVENTMESSAGE_TypeMissing = GetLocalizedString("EVENTMESSAGE_TypeMissing"); [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION = GetLocalizedString("EXCEPTION"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_FileLoad = GetLocalizedString("EXCEPTION_FileLoad"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_FileRead = GetLocalizedString("EXCEPTION_FileRead"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_GlobDotDotNotSupportedInCleanup = GetLocalizedString("EXCEPTION_GlobDotDotNotSupportedInCleanup"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_InstallerCreate = GetLocalizedString("EXCEPTION_InstallerCreate"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_MissingDnn = GetLocalizedString("EXCEPTION_MissingDnn"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_MultipleDnn = GetLocalizedString("EXCEPTION_MultipleDnn"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_NameMissing = GetLocalizedString("EXCEPTION_NameMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_Type = GetLocalizedString("EXCEPTION_Type"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_TypeMissing = GetLocalizedString("EXCEPTION_TypeMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string EXCEPTION_VersionMissing = GetLocalizedString("EXCEPTION_VersionMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_CreateBackup = GetLocalizedString("FILE_CreateBackup"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_Created = GetLocalizedString("FILE_Created"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_Deleted = GetLocalizedString("FILE_Deleted"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_Found = GetLocalizedString("FILE_Found"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_Loading = GetLocalizedString("FILE_Loading"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_NotAllowed = GetLocalizedString("FILE_NotAllowed"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_NotFound = GetLocalizedString("FILE_NotFound"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_ReadSuccess = GetLocalizedString("FILE_ReadSuccess"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILE_RestoreBackup = GetLocalizedString("FILE_RestoreBackup"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILES_CreatedResources = GetLocalizedString("FILES_CreatedResources"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILES_Expanding = GetLocalizedString("FILES_Expanding"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILES_Loading = GetLocalizedString("FILES_Loading"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILES_Reading = GetLocalizedString("FILES_Reading"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FILES_ReadingEnd = GetLocalizedString("FILES_ReadingEnd"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FOLDER_Created = GetLocalizedString("FOLDER_Created"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FOLDER_Deleted = GetLocalizedString("FOLDER_Deleted"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string FOLDER_DeletedBackup = GetLocalizedString("FOLDER_DeletedBackup"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Compatibility = GetLocalizedString("INSTALL_Compatibility"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Dependencies = GetLocalizedString("INSTALL_Dependencies"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Aborted = GetLocalizedString("INSTALL_Aborted"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Failed = GetLocalizedString("INSTALL_Failed"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Committed = GetLocalizedString("INSTALL_Committed"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Namespace = GetLocalizedString("INSTALL_Namespace"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Package = GetLocalizedString("INSTALL_Package"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Permissions = GetLocalizedString("INSTALL_Permissions"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Start = GetLocalizedString("INSTALL_Start"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Success = GetLocalizedString("INSTALL_Success"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string INSTALL_Version = GetLocalizedString("INSTALL_Version"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string LANGUAGE_PortalsEnabled = GetLocalizedString("LANGUAGE_PortalsEnabled"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string LANGUAGE_Registered = GetLocalizedString("LANGUAGE_Registered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string LANGUAGE_UnRegistered = GetLocalizedString("LANGUAGE_UnRegistered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string LIBRARY_ReadSuccess = GetLocalizedString("LIBRARY_ReadSuccess"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string LIBRARY_Registered = GetLocalizedString("LIBRARY_Registered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string LIBRARY_UnRegistered = GetLocalizedString("LIBRARY_UnRegistered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_ControlKeyMissing = GetLocalizedString("MODULE_ControlKeyMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_ControlTypeMissing = GetLocalizedString("MODULE_ControlTypeMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_FriendlyNameMissing = GetLocalizedString("MODULE_FriendlyNameMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_InvalidVersion = GetLocalizedString("MODULE_InvalidVersion"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_ReadSuccess = GetLocalizedString("MODULE_ReadSuccess"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_Registered = GetLocalizedString("MODULE_Registered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_UnRegistered = GetLocalizedString("MODULE_UnRegistered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_AdminPageAdded = GetLocalizedString("MODULE_AdminPageAdded"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_AdminPagemoduleAdded = GetLocalizedString("MODULE_AdminPagemoduleAdded"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_AdminPageRemoved = GetLocalizedString("MODULE_AdminPageRemoved"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_AdminPagemoduleRemoved = GetLocalizedString("MODULE_AdminPagemoduleRemoved"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_HostPageAdded = GetLocalizedString("MODULE_HostPageAdded"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_HostPagemoduleAdded = GetLocalizedString("MODULE_HostPagemoduleAdded"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_HostPageRemoved = GetLocalizedString("MODULE_HostPageRemoved"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULE_HostPagemoduleRemoved = GetLocalizedString("MODULE_HostPagemoduleRemoved"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string PACKAGE_NoLicense = GetLocalizedString("PACKAGE_NoLicense"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string PACKAGE_NoReleaseNotes = GetLocalizedString("PACKAGE_NoReleaseNotes"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string PACKAGE_UnRecognizable = GetLocalizedString("PACKAGE_UnRecognizable"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SECURITY_Installer = GetLocalizedString("SECURITY_Installer"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SECURITY_NotRegistered = GetLocalizedString("SECURITY_NotRegistered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SKIN_BeginProcessing = GetLocalizedString("SKIN_BeginProcessing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SKIN_Installed = GetLocalizedString("SKIN_Installed"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SKIN_EndProcessing = GetLocalizedString("SKIN_EndProcessing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SKIN_Registered = GetLocalizedString("SKIN_Registered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SKIN_UnRegistered = GetLocalizedString("SKIN_UnRegistered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_Begin = GetLocalizedString("SQL_Begin"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_BeginFile = GetLocalizedString("SQL_BeginFile"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_BeginUnInstall = GetLocalizedString("SQL_BeginUnInstall"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_Committed = GetLocalizedString("SQL_Committed"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_End = GetLocalizedString("SQL_End"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_EndFile = GetLocalizedString("SQL_EndFile"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_EndUnInstall = GetLocalizedString("SQL_EndUnInstall"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_Exceptions = GetLocalizedString("SQL_Exceptions"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_Executing = GetLocalizedString("SQL_Executing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_Manifest_BadFile = GetLocalizedString("SQL_Manifest_BadFile"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_Manifest_Error = GetLocalizedString("SQL_Manifest_Error"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string SQL_RolledBack = GetLocalizedString("SQL_RolledBack"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string UNINSTALL_Start = GetLocalizedString("UNINSTALL_Start"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string UNINSTALL_StartComp = GetLocalizedString("UNINSTALL_StartComp"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string UNINSTALL_Failure = GetLocalizedString("UNINSTALL_Failure"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string UNINSTALL_Success = GetLocalizedString("UNINSTALL_Success"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string UNINSTALL_SuccessComp = GetLocalizedString("UNINSTALL_SuccessComp"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string UNINSTALL_Warnings = GetLocalizedString("UNINSTALL_Warnings"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string UNINSTALL_WarningsComp = GetLocalizedString("UNINSTALL_WarningsComp"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string URLPROVIDER_NameMissing = GetLocalizedString("URLPROVIDER_NameMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string URLPROVIDER_ReadSuccess = GetLocalizedString("URLPROVIDER_ReadSuccess"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string URLPROVIDER_Registered = GetLocalizedString("URLPROVIDER_Registered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string URLPROVIDER_TypeMissing = GetLocalizedString("URLPROVIDER_TypeMissing"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string URLPROVIDER_UnRegistered = GetLocalizedString("URLPROVIDER_UnRegistered"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string WRITER_AddFileToManifest = GetLocalizedString("WRITER_AddFileToManifest"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string WRITER_CreateArchive = GetLocalizedString("WRITER_CreateArchive"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string WRITER_CreatedManifest = GetLocalizedString("WRITER_CreatedManifest"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string WRITER_CreatedPackage = GetLocalizedString("WRITER_CreatedPackage"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string WRITER_CreatingManifest = GetLocalizedString("WRITER_CreatingManifest"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string WRITER_CreatingPackage = GetLocalizedString("WRITER_CreatingPackage"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string WRITER_SavedFile = GetLocalizedString("WRITER_SavedFile"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string WRITER_SaveFileError = GetLocalizedString("WRITER_SaveFileError"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] - public static readonly string REGEX_Version = "\\d{2}.\\d{2}.\\d{2}"; + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] + public static readonly string REGEX_Version = @"\d{2}.\d{2}.\d{2}"; +#pragma warning restore CA1707 // ReSharper restore InconsistentNaming @@ -452,7 +590,7 @@ public static void DeleteFile(string fileName, string basePath, Logger log) if (File.Exists(fullFileName)) { RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.DeleteFile(fullFileName), "Delete file " + fullFileName); - log.AddInfo(string.Format(FILE_Deleted, fileName)); + log.AddInfo(string.Format(CultureInfo.InvariantCulture, FILE_Deleted, fileName)); string folderName = Path.GetDirectoryName(fullFileName); if (folderName != null) { @@ -479,9 +617,11 @@ public static bool IsFileValid(InstallFile file, string packageWhiteList) FileExtensionWhitelist whiteList = Host.AllowedExtensionWhitelist; // Check the White Lists - string strExtension = file.Extension.ToLowerInvariant(); - if (strExtension == "dnn" || whiteList.IsAllowedExtension(strExtension) || packageWhiteList.Contains(strExtension) || - (packageWhiteList.Contains("*dataprovider") && strExtension.EndsWith("dataprovider"))) + string strExtension = file.Extension; + if (string.Equals(strExtension, "dnn", StringComparison.OrdinalIgnoreCase) + || whiteList.IsAllowedExtension(strExtension) + || packageWhiteList.Contains(strExtension, StringComparison.OrdinalIgnoreCase) + || (packageWhiteList.Contains("*dataprovider", StringComparison.OrdinalIgnoreCase) && strExtension.EndsWith("dataprovider", StringComparison.OrdinalIgnoreCase))) { // Install File is Valid return true; @@ -583,7 +723,7 @@ public static string ParsePackageIconFileName(PackageInfo package) var filename = string.Empty; if ((package.IconFile != null) && (package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Auth_System", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase))) { - filename = package.IconFile.StartsWith("~/" + package.FolderName) ? package.IconFile.Remove(0, ("~/" + package.FolderName).Length).TrimStart('/') : package.IconFile; + filename = package.IconFile.StartsWith("~/" + package.FolderName, StringComparison.OrdinalIgnoreCase) ? package.IconFile.Remove(0, ("~/" + package.FolderName).Length).TrimStart('/') : package.IconFile; } return filename; @@ -594,7 +734,7 @@ public static string ParsePackageIconFile(PackageInfo package) var iconFile = string.Empty; if ((package.IconFile != null) && (package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Auth_System", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase))) { - iconFile = !package.IconFile.StartsWith("~/") ? "~/" + package.FolderName + "/" + package.IconFile : package.IconFile; + iconFile = !package.IconFile.StartsWith("~/", StringComparison.Ordinal) ? $"~/{package.FolderName}/{package.IconFile}" : package.IconFile; } return iconFile; @@ -675,7 +815,7 @@ public static void RestoreFile(InstallFile installFile, string basePath, Logger // Copy File back over install file FileSystemUtils.CopyFile(backupFileName, fullFileName); - log.AddInfo(string.Format(FILE_RestoreBackup, installFile.FullName)); + log.AddInfo(string.Format(CultureInfo.InvariantCulture, FILE_RestoreBackup, installFile.FullName)); } /// @@ -831,7 +971,7 @@ public static WebResponse GetExternalRequest(string url, byte[] data, string use if (!doPOST && data != null && data.Length > 0) { string restoftheurl = Encoding.ASCII.GetString(data); - if (url != null && url.IndexOf("?") <= 0) + if (url != null && url.IndexOf("?", StringComparison.Ordinal) <= 0) { url = url + "?"; } @@ -871,7 +1011,7 @@ public static WebResponse GetExternalRequest(string url, byte[] data, string use wreq.Credentials = new NetworkCredential(username, password); } - if (doPOST && data != null && data.Length > 0) + if (doPOST && data is { Length: > 0, }) { wreq.ContentType = "application/x-www-form-urlencoded"; Stream request = wreq.GetRequestStream(); @@ -880,26 +1020,26 @@ public static WebResponse GetExternalRequest(string url, byte[] data, string use } filename = string.Empty; - WebResponse wrsp = wreq.GetResponse(); - string cd = wrsp.Headers["Content-Disposition"]; - if (cd != null && cd.Trim() != string.Empty && cd.StartsWith("attachment")) + WebResponse response = wreq.GetResponse(); + string cd = response.Headers["Content-Disposition"]; + if (cd != null && cd.Trim() != string.Empty && cd.StartsWith("attachment", StringComparison.OrdinalIgnoreCase)) { - if (cd.IndexOf("filename") > -1 && cd.Substring(cd.IndexOf("filename")).IndexOf("=") > -1) + if (cd.IndexOf("filename", StringComparison.OrdinalIgnoreCase) > -1 && cd.Substring(cd.IndexOf("filename", StringComparison.OrdinalIgnoreCase)).IndexOf("=", StringComparison.Ordinal) > -1) { - string filenameParam = cd.Substring(cd.IndexOf("filename")); + string filenameParam = cd.Substring(cd.IndexOf("filename", StringComparison.OrdinalIgnoreCase)); - if (filenameParam.IndexOf("\"") > -1) + if (filenameParam.IndexOf("\"", StringComparison.Ordinal) > -1) { - filename = filenameParam.Substring(filenameParam.IndexOf("\"") + 1).TrimEnd(Convert.ToChar("\"")).TrimEnd(Convert.ToChar("\\")); + filename = filenameParam.Substring(filenameParam.IndexOf("\"", StringComparison.Ordinal) + 1).TrimEnd('"').TrimEnd('\\'); } else { - filename = filenameParam.Substring(filenameParam.IndexOf("=") + 1); + filename = filenameParam.Substring(filenameParam.IndexOf("=", StringComparison.Ordinal) + 1); } } } - return wrsp; + return response; } public static void DeployExtension(WebResponse wr, string myfile, string installFolder) @@ -966,7 +1106,7 @@ public static void BackupFile(InstallFile installFile, string basePath, Logger l // Copy file to the backup location RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.CopyFile(fullFileName, backupFileName), "Backup file " + fullFileName); - log.AddInfo(string.Format(FILE_CreateBackup, installFile.FullName)); + log.AddInfo(string.Format(CultureInfo.InvariantCulture, FILE_CreateBackup, installFile.FullName)); } /// The CopyFile method copies a file from the temporary extract location. @@ -978,20 +1118,20 @@ public static void CopyFile(InstallFile installFile, string basePath, Logger log string filePath = Path.Combine(basePath, installFile.Path); string fullFileName = Path.Combine(basePath, installFile.FullName); - // create the folder if neccessary + // create the folder if necessary if (!Directory.Exists(filePath)) { - log.AddInfo(string.Format(FOLDER_Created, filePath)); + log.AddInfo(string.Format(CultureInfo.InvariantCulture, FOLDER_Created, filePath)); Directory.CreateDirectory(filePath); } // Copy file from temp location RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.CopyFile(installFile.TempFileName, fullFileName), "Copy file to " + fullFileName); - log.AddInfo(string.Format(FILE_Created, installFile.FullName)); + log.AddInfo(string.Format(CultureInfo.InvariantCulture, FILE_Created, installFile.FullName)); } - /// The StreamToStream method reads a source stream and wrtites it to a destination stream. + /// The StreamToStream method reads a source stream and writes it to a destination stream. /// The Source Stream. /// The Destination Stream. private static void StreamToStream(Stream sourceStream, Stream destStream) @@ -1015,19 +1155,19 @@ private static void TryDeleteFolder(DirectoryInfo folder, Logger log) if (folder.GetFiles().Length == 0 && folder.GetDirectories().Length == 0) { folder.Delete(); - log.AddInfo(string.Format(FOLDER_Deleted, folder.Name)); + log.AddInfo(string.Format(CultureInfo.InvariantCulture, FOLDER_Deleted, folder.Name)); TryDeleteFolder(folder.Parent, log); } } - private static string ValidateNode(string propValue, bool isRequired, Logger log, string logmessage, string defaultValue) + private static string ValidateNode(string propValue, bool isRequired, Logger log, string logMessage, string defaultValue) { if (string.IsNullOrEmpty(propValue)) { if (isRequired) { // Log Error - log.AddFailure(logmessage); + log.AddFailure(logMessage); } else { diff --git a/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs index a9fbfc68df3..badce29e6df 100644 --- a/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Installer.Writers { using System.Collections.Generic; + using System.Globalization; using System.Xml; using DotNetNuke.Common.Utilities; @@ -116,12 +117,12 @@ public virtual void WriteManifest(XmlWriter writer) writer.WriteAttributeString("type", this.ComponentType); if (this.InstallOrder > Null.NullInteger) { - writer.WriteAttributeString("installOrder", this.InstallOrder.ToString()); + writer.WriteAttributeString("installOrder", this.InstallOrder.ToString(CultureInfo.InvariantCulture)); } if (this.UnInstallOrder > Null.NullInteger) { - writer.WriteAttributeString("unInstallOrder", this.UnInstallOrder.ToString()); + writer.WriteAttributeString("unInstallOrder", this.UnInstallOrder.ToString(CultureInfo.InvariantCulture)); } // Start files element @@ -152,14 +153,14 @@ public virtual void WriteManifest(XmlWriter writer) /// The WriteCustomManifest method writes the custom manifest items (that subclasses /// of FileComponentWriter may need). /// - /// The Xmlwriter to use. + /// The XmlWriter to use. protected virtual void WriteCustomManifest(XmlWriter writer) { } protected virtual void WriteFileElement(XmlWriter writer, InstallFile file) { - this.Log.AddInfo(string.Format(Util.WRITER_AddFileToManifest, file.Name)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.WRITER_AddFileToManifest, file.Name)); // Start file Element writer.WriteStartElement(this.ItemNodeName); @@ -172,7 +173,7 @@ protected virtual void WriteFileElement(XmlWriter writer, InstallFile file) { if (file.Path.ToLowerInvariant().Contains(this.basePath.ToLowerInvariant())) { - path = file.Path.ToLowerInvariant().Replace(this.basePath.ToLowerInvariant() + "\\", string.Empty); + path = file.Path.ToLowerInvariant().Replace(this.basePath.ToLowerInvariant() + @"\", string.Empty); } } diff --git a/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs b/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs index 7371b7b2169..885c28cd63e 100644 --- a/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs @@ -1,560 +1,560 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Installer.Writers -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Xml; - using System.Xml.XPath; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Services.Installer.Packages; - using DotNetNuke.Services.Localization; - - /// The LanguagePackWriter class. - public class LanguagePackWriter : PackageWriterBase - { - private bool isCore = Null.NullBoolean; - private Locale language; - private LanguagePackInfo languagePack; - - /// Initializes a new instance of the class. - /// The package info. - public LanguagePackWriter(PackageInfo package) - : base(package) - { - this.languagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); - if (this.LanguagePack != null) - { - this.language = LocaleController.Instance.GetLocale(this.languagePack.LanguageID); - if (this.LanguagePack.PackageType == LanguagePackType.Core) - { - this.BasePath = Null.NullString; - } - else - { - // Get the BasePath of the Dependent Package - PackageInfo dependendentPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == this.LanguagePack.DependentPackageID); - PackageWriterBase dependentPackageWriter = PackageWriterFactory.GetWriter(dependendentPackage); - this.BasePath = dependentPackageWriter.BasePath; - } - } - else - { - this.BasePath = Null.NullString; - } - } - - /// Initializes a new instance of the class. - /// The XPath navigator for the manifest section. - /// The installer info. - public LanguagePackWriter(XPathNavigator manifestNav, InstallerInfo installer) - { - this.language = new Locale(); - XPathNavigator cultureNav = manifestNav.SelectSingleNode("Culture"); - this.language.Text = Util.ReadAttribute(cultureNav, "DisplayName"); - this.language.Code = Util.ReadAttribute(cultureNav, "Code"); - this.language.Fallback = Localization.SystemLocale; - - // Create a Package - this.Package = new PackageInfo(installer); - this.Package.Name = this.Language.Text; - this.Package.FriendlyName = this.Language.Text; - this.Package.Description = Null.NullString; - this.Package.Version = new Version(1, 0, 0); - this.Package.License = Util.PACKAGE_NoLicense; - - this.ReadLegacyManifest(manifestNav); - - if (this.isCore) - { - this.Package.PackageType = "CoreLanguagePack"; - } - else - { - this.Package.PackageType = "ExtensionLanguagePack"; - } - - this.BasePath = Null.NullString; - } - - /// Initializes a new instance of the class. - /// The locale. - /// The package info. - public LanguagePackWriter(Locale language, PackageInfo package) - : base(package) - { - this.language = language; - this.BasePath = Null.NullString; - } - - /// - public override bool IncludeAssemblies - { - get - { - return false; - } - } - - /// Gets or sets the associated Language. - /// An Locale object. - public Locale Language - { - get - { - return this.language; - } - - set - { - this.language = value; - } - } - - /// Gets or sets the associated Language Pack. - /// An LanguagePackInfo object. - public LanguagePackInfo LanguagePack - { - get - { - return this.languagePack; - } - - set - { - this.languagePack = value; - } - } - - /// - protected override void GetFiles(bool includeSource, bool includeAppCode) - { - // Language file starts at the root - this.ParseFolder(Path.Combine(Globals.ApplicationMapPath, this.BasePath), Globals.ApplicationMapPath); - } - - /// - protected override void ParseFiles(DirectoryInfo folder, string rootPath) - { - if (this.LanguagePack.PackageType == LanguagePackType.Core) - { - if ((folder.FullName.ToLowerInvariant().Contains("desktopmodules") && !folder.FullName.ToLowerInvariant().Contains("admin")) || folder.FullName.ToLowerInvariant().Contains("providers")) - { - return; - } - - if (folder.FullName.ToLowerInvariant().Contains("install") && folder.FullName.ToLowerInvariant().Contains("temp")) - { - return; - } - } - - if (folder.Name.Equals("app_localresources", StringComparison.OrdinalIgnoreCase) || folder.Name.Equals("app_globalresources", StringComparison.OrdinalIgnoreCase) || folder.Name.Equals("_default", StringComparison.OrdinalIgnoreCase)) - { - // Add the Files in the Folder - FileInfo[] files = folder.GetFiles(); - foreach (FileInfo file in files) - { - string filePath = folder.FullName.Replace(rootPath, string.Empty); - if (filePath.StartsWith("\\")) - { - filePath = filePath.Substring(1); - } - - if (file.Name.Contains(this.Language.Code, StringComparison.OrdinalIgnoreCase) || (this.Language.Code.Equals("en-us", StringComparison.OrdinalIgnoreCase) && !file.Name.Contains("-"))) - { - this.AddFile(Path.Combine(filePath, file.Name)); - } - } - } - } - - /// - protected override void WriteFilesToManifest(XmlWriter writer) - { - LanguageComponentWriter languageFileWriter; - if (this.LanguagePack == null) - { - languageFileWriter = new LanguageComponentWriter(this.Language, this.BasePath, this.Files, this.Package); - } - else - { - languageFileWriter = new LanguageComponentWriter(this.LanguagePack, this.BasePath, this.Files, this.Package); - } - - languageFileWriter.WriteManifest(writer); - } - - private void ReadLegacyManifest(XPathNavigator manifestNav) - { - string fileName = Null.NullString; - string filePath = Null.NullString; - string sourceFileName = Null.NullString; - string resourcetype = Null.NullString; - string moduleName = Null.NullString; - foreach (XPathNavigator fileNav in manifestNav.Select("Files/File")) - { - fileName = Util.ReadAttribute(fileNav, "FileName").ToLowerInvariant(); - resourcetype = Util.ReadAttribute(fileNav, "FileType"); - moduleName = Util.ReadAttribute(fileNav, "ModuleName").ToLowerInvariant(); - sourceFileName = Path.Combine(resourcetype, Path.Combine(moduleName, fileName)); - string extendedExtension = "." + this.Language.Code.ToLowerInvariant() + ".resx"; - switch (resourcetype) - { - case "GlobalResource": - filePath = "App_GlobalResources"; - this.isCore = true; - break; - case "ControlResource": - filePath = "Controls\\App_LocalResources"; - break; - case "AdminResource": - this.isCore = true; - switch (moduleName) - { - case "authentication": - filePath = "DesktopModules\\Admin\\Authentication\\App_LocalResources"; - break; - case "controlpanel": - filePath = "Admin\\ControlPanel\\App_LocalResources"; - break; - case "files": - filePath = "DesktopModules\\Admin\\FileManager\\App_LocalResources"; - break; - case "host": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "authentication.ascx": - filePath = string.Empty; - break; - case "friendlyurls.ascx": - filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; - break; - case "hostsettings.ascx": - filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; - break; - case "requestfilters.ascx": - filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; - break; - } - - break; - case "lists": - filePath = "DesktopModules\\Admin\\Lists\\App_LocalResources"; - break; - case "localization": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "languageeditor.ascx": - filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; - break; - case "languageeditorext.ascx": - filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; - break; - case "timezoneeditor.ascx": - filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; - break; - case "resourceverifier.ascx": - filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; - break; - default: - filePath = string.Empty; - break; - } - - break; - case "logging": - filePath = "DesktopModules\\Admin\\LogViewer\\App_LocalResources"; - break; - case "moduledefinitions": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "editmodulecontrol.ascx": - filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; - break; - case "importmoduledefinition.ascx": - filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; - break; - case "timezoneeditor.ascx": - filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; - break; - default: - filePath = string.Empty; - break; - } - - break; - case "modules": - filePath = "Admin\\Modules\\App_LocalResources"; - break; - case "packages": - filePath = "DesktopModules\\Admin\\Extensions\\App_LocalResources"; - break; - case "portal": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "editportalalias.ascx": - filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; - break; - case "portalalias.ascx": - filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; - break; - case "portals.ascx": - filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; - break; - case "privacy.ascx": - filePath = "Admin\\Portal\\App_LocalResources"; - break; - case "signup.ascx": - filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; - break; - case "sitesettings.ascx": - filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; - break; - case "sitewizard.ascx": - filePath = "DesktopModules\\Admin\\SiteWizard\\App_LocalResources"; - break; - case "sql.ascx": - filePath = "DesktopModules\\Admin\\SQL\\App_LocalResources"; - break; - case "systemmessages.ascx": - filePath = string.Empty; - break; - case "template.ascx": - filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; - break; - case "terms.ascx": - filePath = "Admin\\Portal\\App_LocalResources"; - break; - } - - break; - case "scheduling": - filePath = "DesktopModules\\Admin\\Scheduler\\App_LocalResources"; - break; - case "search": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "inputsettings.ascx": - filePath = "DesktopModules\\Admin\\SearchInput\\App_LocalResources"; - break; - case "resultssettings.ascx": - filePath = "DesktopModules\\Admin\\SearchResults\\App_LocalResources"; - break; - case "searchadmin.ascx": - filePath = "DesktopModules\\Admin\\SearchAdmin\\App_LocalResources"; - break; - case "searchinput.ascx": - filePath = "DesktopModules\\Admin\\SearchInput\\App_LocalResources"; - break; - case "searchresults.ascx": - filePath = "DesktopModules\\Admin\\SearchResults\\App_LocalResources"; - break; - } - - break; - case "security": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "accessdenied.ascx": - filePath = "Admin\\Security\\App_LocalResources"; - break; - case "authenticationsettings.ascx": - filePath = string.Empty; - break; - case "editgroups.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "editroles.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "register.ascx": - filePath = string.Empty; - break; - case "roles.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "securityroles.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "sendpassword.ascx": - filePath = "Admin\\Security\\App_LocalResources"; - break; - case "signin.ascx": - filePath = string.Empty; - break; - } - - break; - case "skins": - filePath = "Admin\\Skins\\App_LocalResources"; - break; - case "syndication": - filePath = "DesktopModules\\Admin\\FeedExplorer\\App_LocalResources"; - break; - case "tabs": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "export.ascx": - filePath = "Admin\\Tabs\\App_LocalResources"; - break; - case "import.ascx": - filePath = "Admin\\Tabs\\App_LocalResources"; - break; - case "managetabs.ascx": - filePath = "DesktopModules\\Admin\\Tabs\\App_LocalResources"; - break; - case "recyclebin.ascx": - filePath = "DesktopModules\\Admin\\RecycleBin\\App_LocalResources"; - break; - case "tabs.ascx": - filePath = "DesktopModules\\Admin\\Tabs\\App_LocalResources"; - break; - } - - break; - case "users": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "bulkemail.ascx": - filePath = "DesktopModules\\Admin\\Newsletters\\App_LocalResources"; - fileName = "Newsletter.ascx" + extendedExtension; - break; - case "editprofiledefinition.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "manageusers.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "memberservices.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "membership.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "password.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "profile.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "profiledefinitions.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "user.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "users.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "usersettings.ascx": - filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; - break; - case "viewprofile.ascx": - filePath = "Admin\\Users\\App_LocalResources"; - break; - } - - break; - case "vendors": - switch (fileName.Replace(extendedExtension, string.Empty)) - { - case "adsense.ascx": - filePath = string.Empty; - break; - case "editadsense.ascx": - filePath = string.Empty; - break; - case "affiliates.ascx": - filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; - break; - case "banneroptions.ascx": - filePath = "DesktopModules\\Admin\\Banners\\App_LocalResources"; - break; - case "banners.ascx": - filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; - break; - case "displaybanners.ascx": - filePath = "DesktopModules\\Admin\\Banners\\App_LocalResources"; - break; - case "editaffiliate.ascx": - filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; - break; - case "editbanner.ascx": - filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; - break; - case "editvendors.ascx": - filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; - break; - case "vendors.ascx": - filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; - break; - } - - break; - } - - break; - case "LocalResource": - filePath = Path.Combine("DesktopModules", Path.Combine(moduleName, "App_LocalResources")); - - // Two assumptions are made here - // 1. Core files appear in the package before extension files - // 2. Module packages only include one module - if (!this.isCore && this.languagePack == null) - { - // Check if language is installed - Locale locale = LocaleController.Instance.GetLocale(this.language.Code); - if (locale == null) - { - this.LegacyError = "CoreLanguageError"; - } - else - { - // Attempt to figure out the Extension - foreach (var kvp in DesktopModuleController.GetDesktopModules(Null.NullInteger)) - { - if (kvp.Value.FolderName.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) - { - // Found Module - Get Package - var dependentPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == kvp.Value.PackageID); - this.Package.Name += "_" + dependentPackage.Name; - this.Package.FriendlyName += " " + dependentPackage.FriendlyName; - this.languagePack = new LanguagePackInfo - { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Installer.Writers +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + + /// The LanguagePackWriter class. + public class LanguagePackWriter : PackageWriterBase + { + private bool isCore = Null.NullBoolean; + private Locale language; + private LanguagePackInfo languagePack; + + /// Initializes a new instance of the class. + /// The package info. + public LanguagePackWriter(PackageInfo package) + : base(package) + { + this.languagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); + if (this.LanguagePack != null) + { + this.language = LocaleController.Instance.GetLocale(this.languagePack.LanguageID); + if (this.LanguagePack.PackageType == LanguagePackType.Core) + { + this.BasePath = Null.NullString; + } + else + { + // Get the BasePath of the Dependent Package + PackageInfo dependendentPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == this.LanguagePack.DependentPackageID); + PackageWriterBase dependentPackageWriter = PackageWriterFactory.GetWriter(dependendentPackage); + this.BasePath = dependentPackageWriter.BasePath; + } + } + else + { + this.BasePath = Null.NullString; + } + } + + /// Initializes a new instance of the class. + /// The XPath navigator for the manifest section. + /// The installer info. + public LanguagePackWriter(XPathNavigator manifestNav, InstallerInfo installer) + { + this.language = new Locale(); + XPathNavigator cultureNav = manifestNav.SelectSingleNode("Culture"); + this.language.Text = Util.ReadAttribute(cultureNav, "DisplayName"); + this.language.Code = Util.ReadAttribute(cultureNav, "Code"); + this.language.Fallback = Localization.SystemLocale; + + // Create a Package + this.Package = new PackageInfo(installer); + this.Package.Name = this.Language.Text; + this.Package.FriendlyName = this.Language.Text; + this.Package.Description = Null.NullString; + this.Package.Version = new Version(1, 0, 0); + this.Package.License = Util.PACKAGE_NoLicense; + + this.ReadLegacyManifest(manifestNav); + + if (this.isCore) + { + this.Package.PackageType = "CoreLanguagePack"; + } + else + { + this.Package.PackageType = "ExtensionLanguagePack"; + } + + this.BasePath = Null.NullString; + } + + /// Initializes a new instance of the class. + /// The locale. + /// The package info. + public LanguagePackWriter(Locale language, PackageInfo package) + : base(package) + { + this.language = language; + this.BasePath = Null.NullString; + } + + /// + public override bool IncludeAssemblies + { + get + { + return false; + } + } + + /// Gets or sets the associated Language. + /// An Locale object. + public Locale Language + { + get + { + return this.language; + } + + set + { + this.language = value; + } + } + + /// Gets or sets the associated Language Pack. + /// An LanguagePackInfo object. + public LanguagePackInfo LanguagePack + { + get + { + return this.languagePack; + } + + set + { + this.languagePack = value; + } + } + + /// + protected override void GetFiles(bool includeSource, bool includeAppCode) + { + // Language file starts at the root + this.ParseFolder(Path.Combine(Globals.ApplicationMapPath, this.BasePath), Globals.ApplicationMapPath); + } + + /// + protected override void ParseFiles(DirectoryInfo folder, string rootPath) + { + if (this.LanguagePack.PackageType == LanguagePackType.Core) + { + if ((folder.FullName.ToLowerInvariant().Contains("desktopmodules") && !folder.FullName.ToLowerInvariant().Contains("admin")) || folder.FullName.ToLowerInvariant().Contains("providers")) + { + return; + } + + if (folder.FullName.ToLowerInvariant().Contains("install") && folder.FullName.ToLowerInvariant().Contains("temp")) + { + return; + } + } + + if (folder.Name.Equals("app_localresources", StringComparison.OrdinalIgnoreCase) || folder.Name.Equals("app_globalresources", StringComparison.OrdinalIgnoreCase) || folder.Name.Equals("_default", StringComparison.OrdinalIgnoreCase)) + { + // Add the Files in the Folder + FileInfo[] files = folder.GetFiles(); + foreach (FileInfo file in files) + { + string filePath = folder.FullName.Replace(rootPath, string.Empty); + if (filePath.StartsWith(@"\", StringComparison.Ordinal)) + { + filePath = filePath.Substring(1); + } + + if (file.Name.Contains(this.Language.Code, StringComparison.OrdinalIgnoreCase) || (this.Language.Code.Equals("en-us", StringComparison.OrdinalIgnoreCase) && !file.Name.Contains("-"))) + { + this.AddFile(Path.Combine(filePath, file.Name)); + } + } + } + } + + /// + protected override void WriteFilesToManifest(XmlWriter writer) + { + LanguageComponentWriter languageFileWriter; + if (this.LanguagePack == null) + { + languageFileWriter = new LanguageComponentWriter(this.Language, this.BasePath, this.Files, this.Package); + } + else + { + languageFileWriter = new LanguageComponentWriter(this.LanguagePack, this.BasePath, this.Files, this.Package); + } + + languageFileWriter.WriteManifest(writer); + } + + private void ReadLegacyManifest(XPathNavigator manifestNav) + { + string fileName = Null.NullString; + string filePath = Null.NullString; + string sourceFileName = Null.NullString; + string resourcetype = Null.NullString; + string moduleName = Null.NullString; + foreach (XPathNavigator fileNav in manifestNav.Select("Files/File")) + { + fileName = Util.ReadAttribute(fileNav, "FileName").ToLowerInvariant(); + resourcetype = Util.ReadAttribute(fileNav, "FileType"); + moduleName = Util.ReadAttribute(fileNav, "ModuleName").ToLowerInvariant(); + sourceFileName = Path.Combine(resourcetype, Path.Combine(moduleName, fileName)); + string extendedExtension = "." + this.Language.Code.ToLowerInvariant() + ".resx"; + switch (resourcetype) + { + case "GlobalResource": + filePath = "App_GlobalResources"; + this.isCore = true; + break; + case "ControlResource": + filePath = "Controls\\App_LocalResources"; + break; + case "AdminResource": + this.isCore = true; + switch (moduleName) + { + case "authentication": + filePath = "DesktopModules\\Admin\\Authentication\\App_LocalResources"; + break; + case "controlpanel": + filePath = "Admin\\ControlPanel\\App_LocalResources"; + break; + case "files": + filePath = "DesktopModules\\Admin\\FileManager\\App_LocalResources"; + break; + case "host": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "authentication.ascx": + filePath = string.Empty; + break; + case "friendlyurls.ascx": + filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; + break; + case "hostsettings.ascx": + filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; + break; + case "requestfilters.ascx": + filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; + break; + } + + break; + case "lists": + filePath = "DesktopModules\\Admin\\Lists\\App_LocalResources"; + break; + case "localization": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "languageeditor.ascx": + filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; + break; + case "languageeditorext.ascx": + filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; + break; + case "timezoneeditor.ascx": + filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; + break; + case "resourceverifier.ascx": + filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; + break; + default: + filePath = string.Empty; + break; + } + + break; + case "logging": + filePath = "DesktopModules\\Admin\\LogViewer\\App_LocalResources"; + break; + case "moduledefinitions": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "editmodulecontrol.ascx": + filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; + break; + case "importmoduledefinition.ascx": + filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; + break; + case "timezoneeditor.ascx": + filePath = "DesktopModules\\Admin\\Extensions\\Editors\\App_LocalResources"; + break; + default: + filePath = string.Empty; + break; + } + + break; + case "modules": + filePath = "Admin\\Modules\\App_LocalResources"; + break; + case "packages": + filePath = "DesktopModules\\Admin\\Extensions\\App_LocalResources"; + break; + case "portal": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "editportalalias.ascx": + filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; + break; + case "portalalias.ascx": + filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; + break; + case "portals.ascx": + filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; + break; + case "privacy.ascx": + filePath = "Admin\\Portal\\App_LocalResources"; + break; + case "signup.ascx": + filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; + break; + case "sitesettings.ascx": + filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; + break; + case "sitewizard.ascx": + filePath = "DesktopModules\\Admin\\SiteWizard\\App_LocalResources"; + break; + case "sql.ascx": + filePath = "DesktopModules\\Admin\\SQL\\App_LocalResources"; + break; + case "systemmessages.ascx": + filePath = string.Empty; + break; + case "template.ascx": + filePath = "DesktopModules\\Admin\\Portals\\App_LocalResources"; + break; + case "terms.ascx": + filePath = "Admin\\Portal\\App_LocalResources"; + break; + } + + break; + case "scheduling": + filePath = "DesktopModules\\Admin\\Scheduler\\App_LocalResources"; + break; + case "search": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "inputsettings.ascx": + filePath = "DesktopModules\\Admin\\SearchInput\\App_LocalResources"; + break; + case "resultssettings.ascx": + filePath = "DesktopModules\\Admin\\SearchResults\\App_LocalResources"; + break; + case "searchadmin.ascx": + filePath = "DesktopModules\\Admin\\SearchAdmin\\App_LocalResources"; + break; + case "searchinput.ascx": + filePath = "DesktopModules\\Admin\\SearchInput\\App_LocalResources"; + break; + case "searchresults.ascx": + filePath = "DesktopModules\\Admin\\SearchResults\\App_LocalResources"; + break; + } + + break; + case "security": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "accessdenied.ascx": + filePath = "Admin\\Security\\App_LocalResources"; + break; + case "authenticationsettings.ascx": + filePath = string.Empty; + break; + case "editgroups.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "editroles.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "register.ascx": + filePath = string.Empty; + break; + case "roles.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "securityroles.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "sendpassword.ascx": + filePath = "Admin\\Security\\App_LocalResources"; + break; + case "signin.ascx": + filePath = string.Empty; + break; + } + + break; + case "skins": + filePath = "Admin\\Skins\\App_LocalResources"; + break; + case "syndication": + filePath = "DesktopModules\\Admin\\FeedExplorer\\App_LocalResources"; + break; + case "tabs": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "export.ascx": + filePath = "Admin\\Tabs\\App_LocalResources"; + break; + case "import.ascx": + filePath = "Admin\\Tabs\\App_LocalResources"; + break; + case "managetabs.ascx": + filePath = "DesktopModules\\Admin\\Tabs\\App_LocalResources"; + break; + case "recyclebin.ascx": + filePath = "DesktopModules\\Admin\\RecycleBin\\App_LocalResources"; + break; + case "tabs.ascx": + filePath = "DesktopModules\\Admin\\Tabs\\App_LocalResources"; + break; + } + + break; + case "users": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "bulkemail.ascx": + filePath = "DesktopModules\\Admin\\Newsletters\\App_LocalResources"; + fileName = "Newsletter.ascx" + extendedExtension; + break; + case "editprofiledefinition.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "manageusers.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "memberservices.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "membership.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "password.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "profile.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "profiledefinitions.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "user.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "users.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "usersettings.ascx": + filePath = "DesktopModules\\Admin\\Security\\App_LocalResources"; + break; + case "viewprofile.ascx": + filePath = "Admin\\Users\\App_LocalResources"; + break; + } + + break; + case "vendors": + switch (fileName.Replace(extendedExtension, string.Empty)) + { + case "adsense.ascx": + filePath = string.Empty; + break; + case "editadsense.ascx": + filePath = string.Empty; + break; + case "affiliates.ascx": + filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; + break; + case "banneroptions.ascx": + filePath = "DesktopModules\\Admin\\Banners\\App_LocalResources"; + break; + case "banners.ascx": + filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; + break; + case "displaybanners.ascx": + filePath = "DesktopModules\\Admin\\Banners\\App_LocalResources"; + break; + case "editaffiliate.ascx": + filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; + break; + case "editbanner.ascx": + filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; + break; + case "editvendors.ascx": + filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; + break; + case "vendors.ascx": + filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; + break; + } + + break; + } + + break; + case "LocalResource": + filePath = Path.Combine("DesktopModules", Path.Combine(moduleName, "App_LocalResources")); + + // Two assumptions are made here + // 1. Core files appear in the package before extension files + // 2. Module packages only include one module + if (!this.isCore && this.languagePack == null) + { + // Check if language is installed + Locale locale = LocaleController.Instance.GetLocale(this.language.Code); + if (locale == null) + { + this.LegacyError = "CoreLanguageError"; + } + else + { + // Attempt to figure out the Extension + foreach (var kvp in DesktopModuleController.GetDesktopModules(Null.NullInteger)) + { + if (kvp.Value.FolderName.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) + { + // Found Module - Get Package + var dependentPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == kvp.Value.PackageID); + this.Package.Name += "_" + dependentPackage.Name; + this.Package.FriendlyName += " " + dependentPackage.FriendlyName; + this.languagePack = new LanguagePackInfo + { DependentPackageID = dependentPackage.PackageID, - LanguageID = locale.LanguageId, - }; - break; - } - } - - if (this.languagePack == null) - { - this.LegacyError = "DependencyError"; - } - } - } - - break; - case "ProviderResource": - filePath = Path.Combine("Providers", Path.Combine(moduleName, "App_LocalResources")); - break; - case "InstallResource": - filePath = "Install\\App_LocalResources"; - break; - } - - if (!string.IsNullOrEmpty(filePath)) - { - this.AddFile(Path.Combine(filePath, fileName), sourceFileName); - } - } - } - } -} + LanguageID = locale.LanguageId, + }; + break; + } + } + + if (this.languagePack == null) + { + this.LegacyError = "DependencyError"; + } + } + } + + break; + case "ProviderResource": + filePath = Path.Combine("Providers", Path.Combine(moduleName, "App_LocalResources")); + break; + case "InstallResource": + filePath = "Install\\App_LocalResources"; + break; + } + + if (!string.IsNullOrEmpty(filePath)) + { + this.AddFile(Path.Combine(filePath, fileName), sourceFileName); + } + } + } + } +} diff --git a/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs index 67f0ddcee53..c09753a09e6 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Installer.Writers using System; using System.Collections.Generic; using System.ComponentModel; + using System.Globalization; using System.IO; using System.Xml; using System.Xml.XPath; @@ -158,7 +159,7 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold string viewOrder = Util.ReadElement(controlNav, "vieworder"); if (!string.IsNullOrEmpty(viewOrder)) { - moduleControl.ViewOrder = int.Parse(viewOrder); + moduleControl.ViewOrder = int.Parse(viewOrder, CultureInfo.InvariantCulture); } moduleControl.HelpURL = Util.ReadElement(controlNav, "helpurl"); @@ -179,8 +180,8 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold private void Initialize(string folder) { - this.BasePath = Path.Combine("DesktopModules", folder).Replace("/", "\\"); - this.AppCodePath = Path.Combine("App_Code", folder).Replace("/", "\\"); + this.BasePath = Path.Combine("DesktopModules", folder).Replace("/", @"\"); + this.AppCodePath = Path.Combine("App_Code", folder).Replace("/", @"\"); this.AssemblyPath = "bin"; } @@ -189,7 +190,7 @@ private void ProcessModuleFiles(string folder, string basePath) // we are going to drill down through the folders to add the files foreach (string fileName in Directory.GetFiles(folder)) { - string name = fileName.Replace(basePath + "\\", string.Empty); + string name = fileName.Replace(basePath + @"\", string.Empty); this.AddFile(name, name); } } @@ -214,7 +215,7 @@ private void ProcessModules(XPathNavigator moduleNav, string moduleFolder) string cacheTime = Util.ReadElement(moduleNav, "cachetime"); if (!string.IsNullOrEmpty(cacheTime)) { - definition.DefaultCacheTime = int.Parse(cacheTime); + definition.DefaultCacheTime = int.Parse(cacheTime, CultureInfo.InvariantCulture); } // Process legacy controls Node diff --git a/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs b/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs index 7c6509fa973..d68b5ea4998 100644 --- a/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs +++ b/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Installer.Writers using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.IO.Compression; using System.Text; @@ -482,12 +483,12 @@ protected virtual void ParseFiles(DirectoryInfo folder, string rootPath) foreach (FileInfo file in files) { string filePath = folder.FullName.Replace(rootPath, string.Empty); - if (filePath.StartsWith("\\")) + if (filePath.StartsWith(@"\", StringComparison.Ordinal)) { filePath = filePath.Substring(1); } - if (folder.FullName.ToLowerInvariant().Contains("app_code")) + if (folder.FullName.Contains("app_code", StringComparison.OrdinalIgnoreCase)) { filePath = "[app_code]" + filePath; } @@ -545,21 +546,23 @@ protected void ParseProjectFile(FileInfo projFile, bool includeSource) fileName = assemblyNav.Value; XPathNavigator buildPathNav = rootNav.SelectSingleNode("proj:PropertyGroup/proj:OutputPath", manager); string buildPath = buildPathNav.Value.Replace("..\\", string.Empty); - buildPath = buildPath.Replace(this.AssemblyPath + "\\", string.Empty); + buildPath = buildPath.Replace(this.AssemblyPath + @"\", string.Empty); this.AddFile(Path.Combine(buildPath, fileName + ".dll")); // Check for referenced assemblies foreach (XPathNavigator itemNav in rootNav.Select("proj:ItemGroup/proj:Reference", manager)) { fileName = Util.ReadAttribute(itemNav, "Include"); - if (fileName.IndexOf(",") > -1) + if (fileName.Contains(",", StringComparison.Ordinal)) { - fileName = fileName.Substring(0, fileName.IndexOf(",")); + fileName = fileName.Substring(0, fileName.IndexOf(",", StringComparison.Ordinal)); } - if ( - !(fileName.StartsWith("system", StringComparison.InvariantCultureIgnoreCase) || fileName.StartsWith("microsoft", StringComparison.InvariantCultureIgnoreCase) || fileName.Equals("dotnetnuke", StringComparison.OrdinalIgnoreCase) || - fileName.Equals("dotnetnuke.webutility", StringComparison.OrdinalIgnoreCase) || fileName.Equals("dotnetnuke.webcontrols", StringComparison.OrdinalIgnoreCase))) + if (!(fileName.StartsWith("system", StringComparison.OrdinalIgnoreCase) + || fileName.StartsWith("microsoft", StringComparison.OrdinalIgnoreCase) + || fileName.Equals("dotnetnuke", StringComparison.OrdinalIgnoreCase) + || fileName.Equals("dotnetnuke.webutility", StringComparison.OrdinalIgnoreCase) + || fileName.Equals("dotnetnuke.webcontrols", StringComparison.OrdinalIgnoreCase))) { this.AddFile(fileName + ".dll"); } @@ -628,7 +631,7 @@ private void AddFilesToZip(ZipArchive stream, IDictionary f } else { - filepath = Path.Combine(Path.Combine(this.applicationStatusInfo.ApplicationMapPath, basePath), packageFile.FullName.Replace(basePath + "\\", string.Empty)); + filepath = Path.Combine(Path.Combine(this.applicationStatusInfo.ApplicationMapPath, basePath), packageFile.FullName.Replace(basePath + @"\", string.Empty)); } if (File.Exists(filepath)) @@ -636,11 +639,11 @@ private void AddFilesToZip(ZipArchive stream, IDictionary f string packageFilePath = packageFile.Path; if (!string.IsNullOrEmpty(basePath)) { - packageFilePath = packageFilePath.Replace(basePath + "\\", string.Empty); + packageFilePath = packageFilePath.Replace($@"{basePath}\", string.Empty); } FileSystemUtils.AddToZip(ref stream, filepath, packageFile.Name, packageFilePath); - this.Log.AddInfo(string.Format(Util.WRITER_SavedFile, packageFile.FullName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.WRITER_SavedFile, packageFile.FullName)); } } } @@ -655,7 +658,7 @@ private void CreateZipFile(string zipFileName) this.Log.StartJob(Util.WRITER_CreatingPackage); try { - this.Log.AddInfo(string.Format(Util.WRITER_CreateArchive, zipFileShortName)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.WRITER_CreateArchive, zipFileShortName)); strmZipFile = File.Create(zipFileName); ZipArchive strmZipStream = null; try @@ -673,14 +676,11 @@ private void CreateZipFile(string zipFileName) catch (Exception ex) { Exceptions.Exceptions.LogException(ex); - this.Log.AddFailure(string.Format(Util.WRITER_SaveFileError, ex)); + this.Log.AddFailure(string.Format(CultureInfo.InvariantCulture, Util.WRITER_SaveFileError, ex)); } finally { - if (strmZipStream != null) - { - strmZipStream.Dispose(); - } + strmZipStream?.Dispose(); } this.Log.EndJob(Util.WRITER_CreatedPackage); @@ -688,7 +688,7 @@ private void CreateZipFile(string zipFileName) catch (Exception ex) { Exceptions.Exceptions.LogException(ex); - this.Log.AddFailure(string.Format(Util.WRITER_SaveFileError, ex)); + this.Log.AddFailure(string.Format(CultureInfo.InvariantCulture, Util.WRITER_SaveFileError, ex)); } finally { diff --git a/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs index 591b673bdf6..c82c4cbc273 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs @@ -27,7 +27,7 @@ public ProviderPackageWriter(PackageInfo package) if (!string.IsNullOrEmpty(providerPath)) { - this.BasePath = providerPath.Replace("~/", string.Empty).Replace("/", "\\"); + this.BasePath = providerPath.Replace("~/", string.Empty).Replace("/", @"\"); } } diff --git a/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs index 61d3527d35a..a4f1d7cb92e 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Installer.Writers { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Xml; @@ -59,7 +60,7 @@ protected override string ItemNodeName /// protected override void WriteFileElement(XmlWriter writer, InstallFile file) { - this.Log.AddInfo(string.Format(Util.WRITER_AddFileToManifest, file.Name)); + this.Log.AddInfo(string.Format(CultureInfo.InvariantCulture, Util.WRITER_AddFileToManifest, file.Name)); string type = "Install"; string version = Null.NullString; string fileName = Path.GetFileNameWithoutExtension(file.Name); @@ -75,7 +76,7 @@ protected override void WriteFileElement(XmlWriter writer, InstallFile file) type = "Install"; version = new Version(0, 0, 0).ToString(3); } - else if (fileName.StartsWith("Install")) + else if (fileName.StartsWith("Install", StringComparison.OrdinalIgnoreCase)) { // Install.xx.xx.xx.SqlDataprovider type = "Install"; diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs index 67bf6ce36a5..7136ded2068 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs @@ -21,8 +21,8 @@ public SkinControlPackageWriter(PackageInfo package) : base(package) { this.SkinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); - this.BasePath = Path.Combine("DesktopModules", package.Name.ToLowerInvariant()).Replace("/", "\\"); - this.AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", "\\"); + this.BasePath = Path.Combine("DesktopModules", package.Name.ToLowerInvariant()).Replace("/", @"\"); + this.AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", @"\"); } /// Initializes a new instance of the class. @@ -32,8 +32,8 @@ public SkinControlPackageWriter(SkinControlInfo skinControl, PackageInfo package : base(package) { this.SkinControl = skinControl; - this.BasePath = Path.Combine("DesktopModules", package.Name.ToLowerInvariant()).Replace("/", "\\"); - this.AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", "\\"); + this.BasePath = Path.Combine("DesktopModules", package.Name.ToLowerInvariant()).Replace("/", @"\"); + this.AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", @"\"); } /// Initializes a new instance of the class. @@ -53,8 +53,8 @@ public SkinControlPackageWriter(XPathNavigator manifestNav, InstallerInfo instal this.Package.PackageType = "SkinObject"; this.Package.License = Util.PACKAGE_NoLicense; - this.BasePath = Path.Combine("DesktopModules", this.Package.Name.ToLowerInvariant()).Replace("/", "\\"); - this.AppCodePath = Path.Combine("App_Code", this.Package.Name.ToLowerInvariant()).Replace("/", "\\"); + this.BasePath = Path.Combine("DesktopModules", this.Package.Name.ToLowerInvariant()).Replace("/", @"\"); + this.AppCodePath = Path.Combine("App_Code", this.Package.Name.ToLowerInvariant()).Replace("/", @"\"); } /// Gets or sets the associated SkinControl. @@ -88,7 +88,7 @@ private void ReadLegacyManifest(XPathNavigator legacyManifest, bool processModul foreach (XPathNavigator controlNav in folderNav.Select("modules/module/controls/control")) { this.SkinControl.ControlKey = Util.ReadElement(controlNav, "key"); - this.SkinControl.ControlSrc = Path.Combine(Path.Combine("DesktopModules", this.Package.Name.ToLowerInvariant()), Util.ReadElement(controlNav, "src")).Replace("\\", "/"); + this.SkinControl.ControlSrc = Path.Combine(Path.Combine("DesktopModules", this.Package.Name.ToLowerInvariant()), Util.ReadElement(controlNav, "src")).Replace(@"\", "/"); string supportsPartialRendering = Util.ReadElement(controlNav, "supportspartialrendering"); if (!string.IsNullOrEmpty(supportsPartialRendering)) { diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs index d4a0eb0f515..d54b52bc057 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs @@ -103,7 +103,7 @@ protected override void ParseFiles(DirectoryInfo folder, string rootPath) foreach (FileInfo file in files) { string filePath = folder.FullName.Replace(rootPath, string.Empty); - if (filePath.StartsWith("\\")) + if (filePath.StartsWith(@"\", StringComparison.Ordinal)) { filePath = filePath.Substring(1); } diff --git a/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs index 5b281abeede..cb707225d4a 100644 --- a/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Installer.Writers { + using System; using System.IO; using System.Xml; @@ -17,12 +18,12 @@ public WidgetPackageWriter(PackageInfo package) : base(package) { string company = package.Name; - if (company.Contains(".")) + if (company.Contains(".", StringComparison.Ordinal)) { - company = company.Substring(0, company.IndexOf(".")); + company = company.Substring(0, company.IndexOf(".", StringComparison.Ordinal)); } - this.BasePath = Path.Combine("Resources\\Widgets\\User", company); + this.BasePath = Path.Combine(@"Resources\Widgets\User", company); } /// @@ -44,7 +45,7 @@ protected override void GetFiles(bool includeSource, bool includeAppCode) /// protected override void WriteFilesToManifest(XmlWriter writer) { - string company = this.Package.Name.Substring(0, this.Package.Name.IndexOf(".")); + string company = this.Package.Name.Substring(0, this.Package.Name.IndexOf(".", StringComparison.Ordinal)); var widgetFileWriter = new WidgetComponentWriter(company, this.Files, this.Package); widgetFileWriter.WriteManifest(writer); } diff --git a/DNN Platform/Library/Services/Installer/XmlMerge.cs b/DNN Platform/Library/Services/Installer/XmlMerge.cs index 98cda561f09..81d2efdb66e 100644 --- a/DNN Platform/Library/Services/Installer/XmlMerge.cs +++ b/DNN Platform/Library/Services/Installer/XmlMerge.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Installer using System; using System.Collections.Generic; using System.Diagnostics; + using System.Globalization; using System.IO; using System.Linq; using System.Xml; @@ -172,7 +173,7 @@ public void UpdateConfigs(bool autoSave) bool isAppliedToProduct; - if (!File.Exists(Globals.ApplicationMapPath + "\\" + this.TargetFileName)) + if (!File.Exists(Globals.ApplicationMapPath + @"\" + this.TargetFileName)) { DnnInstallLogger.InstallLogInfo($"Target File {this.TargetFileName} doesn't exist, ignore the merge process"); return; @@ -231,7 +232,7 @@ private static string AdjustRootNodePathRelativeToLocationElements(XmlNode root, return rootNodePath; } - var index = rootNodePath.IndexOf("configuration"); + var index = rootNodePath.IndexOf("configuration", StringComparison.OrdinalIgnoreCase); var adjustedPath = rootNodePath.Substring(index + "configuration".Length); adjustedPath = adjustedPath.TrimStart('/'); if (string.IsNullOrEmpty(adjustedPath)) @@ -620,6 +621,7 @@ private bool UpdateNode(XmlNode rootNode, XmlNode actionNode) } string commentHeaderText = string.Format( + CultureInfo.InvariantCulture, Localization.GetString("XMLMERGE_Upgrade", Localization.SharedResourceFile), Environment.NewLine, this.Sender, diff --git a/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs b/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs index b858263ffed..7909b8b383e 100644 --- a/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs +++ b/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Services.Journal public interface IJournalDataService { +#pragma warning disable CA1707 // Identifiers should not contain underscores IDataReader Journal_ListForSummary(int portalId, int moduleId, int currentUserId, int rowIndex, int maxRows); IDataReader Journal_ListForProfile(int portalId, int moduleId, int currentUserId, int profileId, int rowIndex, int maxRows); @@ -83,5 +84,6 @@ public interface IJournalDataService void Journal_TypeFilters_Delete(int portalId, int moduleId); void Journal_TypeFilters_Save(int portalId, int moduleId, int journalTypeId); +#pragma warning restore CA1707 } } diff --git a/DNN Platform/Library/Services/Journal/IJournalController.cs b/DNN Platform/Library/Services/Journal/IJournalController.cs index 71cb6595384..a4e47550cf7 100644 --- a/DNN Platform/Library/Services/Journal/IJournalController.cs +++ b/DNN Platform/Library/Services/Journal/IJournalController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Journal { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.IO; using DotNetNuke.Entities.Modules; @@ -91,16 +92,19 @@ public interface IJournalController /// File Name. /// File content. /// A FileInfo object corresponding to the saved file. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] IFileInfo SaveJourmalFile(ModuleInfo module, UserInfo userInfo, string fileName, Stream fileContent); /// Save the journal object into database. /// Journal object. /// The module info of journal item context. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void SaveJournalItem(JournalItem journalItem, ModuleInfo module); /// Update the journal info in database. /// Journal object. /// The module info of journal item context. + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] void UpdateJournalItem(JournalItem journalItem, ModuleInfo module); /// Hard delete journal item by journal ID. diff --git a/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs b/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs index 4cad988a08f..00491853510 100644 --- a/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs +++ b/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs @@ -4,9 +4,11 @@ namespace DotNetNuke.Services.Journal.Internal { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Common.Utilities; + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public class InternalJournalControllerImpl : IInternalJournalController { private readonly IJournalDataService dataService; @@ -18,6 +20,7 @@ public InternalJournalControllerImpl() } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public IList GetJournalItemsByProfile(int portalId, int moduleId, int currentUserId, int profileId, int rowIndex, int maxRows) { return @@ -32,6 +35,7 @@ public IList GetJournalItemsByProfile(int portalId, int moduleId, i } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public IList GetJournalItemsByGroup(int portalId, int moduleId, int currentUserId, int groupId, int rowIndex, int maxRows) { return @@ -46,6 +50,7 @@ public IList GetJournalItemsByGroup(int portalId, int moduleId, int } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public IList GetJournalItems(int portalId, int moduleId, int currentUserId, int rowIndex, int maxRows) { return @@ -65,6 +70,7 @@ public void DeleteFilters(int portalId, int moduleId) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void SaveFilters(int portalId, int moduleId, int journalTypeId) { this.dataService.Journal_TypeFilters_Save(portalId, moduleId, journalTypeId); diff --git a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs index bcdbe877b5e..df41fc49b6f 100644 --- a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs +++ b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs @@ -1,817 +1,818 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information - -namespace DotNetNuke.Services.Journal; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Xml; - -using DotNetNuke.Abstractions.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Data; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Users; -using DotNetNuke.Security; -using DotNetNuke.Security.Roles; -using DotNetNuke.Services.FileSystem; -using DotNetNuke.Services.Search.Entities; -using DotNetNuke.Services.Search.Internals; - -using Microsoft.Extensions.DependencyInjection; - -/// The default implementation. -internal class JournalControllerImpl : IJournalController -{ - private const string AllowResizePhotosSetting = "Journal_AllowResizePhotos"; - private const string AllowPhotosSetting = "Journal_AllowPhotos"; - private const string EditorEnabledSetting = "Journal_EditorEnabled"; - - private static readonly string[] InvalidSecuritySetsWithoutId = ["R", "U", "F", "P"]; - private static readonly char[] ValidSecurityDescriptors = ['E', 'C', 'R', 'U', 'F', 'P']; - private readonly IJournalDataService dataService; - private readonly IHostSettings hostSettings; - private readonly IRoleController roleController; - private readonly ISearchHelper searchHelper; - private readonly DataProvider dataProvider; - private readonly IFolderManager folderManager; - private readonly IFileManager fileManager; - private readonly IFileContentTypeManager fileContentTypeManager; - private readonly PortalSecurity portalSecurity; - - /// Initializes a new instance of the class. - [Obsolete("Deprecated in DotNetNuke 10.1.1. Please use overload with IJournalDataService. Scheduled removal in v12.0.0.")] - public JournalControllerImpl() - : this(null, null, null, null, null, null, null, null, null) - { - } - - /// Initializes a new instance of the class. - /// The journal data service. - /// The host settings. - /// The role controller. - /// The search helpers. - /// The data provider. - /// The folder manager. - /// The file manager. - /// The file content type manager. - /// The portal security instance. - public JournalControllerImpl(IJournalDataService journalDataService, IHostSettings hostSettings, IRoleController roleController, ISearchHelper searchHelper, DataProvider dataProvider, IFolderManager folderManager, IFileManager fileManager, IFileContentTypeManager fileContentTypeManager, PortalSecurity portalSecurity) - { - this.dataService = journalDataService ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - this.hostSettings = hostSettings ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - this.roleController = roleController ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - this.searchHelper = searchHelper ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - this.dataProvider = dataProvider ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - this.folderManager = folderManager ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - this.fileManager = fileManager ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - this.fileContentTypeManager = fileContentTypeManager ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - this.portalSecurity = portalSecurity ?? Globals.GetCurrentServiceProvider().GetRequiredService(); - } - - /// Save the journal object into database. - /// Journal object. - /// The ID of the tab of the journal item context. - /// The ID of the module of the journal item context. - public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) - { - if (journalItem.UserId < 1) - { - throw new ArgumentException("journalItem.UserId must be for a real user"); - } - - UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId); - if (currentUser == null) - { - throw new UserDoesNotExistException("Unable to locate the current user"); - } - - string xml = null; - if (!string.IsNullOrEmpty(journalItem.Title)) - { - journalItem.Title = this.portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); - } - - if (!string.IsNullOrEmpty(journalItem.Summary)) - { - journalItem.Summary = this.portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.Body)) - { - journalItem.Body = this.portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.Body)) - { - var xDoc = new XmlDocument { XmlResolver = null }; - var itemsNode = xDoc.CreateElement("items"); - var itemNode = xDoc.CreateElement("item"); - itemNode.AppendChild(CreateElement(xDoc, "id", "-1")); - itemNode.AppendChild(CreateCDataElement(xDoc, "body", journalItem.Body)); - itemsNode.AppendChild(itemNode); - xDoc.AppendChild(itemsNode); - var xDec = xDoc.CreateXmlDeclaration("1.0", null, null); - xDec.Encoding = "UTF-16"; - xDec.Standalone = "yes"; - var root = xDoc.DocumentElement; - xDoc.InsertBefore(xDec, root); - journalItem.JournalXML = xDoc; - xml = journalItem.JournalXML.OuterXml; - } - - if (journalItem.ItemData != null) - { - if (!string.IsNullOrEmpty(journalItem.ItemData.Title)) - { - journalItem.ItemData.Title = this.portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.Description)) - { - journalItem.ItemData.Description = this.portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.Url)) - { - journalItem.ItemData.Url = this.portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) - { - journalItem.ItemData.ImageUrl = this.portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); - } - } - - var journalData = journalItem.ItemData.ToJson(); - if (journalData == "null") - { - journalData = null; - } - - this.PrepareSecuritySet(journalItem); - - journalItem.JournalId = this.dataService.Journal_Save( - journalItem.PortalId, - journalItem.UserId, - journalItem.ProfileId, - journalItem.SocialGroupId, - journalItem.JournalId, - journalItem.JournalTypeId, - journalItem.Title, - journalItem.Summary, - journalItem.Body, - journalData, - xml, - journalItem.ObjectKey, - journalItem.AccessKey, - journalItem.SecuritySet, - journalItem.CommentsDisabled, - journalItem.CommentsHidden); - - var updatedJournalItem = this.GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); - journalItem.DateCreated = updatedJournalItem.DateCreated; - journalItem.DateUpdated = updatedJournalItem.DateUpdated; - var cnt = new Content(); - - if (journalItem.ContentItemId > 0) - { - cnt.UpdateContentItem(journalItem, tabId, moduleId); - this.dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); - } - else - { - var ci = cnt.CreateContentItem(journalItem, tabId, moduleId); - this.dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); - journalItem.ContentItemId = ci.ContentItemId; - } - - if (journalItem.SocialGroupId > 0) - { - try - { - this.UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); - } - catch (Exception exc) - { - Exceptions.Exceptions.LogException(exc); - } - } - } - - /// Update the journal info in database. - /// Journal object. - /// The ID of the tab of the journal item context. - /// The ID of the module of the journal item context. - public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) - { - if (journalItem.UserId < 1) - { - throw new ArgumentException("journalItem.UserId must be for a real user"); - } - - UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId); - if (currentUser == null) - { - throw new UserDoesNotExistException("Unable to locate the current user"); - } - - string xml = null; - if (!string.IsNullOrEmpty(journalItem.Title)) - { - journalItem.Title = this.portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); - } - - if (!string.IsNullOrEmpty(journalItem.Summary)) - { - journalItem.Summary = this.portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.Body)) - { - journalItem.Body = this.portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.Body)) - { - var xDoc = new XmlDocument { XmlResolver = null }; - var itemsNode = xDoc.CreateElement("items"); - var itemNode = xDoc.CreateElement("item"); - itemNode.AppendChild(CreateElement(xDoc, "id", "-1")); - itemNode.AppendChild(CreateCDataElement(xDoc, "body", journalItem.Body)); - itemsNode.AppendChild(itemNode); - xDoc.AppendChild(itemsNode); - var xDec = xDoc.CreateXmlDeclaration("1.0", null, null); - xDec.Encoding = "UTF-16"; - xDec.Standalone = "yes"; - var root = xDoc.DocumentElement; - xDoc.InsertBefore(xDec, root); - journalItem.JournalXML = xDoc; - xml = journalItem.JournalXML.OuterXml; - } - - if (journalItem.ItemData != null) - { - if (!string.IsNullOrEmpty(journalItem.ItemData.Title)) - { - journalItem.ItemData.Title = this.portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.Description)) - { - journalItem.ItemData.Description = - this.portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.Url)) - { - journalItem.ItemData.Url = this.portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) - { - journalItem.ItemData.ImageUrl = this.portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); - } - } - - var journalData = journalItem.ItemData.ToJson(); - if (journalData == "null") - { - journalData = null; - } - - this.PrepareSecuritySet(journalItem); - - journalItem.JournalId = this.dataService.Journal_Update( - journalItem.PortalId, - journalItem.UserId, - journalItem.ProfileId, - journalItem.SocialGroupId, - journalItem.JournalId, - journalItem.JournalTypeId, - journalItem.Title, - journalItem.Summary, - journalItem.Body, - journalData, - xml, - journalItem.ObjectKey, - journalItem.AccessKey, - journalItem.SecuritySet, - journalItem.CommentsDisabled, - journalItem.CommentsHidden); - - var updatedJournalItem = this.GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); - journalItem.DateCreated = updatedJournalItem.DateCreated; - journalItem.DateUpdated = updatedJournalItem.DateUpdated; - - var cnt = new Content(); - if (journalItem.ContentItemId > 0) - { - cnt.UpdateContentItem(journalItem, tabId, moduleId); - this.dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); - } - else - { - var ci = cnt.CreateContentItem(journalItem, tabId, moduleId); - this.dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); - journalItem.ContentItemId = ci.ContentItemId; - } - - if (journalItem.SocialGroupId > 0) - { - try - { - this.UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); - } - catch (Exception exc) - { - Exceptions.Exceptions.LogException(exc); - } - } - } - - /// - public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId) - { - return this.GetJournalItem(portalId, currentUserId, journalId, false, false); - } - - /// - public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems) - { - return this.GetJournalItem(portalId, currentUserId, journalId, includeAllItems, false); - } - - /// - public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted) - { - return this.GetJournalItem(portalId, currentUserId, journalId, includeAllItems, isDeleted, false); - } - - /// - public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted, bool securityCheck) - { - return CBO.FillObject(this.dataService.Journal_Get(portalId, currentUserId, journalId, includeAllItems, isDeleted, securityCheck)); - } - - /// - public JournalItem GetJournalItemByKey(int portalId, string objectKey) - { - return this.GetJournalItemByKey(portalId, objectKey, false, false); - } - - /// - public JournalItem GetJournalItemByKey(int portalId, string objectKey, bool includeAllItems) - { - return this.GetJournalItemByKey(portalId, objectKey, includeAllItems, false); - } - - /// - public JournalItem GetJournalItemByKey(int portalId, string objectKey, bool includeAllItems, bool isDeleted) - { - if (string.IsNullOrEmpty(objectKey)) - { - return null; - } - - return CBO.FillObject(this.dataService.Journal_GetByKey(portalId, objectKey, includeAllItems, isDeleted)); - } - - /// - public IFileInfo SaveJourmalFile(ModuleInfo module, UserInfo userInfo, string fileName, Stream fileContent) - { - var userFolder = this.folderManager.GetUserFolder(userInfo); - - Stream fileContentStream = null; - try - { - if (IsImageFile(fileName) && IsResizePhotosEnabled(module)) - { - fileContentStream = GetJournalImageContent(fileContent); - } - - return this.fileManager.AddFile(userFolder, fileName, fileContentStream ?? fileContent, true, true, this.fileContentTypeManager.GetContentType(Path.GetExtension(fileName))); - } - finally - { - fileContentStream?.Dispose(); - } - } - - /// - public void SaveJournalItem(JournalItem journalItem, ModuleInfo module) - { - var tabId = module?.TabID ?? Null.NullInteger; - var tabModuleId = module?.TabModuleID ?? Null.NullInteger; - - this.SaveJournalItem(journalItem, tabId, tabModuleId); - } - - /// - public void UpdateJournalItem(JournalItem journalItem, ModuleInfo module) - { - var tabId = module?.TabID ?? Null.NullInteger; - var tabModuleId = module?.TabModuleID ?? Null.NullInteger; - - this.UpdateJournalItem(journalItem, tabId, tabModuleId); - } - - /// - public void DisableComments(int portalId, int journalId) - { - this.dataService.Journal_Comments_ToggleDisable(portalId, journalId, true); - } - - /// - public void EnableComments(int portalId, int journalId) - { - this.dataService.Journal_Comments_ToggleDisable(portalId, journalId, false); - } - - /// - public void HideComments(int portalId, int journalId) - { - this.dataService.Journal_Comments_ToggleHidden(portalId, journalId, true); - } - - /// - public void ShowComments(int portalId, int journalId) - { - this.dataService.Journal_Comments_ToggleHidden(portalId, journalId, false); - } - - // Delete Journal Items - - /// HARD deletes journal items. - /// The portal ID. - /// The user ID. - /// The journal ID. - public void DeleteJournalItem(int portalId, int currentUserId, int journalId) - { - this.DeleteJournalItem(portalId, currentUserId, journalId, false); - } - - /// HARD deletes journal items based on item key. - /// The portal ID. - /// The key. - public void DeleteJournalItemByKey(int portalId, string objectKey) - { - this.dataService.Journal_DeleteByKey(portalId, objectKey); - } - - /// HARD deletes journal items based on group ID. - /// The portal ID. - /// The group ID. - public void DeleteJournalItemByGroupId(int portalId, int groupId) - { - this.dataService.Journal_DeleteByGroupId(portalId, groupId); - } - - /// SOFT deletes journal items. - /// The portal ID. - /// The user ID. - /// The journal ID. - public void SoftDeleteJournalItem(int portalId, int currentUserId, int journalId) - { - this.DeleteJournalItem(portalId, currentUserId, journalId, true); - } - - /// SOFT deletes journal items based on item key. - /// The portal ID. - /// The key. - public void SoftDeleteJournalItemByKey(int portalId, string objectKey) - { - this.dataService.Journal_SoftDeleteByKey(portalId, objectKey); - } - - /// SOFT deletes journal items based on group ID. - /// The portal ID. - /// The group ID. - public void SoftDeleteJournalItemByGroupId(int portalId, int groupId) - { - this.dataService.Journal_SoftDeleteByGroupId(portalId, groupId); - } - - /// - public IList GetCommentsByJournalIds(List journalIdList) - { - var journalIds = journalIdList.Aggregate(string.Empty, (current, journalId) => current + journalId + ";"); - return CBO.FillCollection(this.dataService.Journal_Comment_ListByJournalIds(journalIds)); - } - - /// - public void LikeJournalItem(int journalId, int userId, string displayName) - { - this.dataService.Journal_Like(journalId, userId, displayName); - } - - /// - public void SaveComment(CommentInfo comment) - { - if (!string.IsNullOrEmpty(comment.Comment)) - { - comment.Comment = - this.portalSecurity.InputFilter(comment.Comment, PortalSecurity.FilterFlag.NoScripting); - } - - // TODO: enable once the profanity filter is working properly. - // objCommentInfo.Comment = portalSecurity.Remove(objCommentInfo.Comment, DotNetNuke.Security.PortalSecurity.ConfigType.ListController, "ProfanityFilter", DotNetNuke.Security.PortalSecurity.FilterScope.PortalList); - string xml = null; - if (comment.CommentXML != null) - { - xml = comment.CommentXML.OuterXml; - } - - comment.CommentId = this.dataService.Journal_Comment_Save(comment.JournalId, comment.CommentId, comment.UserId, comment.Comment, xml, Null.NullDate); - - var newComment = this.GetComment(comment.CommentId); - comment.DateCreated = newComment.DateCreated; - comment.DateUpdated = newComment.DateUpdated; - } - - /// - public CommentInfo GetComment(int commentId) - { - return CBO.FillObject(this.dataService.Journal_Comment_Get(commentId)); - } - - /// - public void DeleteComment(int journalId, int commentId) - { - this.dataService.Journal_Comment_Delete(journalId, commentId); - - // UNDONE: update the parent journal item and content item so this comment gets removed from search index - } - - /// - public void LikeComment(int journalId, int commentId, int userId, string displayName) - { - this.dataService.Journal_Comment_Like(journalId, commentId, userId, displayName); - } - - /// - public JournalTypeInfo GetJournalType(string journalType) - { - return CBO.FillObject(this.dataService.Journal_Types_Get(journalType)); - } - - /// - public JournalTypeInfo GetJournalTypeById(int journalTypeId) - { - return CBO.FillObject(this.dataService.Journal_Types_GetById(journalTypeId)); - } - - /// - public IEnumerable GetJournalTypes(int portalId) - { - return CBO.GetCachedObject>( - this.hostSettings, - new CacheItemArgs( - string.Format(DataCache.JournalTypesCacheKey, portalId), - DataCache.JournalTypesTimeOut, - DataCache.JournalTypesCachePriority, - portalId), - _ => CBO.FillCollection(this.dataService.Journal_Types_List(portalId))); - } - - private static XmlElement CreateElement(XmlDocument xDoc, string name, string value) - { - var element = xDoc.CreateElement(name); - var xtext = xDoc.CreateTextNode(value); - element.AppendChild(xtext); - return element; - } - - private static XmlElement CreateCDataElement(XmlDocument xDoc, string name, string value) - { - var element = xDoc.CreateElement(name); - var xdata = xDoc.CreateCDataSection(value); - element.AppendChild(xdata); - return element; - } - - private static MemoryStream GetJournalImageContent(Stream fileContent) - { - Image image = new Bitmap(fileContent); - var thumbnailWidth = 400; - var thumbnailHeight = 400; - GetThumbnailSize(image.Width, image.Height, ref thumbnailWidth, ref thumbnailHeight); - var thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight, () => true, IntPtr.Zero); - var result = new MemoryStream(); - thumbnail.Save(result, image.RawFormat); - return result; - } - - private static void GetThumbnailSize(int imageWidth, int imageHeight, ref int thumbnailWidth, ref int thumbnailHeight) - { - if (imageWidth >= imageHeight) - { - thumbnailWidth = Math.Min(imageWidth, thumbnailWidth); - thumbnailHeight = GetMinorSize(imageHeight, imageWidth, thumbnailWidth); - } - else - { - thumbnailHeight = Math.Min(imageHeight, thumbnailHeight); - thumbnailWidth = GetMinorSize(imageWidth, imageHeight, thumbnailHeight); - } - } - - private static int GetMinorSize(int imageMinorSize, int imageMajorSize, int thumbnailMajorSize) - { - if (imageMajorSize == thumbnailMajorSize) - { - return imageMinorSize; - } - - double calculated = (Convert.ToDouble(imageMinorSize) * Convert.ToDouble(thumbnailMajorSize)) / Convert.ToDouble(imageMajorSize); - return Convert.ToInt32(Math.Round(calculated)); - } - - private static bool IsImageFile(string fileName) - { - return (Globals.ImageFileTypes + ",").IndexOf(Path.GetExtension(fileName).Replace(".", string.Empty) + ",", StringComparison.InvariantCultureIgnoreCase) > -1; - } - - private static bool IsResizePhotosEnabled(ModuleInfo module) - { - return GetBooleanSetting(AllowResizePhotosSetting, false, module) && - GetBooleanSetting(AllowPhotosSetting, true, module) && - GetBooleanSetting(EditorEnabledSetting, true, module); - } - - private static bool GetBooleanSetting(string settingName, bool defaultValue, ModuleInfo module) - { - if (module.ModuleSettings.Contains(settingName)) - { - return Convert.ToBoolean(module.ModuleSettings[settingName].ToString()); - } - - return defaultValue; - } - - // none of the parameters should be null; checked before calling this method - private void PrepareSecuritySet(JournalItem journalItem) - { - var originalSecuritySet = - journalItem.SecuritySet = (journalItem.SecuritySet ?? string.Empty).ToUpperInvariant(); - - if (string.IsNullOrEmpty(journalItem.SecuritySet)) - { - journalItem.SecuritySet = "E,"; - } - else if (!journalItem.SecuritySet.EndsWith(",")) - { - journalItem.SecuritySet += ","; - originalSecuritySet = journalItem.SecuritySet; - } - - if (journalItem.SecuritySet == "F,") - { - journalItem.SecuritySet = "F" + journalItem.UserId + ","; - if (journalItem.ProfileId > 0) - { - journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; - } - } - else if (journalItem.SecuritySet == "U,") - { - journalItem.SecuritySet += "U" + journalItem.UserId + ","; - } - else if (journalItem.SecuritySet == "R,") - { - if (journalItem.SocialGroupId > 0) - { - journalItem.SecuritySet += "R" + journalItem.SocialGroupId + ","; - } - } - - if (journalItem.ProfileId > 0 && journalItem.UserId != journalItem.ProfileId) - { - if (!journalItem.SecuritySet.Contains("P" + journalItem.ProfileId + ",")) - { - journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; - } - - if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId + ",")) - { - journalItem.SecuritySet += "U" + journalItem.UserId + ","; - } - } - - if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId + ",")) - { - journalItem.SecuritySet += "U" + journalItem.UserId + ","; - } - - // if the post is marked as private, we shouldn't make it visible to the group. - if (journalItem.SocialGroupId > 0 && originalSecuritySet.Contains("U,")) - { - var item = journalItem; - var role = this.roleController.GetRole( - journalItem.PortalId, - r => r.SecurityMode != SecurityMode.SecurityRole && r.RoleID == item.SocialGroupId); - - if (role != null && !role.IsPublic) - { - journalItem.SecuritySet = journalItem.SecuritySet.Replace("E,", string.Empty).Replace("C,", string.Empty); - } - } - - // clean up and remove duplicates - var parts = journalItem.SecuritySet - .Replace(" ", string.Empty) - .Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) - .Distinct() - .Except(InvalidSecuritySetsWithoutId) - .Where(p => p.IndexOfAny(ValidSecurityDescriptors) >= 0); - - // TODO: validate existence and visibility/accessability of all Roles added to the set (if any) - journalItem.SecuritySet = string.Join(",", parts); - } - - private void UpdateGroupStats(int portalId, int groupId) - { - var role = this.roleController.GetRole(portalId, r => r.RoleID == groupId); - if (role is null) - { - return; - } - - for (var i = 0; i < role.Settings.Keys.Count; i++) - { - var key = role.Settings.Keys.ElementAt(i); - if (key.StartsWith("stat_")) - { - role.Settings[key] = "0"; - } - } - - using (var dr = this.dataService.Journal_GetStatsForGroup(portalId, groupId)) - { - while (dr.Read()) - { - var settingName = "stat_" + dr["JournalType"]; - if (role.Settings.ContainsKey(settingName)) - { - role.Settings[settingName] = dr["JournalTypeCount"].ToString(); - } - else - { - role.Settings.Add(settingName, dr["JournalTypeCount"].ToString()); - } - } - - dr.Close(); - } - - this.roleController.UpdateRoleSettings(role, true); - } - - private void DeleteJournalItem(int portalId, int currentUserId, int journalId, bool softDelete) - { - var ji = this.GetJournalItem(portalId, currentUserId, journalId, !softDelete); - if (ji == null) - { - return; - } - - var groupId = ji.SocialGroupId; - - if (softDelete) - { - this.dataService.Journal_SoftDelete(journalId); - } - else - { - this.dataService.Journal_Delete(journalId); - } - - if (groupId > 0) - { - this.UpdateGroupStats(portalId, groupId); - } - - // queue remove journal from search index - var document = new SearchDocumentToDelete - { - PortalId = portalId, - AuthorUserId = currentUserId, - UniqueKey = ji.ContentItemId.ToString("D"), - - // QueryString = "journalid=" + journalId, - SearchTypeId = this.searchHelper.GetSearchTypeByName("module").SearchTypeId, - }; - - if (groupId > 0) - { - document.RoleId = groupId; - } - - this.dataProvider.AddSearchDeletedItems(document); - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Services.Journal; + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Xml; + +using DotNetNuke.Abstractions.Application; +using DotNetNuke.Common; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Data; +using DotNetNuke.Entities.Modules; +using DotNetNuke.Entities.Users; +using DotNetNuke.Security; +using DotNetNuke.Security.Roles; +using DotNetNuke.Services.FileSystem; +using DotNetNuke.Services.Search.Entities; +using DotNetNuke.Services.Search.Internals; + +using Microsoft.Extensions.DependencyInjection; + +/// The default implementation. +internal class JournalControllerImpl : IJournalController +{ + private const string AllowResizePhotosSetting = "Journal_AllowResizePhotos"; + private const string AllowPhotosSetting = "Journal_AllowPhotos"; + private const string EditorEnabledSetting = "Journal_EditorEnabled"; + + private static readonly string[] InvalidSecuritySetsWithoutId = ["R", "U", "F", "P"]; + private static readonly char[] ValidSecurityDescriptors = ['E', 'C', 'R', 'U', 'F', 'P']; + private readonly IJournalDataService dataService; + private readonly IHostSettings hostSettings; + private readonly IRoleController roleController; + private readonly ISearchHelper searchHelper; + private readonly DataProvider dataProvider; + private readonly IFolderManager folderManager; + private readonly IFileManager fileManager; + private readonly IFileContentTypeManager fileContentTypeManager; + private readonly PortalSecurity portalSecurity; + + /// Initializes a new instance of the class. + [Obsolete("Deprecated in DotNetNuke 10.1.1. Please use overload with IJournalDataService. Scheduled removal in v12.0.0.")] + public JournalControllerImpl() + : this(null, null, null, null, null, null, null, null, null) + { + } + + /// Initializes a new instance of the class. + /// The journal data service. + /// The host settings. + /// The role controller. + /// The search helpers. + /// The data provider. + /// The folder manager. + /// The file manager. + /// The file content type manager. + /// The portal security instance. + public JournalControllerImpl(IJournalDataService journalDataService, IHostSettings hostSettings, IRoleController roleController, ISearchHelper searchHelper, DataProvider dataProvider, IFolderManager folderManager, IFileManager fileManager, IFileContentTypeManager fileContentTypeManager, PortalSecurity portalSecurity) + { + this.dataService = journalDataService ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + this.hostSettings = hostSettings ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + this.roleController = roleController ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + this.searchHelper = searchHelper ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + this.dataProvider = dataProvider ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + this.folderManager = folderManager ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + this.fileManager = fileManager ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + this.fileContentTypeManager = fileContentTypeManager ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + this.portalSecurity = portalSecurity ?? Globals.GetCurrentServiceProvider().GetRequiredService(); + } + + /// Save the journal object into database. + /// Journal object. + /// The ID of the tab of the journal item context. + /// The ID of the module of the journal item context. + public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) + { + if (journalItem.UserId < 1) + { + throw new ArgumentException("journalItem.UserId must be for a real user"); + } + + UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId); + if (currentUser == null) + { + throw new UserDoesNotExistException("Unable to locate the current user"); + } + + string xml = null; + if (!string.IsNullOrEmpty(journalItem.Title)) + { + journalItem.Title = this.portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); + } + + if (!string.IsNullOrEmpty(journalItem.Summary)) + { + journalItem.Summary = this.portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.Body)) + { + journalItem.Body = this.portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.Body)) + { + var xDoc = new XmlDocument { XmlResolver = null }; + var itemsNode = xDoc.CreateElement("items"); + var itemNode = xDoc.CreateElement("item"); + itemNode.AppendChild(CreateElement(xDoc, "id", "-1")); + itemNode.AppendChild(CreateCDataElement(xDoc, "body", journalItem.Body)); + itemsNode.AppendChild(itemNode); + xDoc.AppendChild(itemsNode); + var xDec = xDoc.CreateXmlDeclaration("1.0", null, null); + xDec.Encoding = "UTF-16"; + xDec.Standalone = "yes"; + var root = xDoc.DocumentElement; + xDoc.InsertBefore(xDec, root); + journalItem.JournalXML = xDoc; + xml = journalItem.JournalXML.OuterXml; + } + + if (journalItem.ItemData != null) + { + if (!string.IsNullOrEmpty(journalItem.ItemData.Title)) + { + journalItem.ItemData.Title = this.portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.Description)) + { + journalItem.ItemData.Description = this.portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.Url)) + { + journalItem.ItemData.Url = this.portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) + { + journalItem.ItemData.ImageUrl = this.portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); + } + } + + var journalData = journalItem.ItemData.ToJson(); + if (journalData == "null") + { + journalData = null; + } + + this.PrepareSecuritySet(journalItem); + + journalItem.JournalId = this.dataService.Journal_Save( + journalItem.PortalId, + journalItem.UserId, + journalItem.ProfileId, + journalItem.SocialGroupId, + journalItem.JournalId, + journalItem.JournalTypeId, + journalItem.Title, + journalItem.Summary, + journalItem.Body, + journalData, + xml, + journalItem.ObjectKey, + journalItem.AccessKey, + journalItem.SecuritySet, + journalItem.CommentsDisabled, + journalItem.CommentsHidden); + + var updatedJournalItem = this.GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); + journalItem.DateCreated = updatedJournalItem.DateCreated; + journalItem.DateUpdated = updatedJournalItem.DateUpdated; + var cnt = new Content(); + + if (journalItem.ContentItemId > 0) + { + cnt.UpdateContentItem(journalItem, tabId, moduleId); + this.dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); + } + else + { + var ci = cnt.CreateContentItem(journalItem, tabId, moduleId); + this.dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); + journalItem.ContentItemId = ci.ContentItemId; + } + + if (journalItem.SocialGroupId > 0) + { + try + { + this.UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); + } + catch (Exception exc) + { + Exceptions.Exceptions.LogException(exc); + } + } + } + + /// Update the journal info in database. + /// Journal object. + /// The ID of the tab of the journal item context. + /// The ID of the module of the journal item context. + public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) + { + if (journalItem.UserId < 1) + { + throw new ArgumentException("journalItem.UserId must be for a real user"); + } + + UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId); + if (currentUser == null) + { + throw new UserDoesNotExistException("Unable to locate the current user"); + } + + string xml = null; + if (!string.IsNullOrEmpty(journalItem.Title)) + { + journalItem.Title = this.portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); + } + + if (!string.IsNullOrEmpty(journalItem.Summary)) + { + journalItem.Summary = this.portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.Body)) + { + journalItem.Body = this.portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.Body)) + { + var xDoc = new XmlDocument { XmlResolver = null }; + var itemsNode = xDoc.CreateElement("items"); + var itemNode = xDoc.CreateElement("item"); + itemNode.AppendChild(CreateElement(xDoc, "id", "-1")); + itemNode.AppendChild(CreateCDataElement(xDoc, "body", journalItem.Body)); + itemsNode.AppendChild(itemNode); + xDoc.AppendChild(itemsNode); + var xDec = xDoc.CreateXmlDeclaration("1.0", null, null); + xDec.Encoding = "UTF-16"; + xDec.Standalone = "yes"; + var root = xDoc.DocumentElement; + xDoc.InsertBefore(xDec, root); + journalItem.JournalXML = xDoc; + xml = journalItem.JournalXML.OuterXml; + } + + if (journalItem.ItemData != null) + { + if (!string.IsNullOrEmpty(journalItem.ItemData.Title)) + { + journalItem.ItemData.Title = this.portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.Description)) + { + journalItem.ItemData.Description = + this.portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.Url)) + { + journalItem.ItemData.Url = this.portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) + { + journalItem.ItemData.ImageUrl = this.portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); + } + } + + var journalData = journalItem.ItemData.ToJson(); + if (journalData == "null") + { + journalData = null; + } + + this.PrepareSecuritySet(journalItem); + + journalItem.JournalId = this.dataService.Journal_Update( + journalItem.PortalId, + journalItem.UserId, + journalItem.ProfileId, + journalItem.SocialGroupId, + journalItem.JournalId, + journalItem.JournalTypeId, + journalItem.Title, + journalItem.Summary, + journalItem.Body, + journalData, + xml, + journalItem.ObjectKey, + journalItem.AccessKey, + journalItem.SecuritySet, + journalItem.CommentsDisabled, + journalItem.CommentsHidden); + + var updatedJournalItem = this.GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); + journalItem.DateCreated = updatedJournalItem.DateCreated; + journalItem.DateUpdated = updatedJournalItem.DateUpdated; + + var cnt = new Content(); + if (journalItem.ContentItemId > 0) + { + cnt.UpdateContentItem(journalItem, tabId, moduleId); + this.dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); + } + else + { + var ci = cnt.CreateContentItem(journalItem, tabId, moduleId); + this.dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); + journalItem.ContentItemId = ci.ContentItemId; + } + + if (journalItem.SocialGroupId > 0) + { + try + { + this.UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); + } + catch (Exception exc) + { + Exceptions.Exceptions.LogException(exc); + } + } + } + + /// + public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId) + { + return this.GetJournalItem(portalId, currentUserId, journalId, false, false); + } + + /// + public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems) + { + return this.GetJournalItem(portalId, currentUserId, journalId, includeAllItems, false); + } + + /// + public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted) + { + return this.GetJournalItem(portalId, currentUserId, journalId, includeAllItems, isDeleted, false); + } + + /// + public JournalItem GetJournalItem(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted, bool securityCheck) + { + return CBO.FillObject(this.dataService.Journal_Get(portalId, currentUserId, journalId, includeAllItems, isDeleted, securityCheck)); + } + + /// + public JournalItem GetJournalItemByKey(int portalId, string objectKey) + { + return this.GetJournalItemByKey(portalId, objectKey, false, false); + } + + /// + public JournalItem GetJournalItemByKey(int portalId, string objectKey, bool includeAllItems) + { + return this.GetJournalItemByKey(portalId, objectKey, includeAllItems, false); + } + + /// + public JournalItem GetJournalItemByKey(int portalId, string objectKey, bool includeAllItems, bool isDeleted) + { + if (string.IsNullOrEmpty(objectKey)) + { + return null; + } + + return CBO.FillObject(this.dataService.Journal_GetByKey(portalId, objectKey, includeAllItems, isDeleted)); + } + + /// + public IFileInfo SaveJourmalFile(ModuleInfo module, UserInfo userInfo, string fileName, Stream fileContent) + { + var userFolder = this.folderManager.GetUserFolder(userInfo); + + Stream fileContentStream = null; + try + { + if (IsImageFile(fileName) && IsResizePhotosEnabled(module)) + { + fileContentStream = GetJournalImageContent(fileContent); + } + + return this.fileManager.AddFile(userFolder, fileName, fileContentStream ?? fileContent, true, true, this.fileContentTypeManager.GetContentType(Path.GetExtension(fileName))); + } + finally + { + fileContentStream?.Dispose(); + } + } + + /// + public void SaveJournalItem(JournalItem journalItem, ModuleInfo module) + { + var tabId = module?.TabID ?? Null.NullInteger; + var tabModuleId = module?.TabModuleID ?? Null.NullInteger; + + this.SaveJournalItem(journalItem, tabId, tabModuleId); + } + + /// + public void UpdateJournalItem(JournalItem journalItem, ModuleInfo module) + { + var tabId = module?.TabID ?? Null.NullInteger; + var tabModuleId = module?.TabModuleID ?? Null.NullInteger; + + this.UpdateJournalItem(journalItem, tabId, tabModuleId); + } + + /// + public void DisableComments(int portalId, int journalId) + { + this.dataService.Journal_Comments_ToggleDisable(portalId, journalId, true); + } + + /// + public void EnableComments(int portalId, int journalId) + { + this.dataService.Journal_Comments_ToggleDisable(portalId, journalId, false); + } + + /// + public void HideComments(int portalId, int journalId) + { + this.dataService.Journal_Comments_ToggleHidden(portalId, journalId, true); + } + + /// + public void ShowComments(int portalId, int journalId) + { + this.dataService.Journal_Comments_ToggleHidden(portalId, journalId, false); + } + + // Delete Journal Items + + /// HARD deletes journal items. + /// The portal ID. + /// The user ID. + /// The journal ID. + public void DeleteJournalItem(int portalId, int currentUserId, int journalId) + { + this.DeleteJournalItem(portalId, currentUserId, journalId, false); + } + + /// HARD deletes journal items based on item key. + /// The portal ID. + /// The key. + public void DeleteJournalItemByKey(int portalId, string objectKey) + { + this.dataService.Journal_DeleteByKey(portalId, objectKey); + } + + /// HARD deletes journal items based on group ID. + /// The portal ID. + /// The group ID. + public void DeleteJournalItemByGroupId(int portalId, int groupId) + { + this.dataService.Journal_DeleteByGroupId(portalId, groupId); + } + + /// SOFT deletes journal items. + /// The portal ID. + /// The user ID. + /// The journal ID. + public void SoftDeleteJournalItem(int portalId, int currentUserId, int journalId) + { + this.DeleteJournalItem(portalId, currentUserId, journalId, true); + } + + /// SOFT deletes journal items based on item key. + /// The portal ID. + /// The key. + public void SoftDeleteJournalItemByKey(int portalId, string objectKey) + { + this.dataService.Journal_SoftDeleteByKey(portalId, objectKey); + } + + /// SOFT deletes journal items based on group ID. + /// The portal ID. + /// The group ID. + public void SoftDeleteJournalItemByGroupId(int portalId, int groupId) + { + this.dataService.Journal_SoftDeleteByGroupId(portalId, groupId); + } + + /// + public IList GetCommentsByJournalIds(List journalIdList) + { + var journalIds = journalIdList.Aggregate(string.Empty, (current, journalId) => current + journalId + ";"); + return CBO.FillCollection(this.dataService.Journal_Comment_ListByJournalIds(journalIds)); + } + + /// + public void LikeJournalItem(int journalId, int userId, string displayName) + { + this.dataService.Journal_Like(journalId, userId, displayName); + } + + /// + public void SaveComment(CommentInfo comment) + { + if (!string.IsNullOrEmpty(comment.Comment)) + { + comment.Comment = + this.portalSecurity.InputFilter(comment.Comment, PortalSecurity.FilterFlag.NoScripting); + } + + // TODO: enable once the profanity filter is working properly. + // objCommentInfo.Comment = portalSecurity.Remove(objCommentInfo.Comment, DotNetNuke.Security.PortalSecurity.ConfigType.ListController, "ProfanityFilter", DotNetNuke.Security.PortalSecurity.FilterScope.PortalList); + string xml = null; + if (comment.CommentXML != null) + { + xml = comment.CommentXML.OuterXml; + } + + comment.CommentId = this.dataService.Journal_Comment_Save(comment.JournalId, comment.CommentId, comment.UserId, comment.Comment, xml, Null.NullDate); + + var newComment = this.GetComment(comment.CommentId); + comment.DateCreated = newComment.DateCreated; + comment.DateUpdated = newComment.DateUpdated; + } + + /// + public CommentInfo GetComment(int commentId) + { + return CBO.FillObject(this.dataService.Journal_Comment_Get(commentId)); + } + + /// + public void DeleteComment(int journalId, int commentId) + { + this.dataService.Journal_Comment_Delete(journalId, commentId); + + // UNDONE: update the parent journal item and content item so this comment gets removed from search index + } + + /// + public void LikeComment(int journalId, int commentId, int userId, string displayName) + { + this.dataService.Journal_Comment_Like(journalId, commentId, userId, displayName); + } + + /// + public JournalTypeInfo GetJournalType(string journalType) + { + return CBO.FillObject(this.dataService.Journal_Types_Get(journalType)); + } + + /// + public JournalTypeInfo GetJournalTypeById(int journalTypeId) + { + return CBO.FillObject(this.dataService.Journal_Types_GetById(journalTypeId)); + } + + /// + public IEnumerable GetJournalTypes(int portalId) + { + return CBO.GetCachedObject>( + this.hostSettings, + new CacheItemArgs( + string.Format(CultureInfo.InvariantCulture, DataCache.JournalTypesCacheKey, portalId), + DataCache.JournalTypesTimeOut, + DataCache.JournalTypesCachePriority, + portalId), + _ => CBO.FillCollection(this.dataService.Journal_Types_List(portalId))); + } + + private static XmlElement CreateElement(XmlDocument xDoc, string name, string value) + { + var element = xDoc.CreateElement(name); + var xtext = xDoc.CreateTextNode(value); + element.AppendChild(xtext); + return element; + } + + private static XmlElement CreateCDataElement(XmlDocument xDoc, string name, string value) + { + var element = xDoc.CreateElement(name); + var xdata = xDoc.CreateCDataSection(value); + element.AppendChild(xdata); + return element; + } + + private static MemoryStream GetJournalImageContent(Stream fileContent) + { + Image image = new Bitmap(fileContent); + var thumbnailWidth = 400; + var thumbnailHeight = 400; + GetThumbnailSize(image.Width, image.Height, ref thumbnailWidth, ref thumbnailHeight); + var thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight, () => true, IntPtr.Zero); + var result = new MemoryStream(); + thumbnail.Save(result, image.RawFormat); + return result; + } + + private static void GetThumbnailSize(int imageWidth, int imageHeight, ref int thumbnailWidth, ref int thumbnailHeight) + { + if (imageWidth >= imageHeight) + { + thumbnailWidth = Math.Min(imageWidth, thumbnailWidth); + thumbnailHeight = GetMinorSize(imageHeight, imageWidth, thumbnailWidth); + } + else + { + thumbnailHeight = Math.Min(imageHeight, thumbnailHeight); + thumbnailWidth = GetMinorSize(imageWidth, imageHeight, thumbnailHeight); + } + } + + private static int GetMinorSize(int imageMinorSize, int imageMajorSize, int thumbnailMajorSize) + { + if (imageMajorSize == thumbnailMajorSize) + { + return imageMinorSize; + } + + double calculated = (Convert.ToDouble(imageMinorSize) * Convert.ToDouble(thumbnailMajorSize)) / Convert.ToDouble(imageMajorSize); + return Convert.ToInt32(Math.Round(calculated)); + } + + private static bool IsImageFile(string fileName) + { + return (Globals.ImageFileTypes + ",").IndexOf(Path.GetExtension(fileName).Replace(".", string.Empty) + ",", StringComparison.InvariantCultureIgnoreCase) > -1; + } + + private static bool IsResizePhotosEnabled(ModuleInfo module) + { + return GetBooleanSetting(AllowResizePhotosSetting, false, module) && + GetBooleanSetting(AllowPhotosSetting, true, module) && + GetBooleanSetting(EditorEnabledSetting, true, module); + } + + private static bool GetBooleanSetting(string settingName, bool defaultValue, ModuleInfo module) + { + if (module.ModuleSettings.Contains(settingName)) + { + return Convert.ToBoolean(module.ModuleSettings[settingName].ToString()); + } + + return defaultValue; + } + + // none of the parameters should be null; checked before calling this method + private void PrepareSecuritySet(JournalItem journalItem) + { + var originalSecuritySet = + journalItem.SecuritySet = (journalItem.SecuritySet ?? string.Empty).ToUpperInvariant(); + + if (string.IsNullOrEmpty(journalItem.SecuritySet)) + { + journalItem.SecuritySet = "E,"; + } + else if (!journalItem.SecuritySet.EndsWith(",", StringComparison.Ordinal)) + { + journalItem.SecuritySet += ","; + originalSecuritySet = journalItem.SecuritySet; + } + + if (journalItem.SecuritySet == "F,") + { + journalItem.SecuritySet = "F" + journalItem.UserId + ","; + if (journalItem.ProfileId > 0) + { + journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; + } + } + else if (journalItem.SecuritySet == "U,") + { + journalItem.SecuritySet += "U" + journalItem.UserId + ","; + } + else if (journalItem.SecuritySet == "R,") + { + if (journalItem.SocialGroupId > 0) + { + journalItem.SecuritySet += "R" + journalItem.SocialGroupId + ","; + } + } + + if (journalItem.ProfileId > 0 && journalItem.UserId != journalItem.ProfileId) + { + if (!journalItem.SecuritySet.Contains("P" + journalItem.ProfileId + ",")) + { + journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; + } + + if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId + ",")) + { + journalItem.SecuritySet += "U" + journalItem.UserId + ","; + } + } + + if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId + ",")) + { + journalItem.SecuritySet += "U" + journalItem.UserId + ","; + } + + // if the post is marked as private, we shouldn't make it visible to the group. + if (journalItem.SocialGroupId > 0 && originalSecuritySet.Contains("U,")) + { + var item = journalItem; + var role = this.roleController.GetRole( + journalItem.PortalId, + r => r.SecurityMode != SecurityMode.SecurityRole && r.RoleID == item.SocialGroupId); + + if (role != null && !role.IsPublic) + { + journalItem.SecuritySet = journalItem.SecuritySet.Replace("E,", string.Empty).Replace("C,", string.Empty); + } + } + + // clean up and remove duplicates + var parts = journalItem.SecuritySet + .Replace(" ", string.Empty) + .Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) + .Distinct() + .Except(InvalidSecuritySetsWithoutId) + .Where(p => p.IndexOfAny(ValidSecurityDescriptors) >= 0); + + // TODO: validate existence and visibility/accessability of all Roles added to the set (if any) + journalItem.SecuritySet = string.Join(",", parts); + } + + private void UpdateGroupStats(int portalId, int groupId) + { + var role = this.roleController.GetRole(portalId, r => r.RoleID == groupId); + if (role is null) + { + return; + } + + for (var i = 0; i < role.Settings.Keys.Count; i++) + { + var key = role.Settings.Keys.ElementAt(i); + if (key.StartsWith("stat_", StringComparison.OrdinalIgnoreCase)) + { + role.Settings[key] = "0"; + } + } + + using (var dr = this.dataService.Journal_GetStatsForGroup(portalId, groupId)) + { + while (dr.Read()) + { + var settingName = "stat_" + dr["JournalType"]; + if (role.Settings.ContainsKey(settingName)) + { + role.Settings[settingName] = dr["JournalTypeCount"].ToString(); + } + else + { + role.Settings.Add(settingName, dr["JournalTypeCount"].ToString()); + } + } + + dr.Close(); + } + + this.roleController.UpdateRoleSettings(role, true); + } + + private void DeleteJournalItem(int portalId, int currentUserId, int journalId, bool softDelete) + { + var ji = this.GetJournalItem(portalId, currentUserId, journalId, !softDelete); + if (ji == null) + { + return; + } + + var groupId = ji.SocialGroupId; + + if (softDelete) + { + this.dataService.Journal_SoftDelete(journalId); + } + else + { + this.dataService.Journal_Delete(journalId); + } + + if (groupId > 0) + { + this.UpdateGroupStats(portalId, groupId); + } + + // queue remove journal from search index + var document = new SearchDocumentToDelete + { + PortalId = portalId, + AuthorUserId = currentUserId, + UniqueKey = ji.ContentItemId.ToString("D", CultureInfo.InvariantCulture), + + // QueryString = "journalid=" + journalId, + SearchTypeId = this.searchHelper.GetSearchTypeByName("module").SearchTypeId, + }; + + if (groupId > 0) + { + document.RoleId = groupId; + } + + this.dataProvider.AddSearchDeletedItems(document); + } +} diff --git a/DNN Platform/Library/Services/Journal/JournalEntity.cs b/DNN Platform/Library/Services/Journal/JournalEntity.cs index 2f66a52e7dd..dc234ba7556 100644 --- a/DNN Platform/Library/Services/Journal/JournalEntity.cs +++ b/DNN Platform/Library/Services/Journal/JournalEntity.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Journal { + using System.Globalization; using System.Xml; using DotNetNuke.Services.Tokens; @@ -21,7 +22,7 @@ public JournalEntity(string entityXML) { if (!string.IsNullOrEmpty(entityXML)) { - XmlDocument xDoc = new XmlDocument { XmlResolver = null }; + var xDoc = new XmlDocument { XmlResolver = null, }; xDoc.LoadXml(entityXML); if (xDoc != null) { @@ -30,7 +31,7 @@ public JournalEntity(string entityXML) xNode = xRoot.SelectSingleNode("//entity"); if (xNode != null) { - this.Id = int.Parse(xNode["id"].InnerText); + this.Id = int.Parse(xNode["id"].InnerText, CultureInfo.InvariantCulture); this.Name = xNode["name"].InnerText.ToString(); if (xNode["vanity"] != null) { @@ -72,13 +73,13 @@ public string GetProperty(string propertyName, string format, System.Globalizati switch (propertyName) { case "id": - return PropertyAccess.FormatString(this.Id.ToString(), format); + return PropertyAccess.FormatString(this.Id.ToString(formatProvider), format); case "name": - return PropertyAccess.FormatString(this.Name.ToString(), format); + return PropertyAccess.FormatString(this.Name, format); case "vanity": - return PropertyAccess.FormatString(this.Vanity.ToString(), format); + return PropertyAccess.FormatString(this.Vanity, format); case "avatar": - return PropertyAccess.FormatString(this.Avatar.ToString(), format); + return PropertyAccess.FormatString(this.Avatar, format); } propertyNotFound = true; diff --git a/DNN Platform/Library/Services/Journal/JournalItem.cs b/DNN Platform/Library/Services/Journal/JournalItem.cs index 5e9fec460a5..03f0528f0ca 100644 --- a/DNN Platform/Library/Services/Journal/JournalItem.cs +++ b/DNN Platform/Library/Services/Journal/JournalItem.cs @@ -2,187 +2,187 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Journal -{ - using System; - using System.Data; - using System.Xml; - using System.Xml.Serialization; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Modules; +{ + using System; + using System.Data; + using System.Xml; + using System.Xml.Serialization; + + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; using DotNetNuke.Services.Tokens; using Newtonsoft.Json; public class JournalItem : IHydratable, IPropertyAccess { /// - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - - public int JournalId { get; set; } - - public int JournalTypeId { get; set; } - - public int PortalId { get; set; } - - public int UserId { get; set; } - - public int ProfileId { get; set; } - - public int SocialGroupId { get; set; } - - public string Title { get; set; } - - public string Summary { get; set; } - - public string Body { get; set; } - - public ItemData ItemData { get; set; } - - public XmlDocument JournalXML { get; set; } - - public DateTime DateCreated { get; set; } - - public DateTime DateUpdated { get; set; } - - public string ObjectKey { get; set; } - - public Guid AccessKey { get; set; } - - public string SecuritySet { get; set; } - - public int ContentItemId { get; set; } - - public JournalEntity JournalAuthor { get; set; } - - public JournalEntity JournalOwner { get; set; } - - public string TimeFrame { get; set; } - - public bool CurrentUserLikes { get; set; } - - public string JournalType { get; set; } - - public bool IsDeleted { get; set; } - - public bool CommentsDisabled { get; set; } - - public bool CommentsHidden { get; set; } - - public int SimilarCount { get; set; } - - /// Gets or sets the key ID. - /// - /// The key ID. - /// - /// - /// If you derive class has its own key id, please override this property and set the value to your own key id. - /// + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + + public int JournalId { get; set; } + + public int JournalTypeId { get; set; } + + public int PortalId { get; set; } + + public int UserId { get; set; } + + public int ProfileId { get; set; } + + public int SocialGroupId { get; set; } + + public string Title { get; set; } + + public string Summary { get; set; } + + public string Body { get; set; } + + public ItemData ItemData { get; set; } + + public XmlDocument JournalXML { get; set; } + + public DateTime DateCreated { get; set; } + + public DateTime DateUpdated { get; set; } + + public string ObjectKey { get; set; } + + public Guid AccessKey { get; set; } + + public string SecuritySet { get; set; } + + public int ContentItemId { get; set; } + + public JournalEntity JournalAuthor { get; set; } + + public JournalEntity JournalOwner { get; set; } + + public string TimeFrame { get; set; } + + public bool CurrentUserLikes { get; set; } + + public string JournalType { get; set; } + + public bool IsDeleted { get; set; } + + public bool CommentsDisabled { get; set; } + + public bool CommentsHidden { get; set; } + + public int SimilarCount { get; set; } + + /// Gets or sets the key ID. + /// + /// The key ID. + /// + /// + /// If you derive class has its own key id, please override this property and set the value to your own key id. + /// [XmlIgnore] - [JsonIgnore] - public virtual int KeyID - { - get - { - return this.JournalId; - } - - set - { - this.JournalId = value; - } + [JsonIgnore] + public virtual int KeyID + { + get + { + return this.JournalId; + } + + set + { + this.JournalId = value; + } } /// - public void Fill(IDataReader dr) - { - this.JournalId = Null.SetNullInteger(dr["JournalId"]); - this.JournalTypeId = Null.SetNullInteger(dr["JournalTypeId"]); - this.PortalId = Null.SetNullInteger(dr["PortalId"]); - this.UserId = Null.SetNullInteger(dr["UserId"]); - this.ProfileId = Null.SetNullInteger(dr["ProfileId"]); - this.SocialGroupId = Null.SetNullInteger(dr["GroupId"]); - if (!string.IsNullOrEmpty(Null.SetNullString(dr["JournalXML"]))) - { - this.JournalXML = new XmlDocument { XmlResolver = null }; - this.JournalXML.LoadXml(dr["JournalXML"].ToString()); - XmlNode xRoot = this.JournalXML.DocumentElement; - XmlNode xNode = xRoot.SelectSingleNode("//items/item/body"); - if (xNode != null) - { - this.Body = xNode.InnerText; - } - } - - this.DateCreated = Null.SetNullDateTime(dr["DateCreated"]); - this.DateUpdated = Null.SetNullDateTime(dr["DateUpdated"]); - this.ObjectKey = Null.SetNullString(dr["ObjectKey"]); - this.AccessKey = Null.SetNullGuid(dr["AccessKey"]); - this.Title = Null.SetNullString(dr["Title"]); - this.Summary = Null.SetNullString(dr["Summary"]); - string itemd = Null.SetNullString(dr["ItemData"]); - this.ItemData = new ItemData(); - if (!string.IsNullOrEmpty(itemd)) - { - this.ItemData = itemd.FromJson(); - } - - this.ContentItemId = Null.SetNullInteger(dr["ContentItemId"]); - this.JournalAuthor = new JournalEntity(dr["JournalAuthor"].ToString()); - this.JournalOwner = new JournalEntity(dr["JournalOwner"].ToString()); - this.JournalType = Null.SetNullString(dr["JournalType"]); - - this.IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); - this.CommentsDisabled = Null.SetNullBoolean(dr["CommentsDisabled"]); - this.CommentsHidden = Null.SetNullBoolean(dr["CommentsHidden"]); - this.SimilarCount = Null.SetNullInteger(dr["SimilarCount"]); + public void Fill(IDataReader dr) + { + this.JournalId = Null.SetNullInteger(dr["JournalId"]); + this.JournalTypeId = Null.SetNullInteger(dr["JournalTypeId"]); + this.PortalId = Null.SetNullInteger(dr["PortalId"]); + this.UserId = Null.SetNullInteger(dr["UserId"]); + this.ProfileId = Null.SetNullInteger(dr["ProfileId"]); + this.SocialGroupId = Null.SetNullInteger(dr["GroupId"]); + if (!string.IsNullOrEmpty(Null.SetNullString(dr["JournalXML"]))) + { + this.JournalXML = new XmlDocument { XmlResolver = null }; + this.JournalXML.LoadXml(dr["JournalXML"].ToString()); + XmlNode xRoot = this.JournalXML.DocumentElement; + XmlNode xNode = xRoot.SelectSingleNode("//items/item/body"); + if (xNode != null) + { + this.Body = xNode.InnerText; + } + } + + this.DateCreated = Null.SetNullDateTime(dr["DateCreated"]); + this.DateUpdated = Null.SetNullDateTime(dr["DateUpdated"]); + this.ObjectKey = Null.SetNullString(dr["ObjectKey"]); + this.AccessKey = Null.SetNullGuid(dr["AccessKey"]); + this.Title = Null.SetNullString(dr["Title"]); + this.Summary = Null.SetNullString(dr["Summary"]); + string itemd = Null.SetNullString(dr["ItemData"]); + this.ItemData = new ItemData(); + if (!string.IsNullOrEmpty(itemd)) + { + this.ItemData = itemd.FromJson(); + } + + this.ContentItemId = Null.SetNullInteger(dr["ContentItemId"]); + this.JournalAuthor = new JournalEntity(dr["JournalAuthor"].ToString()); + this.JournalOwner = new JournalEntity(dr["JournalOwner"].ToString()); + this.JournalType = Null.SetNullString(dr["JournalType"]); + + this.IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); + this.CommentsDisabled = Null.SetNullBoolean(dr["CommentsDisabled"]); + this.CommentsHidden = Null.SetNullBoolean(dr["CommentsHidden"]); + this.SimilarCount = Null.SetNullInteger(dr["SimilarCount"]); } /// - public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) - { - string outputFormat = string.Empty; - if (format == string.Empty) - { - outputFormat = "g"; - } - else - { - outputFormat = format; - } - - propertyName = propertyName.ToLowerInvariant(); - switch (propertyName) - { - case "journalid": - return PropertyAccess.FormatString(this.JournalId.ToString(), format); - case "journaltypeid": - return PropertyAccess.FormatString(this.JournalTypeId.ToString(), format); - case "profileid": - return PropertyAccess.FormatString(this.ProfileId.ToString(), format); - case "socialgroupid": - return PropertyAccess.FormatString(this.SocialGroupId.ToString(), format); - case "datecreated": - return PropertyAccess.FormatString(this.DateCreated.ToString(), format); - case "title": - return PropertyAccess.FormatString(this.Title, format); - case "summary": - return PropertyAccess.FormatString(this.Summary, format); - case "body": - return PropertyAccess.FormatString(this.Body, format); - case "timeframe": - return PropertyAccess.FormatString(this.TimeFrame, format); - case "isdeleted": - return this.IsDeleted.ToString(); - } - - propertyNotFound = true; - return string.Empty; - } - } -} + public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { + string outputFormat = string.Empty; + if (format == string.Empty) + { + outputFormat = "g"; + } + else + { + outputFormat = format; + } + + propertyName = propertyName.ToLowerInvariant(); + switch (propertyName) + { + case "journalid": + return PropertyAccess.FormatString(this.JournalId.ToString(formatProvider), format); + case "journaltypeid": + return PropertyAccess.FormatString(this.JournalTypeId.ToString(formatProvider), format); + case "profileid": + return PropertyAccess.FormatString(this.ProfileId.ToString(formatProvider), format); + case "socialgroupid": + return PropertyAccess.FormatString(this.SocialGroupId.ToString(formatProvider), format); + case "datecreated": + return PropertyAccess.FormatString(this.DateCreated.ToString(formatProvider), format); + case "title": + return PropertyAccess.FormatString(this.Title, format); + case "summary": + return PropertyAccess.FormatString(this.Summary, format); + case "body": + return PropertyAccess.FormatString(this.Body, format); + case "timeframe": + return PropertyAccess.FormatString(this.TimeFrame, format); + case "isdeleted": + return this.IsDeleted.ToString(); + } + + propertyNotFound = true; + return string.Empty; + } + } +} diff --git a/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs b/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs index 6e92cc9c5a6..586dabbe486 100644 --- a/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs +++ b/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { + using System; using System.Collections; using System.Globalization; @@ -20,15 +21,12 @@ public CultureInfoComparer(string compareBy) /// public int Compare(object x, object y) { - switch (this.compare.ToUpperInvariant()) + return this.compare.ToUpperInvariant() switch { - case "ENGLISH": - return ((CultureInfo)x).EnglishName.CompareTo(((CultureInfo)y).EnglishName); - case "NATIVE": - return ((CultureInfo)x).NativeName.CompareTo(((CultureInfo)y).NativeName); - default: - return ((CultureInfo)x).Name.CompareTo(((CultureInfo)y).Name); - } + "ENGLISH" => string.Compare(((CultureInfo)x).EnglishName, ((CultureInfo)y).EnglishName, StringComparison.Ordinal), + "NATIVE" => string.Compare(((CultureInfo)x).NativeName, ((CultureInfo)y).NativeName, StringComparison.Ordinal), + _ => string.Compare(((CultureInfo)x).Name, ((CultureInfo)y).Name, StringComparison.Ordinal), + }; } } } diff --git a/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs b/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs index 59df902777f..dda530c29a4 100644 --- a/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs +++ b/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs @@ -52,7 +52,7 @@ public string BestCultureCodeBasedOnBrowserLanguages(IEnumerable culture lang = lang.Substring(0, 2); // check for language match e.g. en-GB == en-US because en == en - var match = values.FirstOrDefault(x => x.StartsWith(lang)); + var match = values.FirstOrDefault(x => x.StartsWith(lang, StringComparison.OrdinalIgnoreCase)); if (match != null) { return match; diff --git a/DNN Platform/Library/Services/Localization/LocaleCollection.cs b/DNN Platform/Library/Services/Localization/LocaleCollection.cs index 5b1bd4dbdee..76d9cef4cdb 100644 --- a/DNN Platform/Library/Services/Localization/LocaleCollection.cs +++ b/DNN Platform/Library/Services/Localization/LocaleCollection.cs @@ -1,78 +1,174 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Localization -{ - using System; - using System.Collections; +namespace DotNetNuke.Services.Localization +{ + using System; + using System.Collections; + using System.Collections.Generic; using System.Collections.Specialized; + using System.Linq; - /// The LocaleCollection class is a collection of Locale objects. It stores the supported locales. - public class LocaleCollection : NameObjectCollectionBase - { - private DictionaryEntry de; - - // Gets a String array that contains all the keys in the collection. - public string[] AllKeys - { - get - { - return this.BaseGetAllKeys(); - } - } - - // Gets an Object array that contains all the values in the collection. - public Array AllValues - { - get - { - return this.BaseGetAllValues(); - } - } - - // Gets a value indicating if the collection contains keys that are not null. - public bool HasKeys - { - get - { - return this.BaseHasKeys(); - } - } - - public DictionaryEntry this[int index] - { - get - { - this.de.Key = this.BaseGetKey(index); - this.de.Value = this.BaseGet(index); - return this.de; - } - } - - // Gets or sets the value associated with the specified key. - public Locale this[string key] - { - get - { - return (Locale)this.BaseGet(key); - } - - set - { - this.BaseSet(key, value); - } - } - - // Adds an entry to the collection. - public void Add(string key, object value) - { - this.BaseAdd(key, value); - } - - // Removes an entry with the specified key from the collection. - public void Remove(string key) - { - this.BaseRemove(key); - } - } -} + using DotNetNuke.Common; + + /// The LocaleCollection class is a collection of Locale objects. It stores the supported locales. + public class LocaleCollection : NameObjectCollectionBase, IDictionary + { + private DictionaryEntry de; + + /// Gets a String array that contains all the keys in the collection. + public string[] AllKeys => this.BaseGetAllKeys(); + + /// Gets an Object array that contains all the values in the collection. + public Array AllValues => this.BaseGetAllValues(); + + /// Gets a value indicating whether the collection contains keys that are not null. + public bool HasKeys => this.BaseHasKeys(); + + /// + bool ICollection>.IsReadOnly => this.IsReadOnly; + + /// + ICollection IDictionary.Keys => this.BaseGetAllKeys(); + + /// + public ICollection Values => this.BaseGetAllValues().Cast().ToList(); + + public DictionaryEntry this[int index] + { + get + { + this.de.Key = this.BaseGetKey(index); + this.de.Value = this.BaseGet(index); + return this.de; + } + } + + /// Gets or sets the value associated with the specified key. + /// The key. + /// The value. + public Locale this[string key] + { + get => (Locale)this.BaseGet(key); + set => this.BaseSet(key, value); + } + + /// + public bool TryGetValue(string key, out Locale value) + { + if (!this.ContainsKey(key)) + { + value = null; + return false; + } + + value = this[key]; + return true; + } + + /// Adds an entry to the collection. + /// The key. + /// The value. + public void Add(string key, object value) + { + this.BaseAdd(key, value); + } + + /// Removes an entry with the specified key from the collection. + /// The key. + public void Remove(string key) + { + this.BaseRemove(key); + } + + /// + public bool ContainsKey(string key) => this[key] is not null; + + /// + public void Add(string key, Locale value) => this.BaseAdd(key, value); + + /// + bool IDictionary.Remove(string key) + { + if (!this.ContainsKey(key)) + { + return false; + } + + this.BaseRemove(key); + return true; + } + + /// + public void Add(KeyValuePair item) => this.Add(item.Key, item.Value); + + /// + public void Clear() => this.BaseClear(); + + /// + public bool Contains(KeyValuePair item) + { + if (!this.TryGetValue(item.Key, out var value)) + { + return false; + } + + return EqualityComparer.Default.Equals(value, item.Value); + } + + /// + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + Requires.NotNull(nameof(array), array); + if (arrayIndex > array.Length) + { + throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "arrayIndex must be less than the length of array"); + } + + if (array.Length - arrayIndex < this.Count) + { + throw new ArgumentOutOfRangeException(nameof(array), array, "array length must be large enough to hold contents"); + } + + foreach (var key in this.BaseGetAllKeys()) + { + array[arrayIndex++] = new KeyValuePair(key, this[key]); + } + } + + /// + public bool Remove(KeyValuePair item) + { + if (!this.Contains(item)) + { + return false; + } + + this.BaseRemove(item.Key); + return true; + } + + /// + IEnumerator> IEnumerable>.GetEnumerator() + => new KeyValuePairEnumerator(this, this.GetEnumerator()); + + private class KeyValuePairEnumerator(LocaleCollection locales, IEnumerator enumerator) : IEnumerator> + { + /// + public KeyValuePair Current => + new KeyValuePair((string)enumerator.Current, locales[(string)enumerator.Current]); + + /// + object IEnumerator.Current => this.Current; + + /// + public void Dispose() => (enumerator as IDisposable)?.Dispose(); + + /// + public bool MoveNext() => enumerator.MoveNext(); + + /// + public void Reset() => enumerator.Reset(); + } + } +} diff --git a/DNN Platform/Library/Services/Localization/LocaleController.cs b/DNN Platform/Library/Services/Localization/LocaleController.cs index e800f73d03c..00dce6c7589 100644 --- a/DNN Platform/Library/Services/Localization/LocaleController.cs +++ b/DNN Platform/Library/Services/Localization/LocaleController.cs @@ -189,7 +189,7 @@ public Dictionary GetLocales(int portalID) } var cacheArgs = new CacheItemArgs( - string.Format(DataCache.LocalesCacheKey, portalID), + string.Format(CultureInfo.InvariantCulture, DataCache.LocalesCacheKey, portalID), DataCache.LocalesCacheTimeOut, DataCache.LocalesCachePriority, portalID, @@ -259,7 +259,7 @@ public bool IsEnabled(ref string localeCode, int portalId) public void UpdatePortalLocale(Locale locale) { this.dataProvider.UpdatePortalLanguage(locale.PortalId, locale.LanguageId, locale.IsPublished, this.userController.GetCurrentUserInfo().UserID); - DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, locale.PortalId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.LocalesCacheKey, locale.PortalId)); } /// Determines the language whether is default language. diff --git a/DNN Platform/Library/Services/Localization/Localization.cs b/DNN Platform/Library/Services/Localization/Localization.cs index 31c8ca9e902..3a0f31e88a4 100644 --- a/DNN Platform/Library/Services/Localization/Localization.cs +++ b/DNN Platform/Library/Services/Localization/Localization.cs @@ -221,7 +221,7 @@ public static void AddLanguageToPortal(int portalID, int languageID, bool clearC } DataProvider.Instance().AddPortalLanguage(portalID, languageID, false, UserController.Instance.GetCurrentUserInfo().UserID); - string cacheKey = string.Format(DataCache.LocalesCacheKey, portalID); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.LocalesCacheKey, portalID); DataCache.RemoveCache(cacheKey); EventLogController.Instance.AddLog( @@ -262,7 +262,7 @@ public static void AddLanguagesToPortal(int portalID) AddLanguageToPortal(portalID, language.LanguageId, false); } - DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portalID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.LocalesCacheKey, portalID)); } public static void AddLanguageToPortals(int languageID) @@ -272,31 +272,30 @@ public static void AddLanguageToPortals(int languageID) // Add Portal/Language to PortalLanguages AddLanguageToPortal(portal.PortalID, languageID, false); - DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portal.PortalID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.LocalesCacheKey, portal.PortalID)); } } public static void AddTranslatorRole(int portalID, Locale language) { // Create new Translator Role - string roleName = string.Format("Translator ({0})", language.Code); + string roleName = $"Translator ({language.Code})"; RoleInfo role = RoleController.Instance.GetRole(portalID, r => r.RoleName == roleName); if (role == null) { - role = new RoleInfo(); - role.RoleGroupID = Null.NullInteger; - role.PortalID = portalID; - role.RoleName = roleName; - role.Description = string.Format("A role for {0} translators", language.EnglishName); - role.SecurityMode = SecurityMode.SecurityRole; - role.Status = RoleStatus.Approved; + role = new RoleInfo + { + RoleGroupID = Null.NullInteger, PortalID = portalID, RoleName = roleName, Description = $"A role for {language.EnglishName} translators", + SecurityMode = SecurityMode.SecurityRole, + Status = RoleStatus.Approved, + }; RoleController.Instance.AddRole(role); } - string roles = string.Format("Administrators;{0}", string.Format("Translator ({0})", language.Code)); + string roles = $"Administrators;Translator ({language.Code})"; - PortalController.UpdatePortalSetting(portalID, string.Format("DefaultTranslatorRoles-{0}", language.Code), roles); + PortalController.UpdatePortalSetting(portalID, $"DefaultTranslatorRoles-{language.Code}", roles); } /// Converts old TimeZoneOffset to new . @@ -466,17 +465,17 @@ public static string GetExceptionMessage(string key, string defaultValue, params { if (HttpContext.Current == null) { - return string.Format(defaultValue, @params); + return string.Format(CultureInfo.CurrentCulture, defaultValue, @params); } var content = GetString(key, ExceptionsResourceFile); - return string.Format(string.IsNullOrEmpty(content) ? defaultValue : GetString(key, ExceptionsResourceFile), @params); + return string.Format(CultureInfo.CurrentCulture, string.IsNullOrEmpty(content) ? defaultValue : GetString(key, ExceptionsResourceFile), @params); } public static string GetLanguageDisplayMode(int portalId) { string viewTypePersonalizationKey = "ViewType" + portalId; - string viewType = Convert.ToString(Personalization.Personalization.GetProfile("LanguageDisplayMode", viewTypePersonalizationKey)); + string viewType = Convert.ToString(Personalization.Personalization.GetProfile("LanguageDisplayMode", viewTypePersonalizationKey), CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(viewType)) { viewType = "NATIVE"; @@ -499,7 +498,7 @@ public static string GetLocaleName(string code, CultureDropDownTypes displayType name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(info.EnglishName); break; case CultureDropDownTypes.Lcid: - name = info.LCID.ToString(); + name = info.LCID.ToString(CultureInfo.CurrentCulture); break; case CultureDropDownTypes.Name: name = info.Name; @@ -629,30 +628,30 @@ public static CultureInfo GetBrowserCulture(int portalId) public static string GetResourceFileName(string resourceFileName, string language, string mode, int portalId) { - if (!resourceFileName.EndsWith(".resx")) + if (!resourceFileName.EndsWith(".resx", StringComparison.OrdinalIgnoreCase)) { resourceFileName += ".resx"; } if (language != SystemLocale) { - if (resourceFileName.ToLowerInvariant().EndsWith(".en-us.resx")) + if (resourceFileName.EndsWith(".en-us.resx", StringComparison.OrdinalIgnoreCase)) { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 11) + "." + language + ".resx"; + resourceFileName = $"{resourceFileName.Substring(0, resourceFileName.Length - 11)}.{language}.resx"; } else { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + language + ".resx"; + resourceFileName = $"{resourceFileName.Substring(0, resourceFileName.Length - 5)}.{language}.resx"; } } if (mode == "Host") { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Host.resx"; + resourceFileName = $"{resourceFileName.Substring(0, resourceFileName.Length - 5)}.Host.resx"; } else if (mode == "Portal") { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Portal-" + portalId + ".resx"; + resourceFileName = $"{resourceFileName.Substring(0, resourceFileName.Length - 5)}.Portal-{portalId}.resx"; } return resourceFileName; @@ -1365,7 +1364,7 @@ public static void RemoveLanguageFromPortal(int portalID, int languageID, bool i } // Get Translator Role - string roleName = string.Format("Translator ({0})", language.Code); + string roleName = $"Translator ({language.Code})"; RoleInfo role = RoleController.Instance.GetRole(portalID, r => r.RoleName == roleName); if (role != null) @@ -1534,7 +1533,7 @@ public string GetFixedCurrency(decimal expression, string culture, int numDigits string oldCurrentCulture = this.CurrentUICulture; var newCulture = new CultureInfo(culture); Thread.CurrentThread.CurrentUICulture = newCulture; - string currencyStr = expression.ToString(newCulture.NumberFormat.CurrencySymbol); + string currencyStr = expression.ToString(newCulture.NumberFormat.CurrencySymbol, newCulture); var oldCulture = new CultureInfo(oldCurrentCulture); Thread.CurrentThread.CurrentUICulture = oldCulture; return currencyStr; @@ -1545,7 +1544,7 @@ public string GetFixedDate(DateTime expression, string culture) string oldCurrentCulture = this.CurrentUICulture; var newCulture = new CultureInfo(culture); Thread.CurrentThread.CurrentUICulture = newCulture; - string dateStr = expression.ToString(newCulture.DateTimeFormat.FullDateTimePattern); + string dateStr = expression.ToString(newCulture.DateTimeFormat.FullDateTimePattern, newCulture); var oldCulture = new CultureInfo(oldCurrentCulture); Thread.CurrentThread.CurrentUICulture = oldCulture; return dateStr; @@ -1556,7 +1555,7 @@ public string GetFixedDate(DateTime expression, string culture) /// If an exact match is not found (language-region), it will try to find a match for the language only. /// Ex: requested locale is "en-GB", requested language is "en", enabled locale is "en-US", so "en" is a match for "en-US". /// - /// Id of current portal. + /// ID of current portal. /// Language to be parsed. /// A valid and enabled CultureInfo that matches the language passed if any. internal static CultureInfo GetCultureFromString(int portalId, string language) @@ -1729,14 +1728,14 @@ private static void AddLanguageHttpAlias(int portalId, Locale locale) } } - var alias = GetValidLanguageURL(portalId, httpAlias, locale.Code.ToLowerInvariant()); + var alias = GetValidLanguageUrl(portalId, httpAlias, locale.Code.ToLowerInvariant()); if (!string.IsNullOrEmpty(alias)) { var newAlias = new PortalAliasInfo(currentAlias) { IsPrimary = true, CultureCode = locale.Code, - HTTPAlias = GetValidLanguageURL(portalId, httpAlias, locale.Code.ToLowerInvariant()), + HTTPAlias = GetValidLanguageUrl(portalId, httpAlias, locale.Code.ToLowerInvariant()), }; PortalAliasController.Instance.AddPortalAlias(newAlias); @@ -1745,21 +1744,21 @@ private static void AddLanguageHttpAlias(int portalId, Locale locale) } } - private static string GetValidLanguageURL(int portalId, string httpAlias, string locale) + private static string GetValidLanguageUrl(int portalId, string httpAlias, string locale) { string alias; bool isValid; - int counter = 0; + var counter = 0; do { - string modifiedLocale = locale; + var modifiedLocale = locale; if (counter > 0) { modifiedLocale += counter.ToString(CultureInfo.InvariantCulture); } - alias = string.Format("{0}/{1}", httpAlias, modifiedLocale); + alias = $"{httpAlias}/{modifiedLocale}"; var tab = TabController.Instance.GetTabByName(modifiedLocale, portalId); isValid = tab == null; diff --git a/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs b/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs index b8a2ae37ae7..426b2130f83 100644 --- a/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs +++ b/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs @@ -45,7 +45,7 @@ public static object GetLocalizedResource(string key, Type targetType, string pr if (value == null) { - throw new InvalidOperationException(string.Format("Localized Value '{0}' not found.", key)); + throw new InvalidOperationException($"Localized Value '{key}' not found."); } // check if value can be converted to property type @@ -57,9 +57,10 @@ public static object GetLocalizedResource(string key, Type targetType, string pr // Type mismatch - make sure that the value can be converted to the Web control property type if (propDesc.Converter != null) { - if (propDesc.Converter.CanConvertFrom(value.GetType()) == false) + if (!propDesc.Converter.CanConvertFrom(value.GetType())) { - throw new InvalidOperationException(string.Format("Localized value '{0}' cannot be converted to type {1}.", key, propDesc.PropertyType)); + throw new InvalidOperationException( + $"Localized value '{key}' cannot be converted to type {propDesc.PropertyType}."); } return propDesc.Converter.ConvertFrom(value); diff --git a/DNN Platform/Library/Services/Localization/LocalizationProvider.cs b/DNN Platform/Library/Services/Localization/LocalizationProvider.cs index 2ddf76b264a..f529ee87600 100644 --- a/DNN Platform/Library/Services/Localization/LocalizationProvider.cs +++ b/DNN Platform/Library/Services/Localization/LocalizationProvider.cs @@ -6,6 +6,8 @@ namespace DotNetNuke.Services.Localization { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Linq; using System.Threading; @@ -82,7 +84,7 @@ public string GetString(string key, string resourceFileRoot, string language, Po if (!keyFound) { - Logger.WarnFormat("Missing localization key. key:{0} resFileRoot:{1} threadCulture:{2} userlan:{3}", key, resourceFileRoot, Thread.CurrentThread.CurrentUICulture, language); + Logger.WarnFormat(CultureInfo.InvariantCulture, "Missing localization key. key:{0} resFileRoot:{1} threadCulture:{2} userlan:{3}", key, resourceFileRoot, Thread.CurrentThread.CurrentUICulture, language); } return string.IsNullOrEmpty(resourceValue) ? string.Empty : resourceValue; @@ -99,6 +101,7 @@ public string GetString(string key, string resourceFileRoot, string language, Po /// if set to a new key will be created if not found. /// If the value could be saved then true will be returned, otherwise false. /// Any file io error or similar will lead to exceptions. + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public bool SaveString(string key, string value, string resourceFileRoot, string language, PortalSettings portalSettings, CustomizedLocale resourceType, bool createFile, bool createKey) { try @@ -603,7 +606,7 @@ private static bool TryGetFromResourceFile(string key, string resourceFile, int { if (Globals.ApplicationPath != "/portals") { - if (cacheKey.StartsWith(Globals.ApplicationPath)) + if (cacheKey.StartsWith(Globals.ApplicationPath, StringComparison.OrdinalIgnoreCase)) { cacheKey = cacheKey.Substring(Globals.ApplicationPath.Length); } @@ -611,7 +614,7 @@ private static bool TryGetFromResourceFile(string key, string resourceFile, int else { cacheKey = "~" + cacheKey; - if (cacheKey.StartsWith("~" + Globals.ApplicationPath)) + if (cacheKey.StartsWith("~" + Globals.ApplicationPath, StringComparison.OrdinalIgnoreCase)) { cacheKey = cacheKey.Substring(Globals.ApplicationPath.Length + 1); } diff --git a/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs b/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs index 3e2d07d3308..3492f6c6b81 100644 --- a/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs +++ b/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs @@ -8,6 +8,8 @@ namespace DotNetNuke.Services.Log.EventLog using System.Collections.Generic; using System.Data; using System.Data.SqlClient; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Threading; using System.Web; using System.Web.Caching; @@ -38,7 +40,7 @@ public class DBLoggingProvider : LoggingProvider public override void AddLog(LogInfo logInfo) { string configPortalId = logInfo.LogPortalID != Null.NullInteger - ? logInfo.LogPortalID.ToString() + ? logInfo.LogPortalID.ToString(CultureInfo.InvariantCulture) : "*"; var logTypeConfigInfo = this.GetLogTypeConfigInfoByKey(logInfo.LogTypeKey, configPortalId); if (logTypeConfigInfo is not { LoggingIsActive: true, }) @@ -70,6 +72,7 @@ public override void AddLogType(string logTypeKey, string logTypeFriendlyName, s } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override void AddLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string thresholdTime, string thresholdTimeType, string mailFromAddress, string mailToAddress) { int intThreshold = -1; @@ -78,22 +81,22 @@ public override void AddLogTypeConfigInfo(string id, bool loggingIsActive, strin int intKeepMostRecent = -1; if (Globals.NumberMatchRegex.IsMatch(threshold)) { - intThreshold = Convert.ToInt32(threshold); + intThreshold = Convert.ToInt32(threshold, CultureInfo.InvariantCulture); } if (Globals.NumberMatchRegex.IsMatch(thresholdTime)) { - intThresholdTime = Convert.ToInt32(thresholdTime); + intThresholdTime = Convert.ToInt32(thresholdTime, CultureInfo.InvariantCulture); } if (Globals.NumberMatchRegex.IsMatch(thresholdTimeType)) { - intThresholdTimeType = Convert.ToInt32(thresholdTimeType); + intThresholdTimeType = Convert.ToInt32(thresholdTimeType, CultureInfo.InvariantCulture); } if (Globals.NumberMatchRegex.IsMatch(keepMostRecent)) { - intKeepMostRecent = Convert.ToInt32(keepMostRecent); + intKeepMostRecent = Convert.ToInt32(keepMostRecent, CultureInfo.InvariantCulture); } DataProvider.Instance().AddLogTypeConfigInfo( @@ -179,7 +182,7 @@ public override ArrayList GetLogTypeConfigInfo() /// public override LogTypeConfigInfo GetLogTypeConfigInfoByID(string id) { - return CBO.FillObject(DataProvider.Instance().GetLogTypeConfigInfoByID(Convert.ToInt32(id))); + return CBO.FillObject(DataProvider.Instance().GetLogTypeConfigInfoByID(Convert.ToInt32(id, CultureInfo.InvariantCulture))); } /// @@ -233,13 +236,13 @@ public override ILogInfo GetLog(string logGuid) /// public override bool LoggingIsEnabled(string logType, int portalID) { - string configPortalID = portalID.ToString(); + string configPortalId = portalID.ToString(CultureInfo.InvariantCulture); if (portalID == -1) { - configPortalID = "*"; + configPortalId = "*"; } - LogTypeConfigInfo configInfo = this.GetLogTypeConfigInfoByKey(logType, configPortalID); + LogTypeConfigInfo configInfo = this.GetLogTypeConfigInfoByKey(logType, configPortalId); if (configInfo == null) { return false; @@ -285,7 +288,7 @@ public override void SendLogNotifications() List configInfos = CBO.FillCollection(DataProvider.Instance().GetEventLogPendingNotifConfig()); foreach (LogTypeConfigInfo typeConfigInfo in configInfos) { - IDataReader dr = DataProvider.Instance().GetEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID)); + IDataReader dr = DataProvider.Instance().GetEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID, CultureInfo.InvariantCulture)); string log = string.Empty; try { @@ -300,8 +303,8 @@ public override void SendLogNotifications() CBO.CloseDataReader(dr, true); } - Mail.Mail.SendEmail(typeConfigInfo.MailFromAddress, typeConfigInfo.MailToAddress, "Event Notification", string.Format("
    {0}
    ", HttpUtility.HtmlEncode(log))); - DataProvider.Instance().UpdateEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID)); + Mail.Mail.SendEmail(typeConfigInfo.MailFromAddress, typeConfigInfo.MailToAddress, "Event Notification", $"
    {HttpUtility.HtmlEncode(log)}
    "); + DataProvider.Instance().UpdateEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID, CultureInfo.InvariantCulture)); } } @@ -339,6 +342,7 @@ public override void UpdateLogType(string logTypeKey, string logTypeFriendlyName } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string thresholdTime, string thresholdTimeType, string mailFromAddress, string mailToAddress) { var intThreshold = -1; @@ -347,22 +351,22 @@ public override void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, st var intKeepMostRecent = -1; if (Globals.NumberMatchRegex.IsMatch(threshold)) { - intThreshold = Convert.ToInt32(threshold); + intThreshold = Convert.ToInt32(threshold, CultureInfo.InvariantCulture); } if (Globals.NumberMatchRegex.IsMatch(thresholdTime)) { - intThresholdTime = Convert.ToInt32(thresholdTime); + intThresholdTime = Convert.ToInt32(thresholdTime, CultureInfo.InvariantCulture); } if (Globals.NumberMatchRegex.IsMatch(thresholdTimeType)) { - intThresholdTimeType = Convert.ToInt32(thresholdTimeType); + intThresholdTimeType = Convert.ToInt32(thresholdTimeType, CultureInfo.InvariantCulture); } if (Globals.NumberMatchRegex.IsMatch(keepMostRecent)) { - intKeepMostRecent = Convert.ToInt32(keepMostRecent); + intKeepMostRecent = Convert.ToInt32(keepMostRecent, CultureInfo.InvariantCulture); } DataProvider.Instance().UpdateLogTypeConfigInfo( @@ -410,30 +414,30 @@ private static LogInfo FillLogInfo(IDataReader dr) var obj = new LogInfo(); try { - obj.LogCreateDate = Convert.ToDateTime(dr["LogCreateDate"]); - obj.LogGUID = Convert.ToString(dr["LogGUID"]); - obj.LogPortalID = Convert.ToInt32(Null.SetNull(dr["LogPortalID"], obj.LogPortalID)); - obj.LogPortalName = Convert.ToString(Null.SetNull(dr["LogPortalName"], obj.LogPortalName)); - obj.LogServerName = Convert.ToString(Null.SetNull(dr["LogServerName"], obj.LogServerName)); - obj.LogUserID = Convert.ToInt32(Null.SetNull(dr["LogUserID"], obj.LogUserID)); - obj.LogEventID = Convert.ToInt32(Null.SetNull(dr["LogEventID"], obj.LogEventID)); - obj.LogTypeKey = Convert.ToString(dr["LogTypeKey"]); - obj.LogUserName = Convert.ToString(dr["LogUserName"]); - obj.LogConfigID = Convert.ToString(dr["LogConfigID"]); - obj.LogProperties.Deserialize(Convert.ToString(dr["LogProperties"])); - obj.Exception.AssemblyVersion = Convert.ToString(Null.SetNull(dr["AssemblyVersion"], obj.Exception.AssemblyVersion)); - obj.Exception.PortalId = Convert.ToInt32(Null.SetNull(dr["PortalId"], obj.Exception.PortalId)); - obj.Exception.UserId = Convert.ToInt32(Null.SetNull(dr["UserId"], obj.Exception.UserId)); - obj.Exception.TabId = Convert.ToInt32(Null.SetNull(dr["TabId"], obj.Exception.TabId)); - obj.Exception.RawUrl = Convert.ToString(Null.SetNull(dr["RawUrl"], obj.Exception.RawUrl)); - obj.Exception.Referrer = Convert.ToString(Null.SetNull(dr["Referrer"], obj.Exception.Referrer)); - obj.Exception.UserAgent = Convert.ToString(Null.SetNull(dr["UserAgent"], obj.Exception.UserAgent)); - obj.Exception.ExceptionHash = Convert.ToString(Null.SetNull(dr["ExceptionHash"], obj.Exception.ExceptionHash)); - obj.Exception.Message = Convert.ToString(Null.SetNull(dr["Message"], obj.Exception.Message)); - obj.Exception.StackTrace = Convert.ToString(Null.SetNull(dr["StackTrace"], obj.Exception.StackTrace)); - obj.Exception.InnerMessage = Convert.ToString(Null.SetNull(dr["InnerMessage"], obj.Exception.InnerMessage)); - obj.Exception.InnerStackTrace = Convert.ToString(Null.SetNull(dr["InnerStackTrace"], obj.Exception.InnerStackTrace)); - obj.Exception.Source = Convert.ToString(Null.SetNull(dr["Source"], obj.Exception.Source)); + obj.LogCreateDate = Convert.ToDateTime(dr["LogCreateDate"], CultureInfo.InvariantCulture); + obj.LogGUID = Convert.ToString(dr["LogGUID"], CultureInfo.InvariantCulture); + obj.LogPortalID = Convert.ToInt32(Null.SetNull(dr["LogPortalID"], obj.LogPortalID), CultureInfo.InvariantCulture); + obj.LogPortalName = Convert.ToString(Null.SetNull(dr["LogPortalName"], obj.LogPortalName), CultureInfo.InvariantCulture); + obj.LogServerName = Convert.ToString(Null.SetNull(dr["LogServerName"], obj.LogServerName), CultureInfo.InvariantCulture); + obj.LogUserID = Convert.ToInt32(Null.SetNull(dr["LogUserID"], obj.LogUserID), CultureInfo.InvariantCulture); + obj.LogEventID = Convert.ToInt32(Null.SetNull(dr["LogEventID"], obj.LogEventID), CultureInfo.InvariantCulture); + obj.LogTypeKey = Convert.ToString(dr["LogTypeKey"], CultureInfo.InvariantCulture); + obj.LogUserName = Convert.ToString(dr["LogUserName"], CultureInfo.InvariantCulture); + obj.LogConfigID = Convert.ToString(dr["LogConfigID"], CultureInfo.InvariantCulture); + obj.LogProperties.Deserialize(Convert.ToString(dr["LogProperties"], CultureInfo.InvariantCulture)); + obj.Exception.AssemblyVersion = Convert.ToString(Null.SetNull(dr["AssemblyVersion"], obj.Exception.AssemblyVersion), CultureInfo.InvariantCulture); + obj.Exception.PortalId = Convert.ToInt32(Null.SetNull(dr["PortalId"], obj.Exception.PortalId), CultureInfo.InvariantCulture); + obj.Exception.UserId = Convert.ToInt32(Null.SetNull(dr["UserId"], obj.Exception.UserId), CultureInfo.InvariantCulture); + obj.Exception.TabId = Convert.ToInt32(Null.SetNull(dr["TabId"], obj.Exception.TabId), CultureInfo.InvariantCulture); + obj.Exception.RawUrl = Convert.ToString(Null.SetNull(dr["RawUrl"], obj.Exception.RawUrl), CultureInfo.InvariantCulture); + obj.Exception.Referrer = Convert.ToString(Null.SetNull(dr["Referrer"], obj.Exception.Referrer), CultureInfo.InvariantCulture); + obj.Exception.UserAgent = Convert.ToString(Null.SetNull(dr["UserAgent"], obj.Exception.UserAgent), CultureInfo.InvariantCulture); + obj.Exception.ExceptionHash = Convert.ToString(Null.SetNull(dr["ExceptionHash"], obj.Exception.ExceptionHash), CultureInfo.InvariantCulture); + obj.Exception.Message = Convert.ToString(Null.SetNull(dr["Message"], obj.Exception.Message), CultureInfo.InvariantCulture); + obj.Exception.StackTrace = Convert.ToString(Null.SetNull(dr["StackTrace"], obj.Exception.StackTrace), CultureInfo.InvariantCulture); + obj.Exception.InnerMessage = Convert.ToString(Null.SetNull(dr["InnerMessage"], obj.Exception.InnerMessage), CultureInfo.InvariantCulture); + obj.Exception.InnerStackTrace = Convert.ToString(Null.SetNull(dr["InnerStackTrace"], obj.Exception.InnerStackTrace), CultureInfo.InvariantCulture); + obj.Exception.Source = Convert.ToString(Null.SetNull(dr["Source"], obj.Exception.Source), CultureInfo.InvariantCulture); /* DNN-6218 + DNN-6242: DB logging provider throws errors // the view "vw_EventLog" doesn't have these fields or any table in the database obj.Exception.FileName = Convert.ToString(Null.SetNull(dr["FileName"], obj.Exception.FileName)); @@ -463,7 +467,7 @@ private static void FillLogs(IDataReader dr, IList logs, ref int totalRecords) dr.NextResult(); while (dr.Read()) { - totalRecords = Convert.ToInt32(dr["TotalRecords"]); + totalRecords = Convert.ToInt32(dr["TotalRecords"], CultureInfo.InvariantCulture); } } finally @@ -517,7 +521,7 @@ private static void WriteLog(LogQueueItem logQueueItem) objLogInfo.LogCreateDate, objLogInfo.LogServerName, logProperties, - Convert.ToInt32(objLogInfo.LogConfigID), + Convert.ToInt32(objLogInfo.LogConfigID, CultureInfo.InvariantCulture), objLogInfo.Exception, logTypeConfigInfo.EmailNotificationIsActive); if (logTypeConfigInfo.EmailNotificationIsActive) @@ -529,7 +533,7 @@ private static void WriteLog(LogQueueItem logQueueItem) if (logTypeConfigInfo.NotificationThreshold == 0) { string str = logQueueItem.LogInfo.Serialize(); - Mail.Mail.SendEmail(logTypeConfigInfo.MailFromAddress, logTypeConfigInfo.MailToAddress, "Event Notification", string.Format("
    {0}
    ", HttpUtility.HtmlEncode(str))); + Mail.Mail.SendEmail(logTypeConfigInfo.MailFromAddress, logTypeConfigInfo.MailToAddress, "Event Notification", $"
    {HttpUtility.HtmlEncode(str)}
    "); } } finally diff --git a/DNN Platform/Library/Services/Log/EventLog/EventLogExtensions.cs b/DNN Platform/Library/Services/Log/EventLog/EventLogExtensions.cs index abec88a37eb..3d9adcfdbda 100644 --- a/DNN Platform/Library/Services/Log/EventLog/EventLogExtensions.cs +++ b/DNN Platform/Library/Services/Log/EventLog/EventLogExtensions.cs @@ -3,6 +3,8 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Log.EventLog { + using System.Globalization; + using DotNetNuke.Abstractions.Logging; /// Extensions methods for types related to the Event Log. @@ -20,7 +22,7 @@ public static void AddSettingLog(this IEventLogger logger, EventLogType logTypeK { ILogInfo log = new LogInfo { LogTypeKey = logTypeKey.ToString(), }; log.LogUserId = userId; - log.LogProperties.Add(new LogDetailInfo(idFieldName, idValue.ToString())); + log.LogProperties.Add(new LogDetailInfo(idFieldName, idValue.ToString(CultureInfo.InvariantCulture))); log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); log.LogProperties.Add(new LogDetailInfo("SettingValue", settingValue)); diff --git a/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs b/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs index 5036cdcea21..3c197bdf221 100644 --- a/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Services.Log.EventLog using System.Data.SqlClient; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web; using DotNetNuke.Common; @@ -17,6 +18,7 @@ public class ExceptionLogController : LogController { public enum ExceptionLogType { +#pragma warning disable CA1707 // Identifiers should not contain underscores /// A general exception. GENERAL_EXCEPTION = 0, @@ -37,6 +39,7 @@ public enum ExceptionLogType /// An exception related to data issues. DATA_EXCEPTION = 6, +#pragma warning restore CA1707 } public void AddLog(Exception objException) @@ -97,8 +100,8 @@ public void AddLog(Exception objException, LogInfo log, ExceptionLogType logType { // Add ModuleLoadException Properties var objModuleLoadException = (ModuleLoadException)objException; - log.LogProperties.Add(new LogDetailInfo("ModuleId", objModuleLoadException.ModuleId.ToString())); - log.LogProperties.Add(new LogDetailInfo("ModuleDefId", objModuleLoadException.ModuleDefId.ToString())); + log.LogProperties.Add(new LogDetailInfo("ModuleId", objModuleLoadException.ModuleId.ToString(CultureInfo.InvariantCulture))); + log.LogProperties.Add(new LogDetailInfo("ModuleDefId", objModuleLoadException.ModuleDefId.ToString(CultureInfo.InvariantCulture))); log.LogProperties.Add(new LogDetailInfo("FriendlyName", objModuleLoadException.FriendlyName)); log.LogProperties.Add(new LogDetailInfo("ModuleControlSource", objModuleLoadException.ModuleControlSource)); } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogController.cs b/DNN Platform/Library/Services/Log/EventLog/LogController.cs index 13281608df4..015544c77d7 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogController.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Services.Log.EventLog using System.Collections; using System.Collections.Generic; using System.Data.SqlClient; + using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -176,8 +177,8 @@ public void AddLogType(string configFile, string fallbackConfigFile) LogTypePortalID = typeConfigInfo.Attributes["LogTypePortalID"].Value, MailFromAddress = typeConfigInfo.Attributes["MailFromAddress"].Value, MailToAddress = typeConfigInfo.Attributes["MailToAddress"].Value, - NotificationThreshold = Convert.ToInt32(typeConfigInfo.Attributes["NotificationThreshold"].Value), - NotificationThresholdTime = Convert.ToInt32(typeConfigInfo.Attributes["NotificationThresholdTime"].Value), + NotificationThreshold = Convert.ToInt32(typeConfigInfo.Attributes["NotificationThreshold"].Value, CultureInfo.InvariantCulture), + NotificationThresholdTime = Convert.ToInt32(typeConfigInfo.Attributes["NotificationThresholdTime"].Value, CultureInfo.InvariantCulture), NotificationThresholdTimeType = (LogTypeConfigInfo.NotificationThresholdTimeTypes)Enum.Parse(typeof(LogTypeConfigInfo.NotificationThresholdTimeTypes), typeConfigInfo.Attributes["NotificationThresholdTimeType"].Value), }; @@ -204,9 +205,9 @@ public void AddLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) logTypeConfig.KeepMostRecent, logTypeConfig.LogFileName, logTypeConfig.EmailNotificationIsActive, - Convert.ToString(logTypeConfig.NotificationThreshold), - Convert.ToString(logTypeConfig.NotificationThresholdTime), - Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), + Convert.ToString(logTypeConfig.NotificationThreshold, CultureInfo.InvariantCulture), + Convert.ToString(logTypeConfig.NotificationThresholdTime, CultureInfo.InvariantCulture), + Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType, CultureInfo.InvariantCulture), logTypeConfig.MailFromAddress, logTypeConfig.MailToAddress); } @@ -288,9 +289,9 @@ public virtual void UpdateLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) logTypeConfig.KeepMostRecent, logTypeConfig.LogFileName, logTypeConfig.EmailNotificationIsActive, - Convert.ToString(logTypeConfig.NotificationThreshold), - Convert.ToString(logTypeConfig.NotificationThresholdTime), - Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), + Convert.ToString(logTypeConfig.NotificationThreshold, CultureInfo.InvariantCulture), + Convert.ToString(logTypeConfig.NotificationThresholdTime, CultureInfo.InvariantCulture), + Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType, CultureInfo.InvariantCulture), logTypeConfig.MailFromAddress, logTypeConfig.MailToAddress); } @@ -324,7 +325,7 @@ private static void AddLogToFile(LogInfo logInfo) private static void RaiseError(string filePath, string header, string message) { - Logger.ErrorFormat("filePath={0}, header={1}, message={2}", filePath, header, message); + Logger.ErrorFormat(CultureInfo.InvariantCulture, "filePath={0}, header={1}, message={2}", filePath, header, message); if (HttpContext.Current != null) { diff --git a/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs index 8a854732763..bdc11526438 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs @@ -4,6 +4,8 @@ namespace DotNetNuke.Services.Log.EventLog { using System; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Text; using System.Xml; @@ -113,9 +115,10 @@ public static bool IsSystemType(string propName) } return false; - } - + } + /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public void AddProperty(string propertyName, string propertyValue) { try @@ -192,7 +195,7 @@ public void ReadXml(XmlReader reader) this.LogPortalName = reader.ReadContentAsString(); break; case "LogCreateDate": - this.LogCreateDate = DateTime.Parse(reader.ReadContentAsString()); + this.LogCreateDate = DateTime.Parse(reader.ReadContentAsString(), CultureInfo.InvariantCulture); break; case "LogCreateDateNum": this.LogCreateDateNum = reader.ReadContentAsLong(); @@ -270,13 +273,13 @@ public void WriteXml(XmlWriter writer) writer.WriteAttributeString("LogGUID", ((ILogInfo)this).LogGuid); writer.WriteAttributeString("LogFileID", ((ILogInfo)this).LogFileId); writer.WriteAttributeString("LogTypeKey", this.LogTypeKey); - writer.WriteAttributeString("LogUserID", ((ILogInfo)this).LogUserId.ToString()); - writer.WriteAttributeString("LogEventID", ((ILogInfo)this).LogEventId.ToString()); + writer.WriteAttributeString("LogUserID", ((ILogInfo)this).LogUserId.ToString(CultureInfo.InvariantCulture)); + writer.WriteAttributeString("LogEventID", ((ILogInfo)this).LogEventId.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("LogUserName", this.LogUserName); - writer.WriteAttributeString("LogPortalID", ((ILogInfo)this).LogPortalId.ToString()); + writer.WriteAttributeString("LogPortalID", ((ILogInfo)this).LogPortalId.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("LogPortalName", this.LogPortalName); - writer.WriteAttributeString("LogCreateDate", this.LogCreateDate.ToString()); - writer.WriteAttributeString("LogCreateDateNum", this.LogCreateDateNum.ToString()); + writer.WriteAttributeString("LogCreateDate", this.LogCreateDate.ToString(CultureInfo.InvariantCulture)); + writer.WriteAttributeString("LogCreateDateNum", this.LogCreateDateNum.ToString(CultureInfo.InvariantCulture)); writer.WriteAttributeString("BypassBuffering", this.BypassBuffering.ToString()); writer.WriteAttributeString("LogServerName", this.LogServerName); writer.WriteAttributeString("LogConfigID", ((ILogInfo)this).LogConfigId); diff --git a/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs b/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs index a0fa25c2af3..792030e3b4b 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs @@ -1,34 +1,41 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Log.EventLog +namespace DotNetNuke.Services.Log.EventLog { using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; - using System.Text; + using System.Text; using System.Xml; using DotNetNuke.Abstractions.Logging; using DotNetNuke.Common.Utilities; - /// - public class LogProperties : ArrayList, ILogProperties + /// + public class LogProperties : ArrayList, ILogProperties, IList { - /// - public string Summary - { - get - { - string summary = HtmlUtils.Clean(this.ToString(), true); - if (summary.Length > 75) - { - summary = summary.Substring(0, 75); - } - - return summary; - } + /// + public string Summary + { + get + { + string summary = HtmlUtils.Clean(this.ToString(), true); + if (summary.Length > 75) + { + summary = summary.Substring(0, 75); + } + + return summary; + } + } + + /// + ILogDetailInfo IList.this[int index] + { + get => (ILogDetailInfo)this[index]; + set => this[index] = value; } /// @@ -43,6 +50,14 @@ public bool Contains(ILogDetailInfo item) => public void CopyTo(ILogDetailInfo[] array, int arrayIndex) => base.CopyTo(array, arrayIndex); + /// + public int IndexOf(ILogDetailInfo item) + => base.IndexOf(item); + + /// + public void Insert(int index, ILogDetailInfo item) + => base.Insert(index, item); + /// IEnumerator IEnumerable.GetEnumerator() => this.ToArray().Cast().GetEnumerator(); @@ -60,73 +75,68 @@ public bool Remove(ILogDetailInfo item) return false; } - public void Deserialize(string content) - { - using (XmlReader reader = XmlReader.Create(new StringReader(content))) - { - reader.ReadStartElement("LogProperties"); - if (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !string.IsNullOrEmpty(reader.LocalName)) - { - this.ReadXml(reader); - } - - reader.Close(); - } - } - - public void ReadXml(XmlReader reader) - { - do - { - reader.ReadStartElement("LogProperty"); - - // Create new LogDetailInfo object - var logDetail = new LogDetailInfo(); - - // Load it from the Xml - logDetail.ReadXml(reader); - - // Add to the collection - this.Add(logDetail); - } - while (reader.ReadToNextSibling("LogProperty")); + public void Deserialize(string content) + { + using var reader = XmlReader.Create(new StringReader(content)); + reader.ReadStartElement("LogProperties"); + if (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !string.IsNullOrEmpty(reader.LocalName)) + { + this.ReadXml(reader); + } + + reader.Close(); } - public string Serialize() - { - var settings = new XmlWriterSettings(); - settings.ConformanceLevel = ConformanceLevel.Fragment; - settings.OmitXmlDeclaration = true; - var sb = new StringBuilder(); - using (XmlWriter writer = XmlWriter.Create(sb, settings)) - { - this.WriteXml(writer); - writer.Close(); - return sb.ToString(); - } + public void ReadXml(XmlReader reader) + { + do + { + reader.ReadStartElement("LogProperty"); + + // Create new LogDetailInfo object + var logDetail = new LogDetailInfo(); + + // Load it from the Xml + logDetail.ReadXml(reader); + + // Add to the collection + this.Add(logDetail); + } + while (reader.ReadToNextSibling("LogProperty")); + } + + public string Serialize() + { + var settings = new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Fragment, OmitXmlDeclaration = true, }; + var sb = new StringBuilder(); + + using var writer = XmlWriter.Create(sb, settings); + this.WriteXml(writer); + writer.Close(); + return sb.ToString(); } /// - public override string ToString() - { - var sb = new StringBuilder(); - foreach (LogDetailInfo logDetail in this) - { - sb.Append(logDetail.ToString()); - } - - return sb.ToString(); - } - - public void WriteXml(XmlWriter writer) - { - writer.WriteStartElement("LogProperties"); - foreach (LogDetailInfo logDetail in this) - { - logDetail.WriteXml(writer); - } - - writer.WriteEndElement(); + public override string ToString() + { + var sb = new StringBuilder(); + foreach (LogDetailInfo logDetail in this) + { + sb.Append(logDetail.ToString()); + } + + return sb.ToString(); + } + + public void WriteXml(XmlWriter writer) + { + writer.WriteStartElement("LogProperties"); + foreach (LogDetailInfo logDetail in this) + { + logDetail.WriteXml(writer); + } + + writer.WriteEndElement(); } - } -} + } +} diff --git a/DNN Platform/Library/Services/Mail/CoreMailProvider.cs b/DNN Platform/Library/Services/Mail/CoreMailProvider.cs index 3ecda52d2ee..87cf620b2be 100644 --- a/DNN Platform/Library/Services/Mail/CoreMailProvider.cs +++ b/DNN Platform/Library/Services/Mail/CoreMailProvider.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Mail { using System; + using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -250,8 +251,8 @@ private static (string Host, int? Port, string ErrorMessage) ParseSmtpServer(ref } // port is guaranteed to be of max 5 digits numeric by the RegEx check - var port = int.Parse(smtpHostParts[1]); - if (port < 1 || port > 65535) + var port = int.Parse(smtpHostParts[1], CultureInfo.InvariantCulture); + if (port is < 1 or > 65535) { return (null, null, Localize.GetString("SmtpInvalidPort")); } diff --git a/DNN Platform/Library/Services/Mail/Mail.cs b/DNN Platform/Library/Services/Mail/Mail.cs index ce3d775e00f..77ccbfb83fb 100644 --- a/DNN Platform/Library/Services/Mail/Mail.cs +++ b/DNN Platform/Library/Services/Mail/Mail.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Mail using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Net.Mail; @@ -40,7 +41,7 @@ public static bool IsValidEmailAddress(string email, int portalid) // During install Wizard we may not have a valid PortalID if (portalid != Null.NullInteger) { - pattern = Convert.ToString(UserController.GetUserSettings(portalid)["Security_EmailValidation"]); + pattern = Convert.ToString(UserController.GetUserSettings(portalid)["Security_EmailValidation"], CultureInfo.InvariantCulture); } pattern = string.IsNullOrEmpty(pattern) ? Globals.glbEmailRegEx : pattern; @@ -227,8 +228,9 @@ public static string SendMail(int portalId, int userId, MessageType msgType, Por subject = Localize.GetSystemMessage(locale, settings, subject, user, Localize.GlobalResourceFile, custom, string.Empty, settings.AdministratorId); body = Localize.GetSystemMessage(locale, settings, body, user, Localize.GlobalResourceFile, custom, string.Empty, settings.AdministratorId); - var fromUser = (UserController.GetUserByEmail(settings.PortalId, settings.Email) != null) ? - string.Format("{0} < {1} >", UserController.GetUserByEmail(settings.PortalId, settings.Email).DisplayName, settings.Email) : settings.Email; + var fromUser = UserController.GetUserByEmail(settings.PortalId, settings.Email) != null + ? $"{UserController.GetUserByEmail(settings.PortalId, settings.Email).DisplayName} < {settings.Email} >" + : settings.Email; SendEmail(fromUser, UserController.GetUserById(settings.PortalId, toUser).Email, subject, body); return Null.NullString; diff --git a/DNN Platform/Library/Services/Mail/MailKitMailProvider.cs b/DNN Platform/Library/Services/Mail/MailKitMailProvider.cs index 32f38a3a72b..2ab44fbfc0e 100644 --- a/DNN Platform/Library/Services/Mail/MailKitMailProvider.cs +++ b/DNN Platform/Library/Services/Mail/MailKitMailProvider.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Mail { using System; + using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Threading; @@ -168,8 +169,8 @@ private static (string Host, int Port, string ErrorMessage) ParseSmtpServer(ref } // port is guaranteed to be of max 5 digits numeric by the RegEx check - port = int.Parse(smtpHostParts[1]); - if (port < 1 || port > 65535) + port = int.Parse(smtpHostParts[1], CultureInfo.InvariantCulture); + if (port is < 1 or > 65535) { return (host, port, Localize.GetString("SmtpInvalidPort")); } diff --git a/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs b/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs index 83479437ad7..f82e9d36572 100644 --- a/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs +++ b/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs @@ -100,6 +100,7 @@ public SendTokenizedBulkEmail(List addressedRoles, List addres // Existing public API public enum AddressMethods { +#pragma warning disable CA1707 // Identifiers should not contain underscores /// Put the recipient's email address in the TO field. Send_TO = 1, @@ -108,6 +109,7 @@ public enum AddressMethods /// Send via an email relay address. Send_Relay = 3, +#pragma warning restore CA1707 } /// Gets or sets priority of emails to be sent. @@ -565,7 +567,7 @@ private void SendConfirmationMail(int numRecipients, int numMessages, int numErr }; this.tokenReplace.User = this.sendingUser; string body = this.tokenReplace.ReplaceEnvironmentTokens(this.BodyFormat == MailFormat.Html ? this.confirmBodyHTML : this.confirmBodyText, parameters, "Custom"); - string strSubject = string.Format(this.confirmSubject, subject); + string strSubject = string.Format(CultureInfo.CurrentCulture, this.confirmSubject, subject); if (!this.SuppressTokenReplace) { strSubject = this.tokenReplace.ReplaceEnvironmentTokens(strSubject); @@ -578,7 +580,7 @@ private void SendConfirmationMail(int numRecipients, int numMessages, int numErr /// check, if the user's language matches the current language filter. /// Language of the user. - /// userlanguage matches current languageFilter. + /// matches current . /// if filter not set, true is returned. private bool MatchLanguageFilter(string userLanguage) { diff --git a/DNN Platform/Library/Services/Messaging/Data/Message.cs b/DNN Platform/Library/Services/Messaging/Data/Message.cs index 3fe789a9bf6..8405525f4cb 100644 --- a/DNN Platform/Library/Services/Messaging/Data/Message.cs +++ b/DNN Platform/Library/Services/Messaging/Data/Message.cs @@ -1,342 +1,342 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Messaging.Data -{ - using System; - using System.Data; +namespace DotNetNuke.Services.Messaging.Data +{ + using System; + using System.Data; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Modules; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; using DotNetNuke.Security; - /// The Info class for Messaging. - [Serializable] - public class Message : IHydratable - { - private string body; - private Guid conversation; - private bool emailSent; - private int fromUserID; - private string fromUserName; - private DateTime messageDate; - private int messageID; - private int portalID; - private int replyTo; - private MessageStatusType status; - private string subject; - private int toRoleId; - private int toUserID; - private string toUserName; - - private bool allowReply; - private bool skipInbox; - - private Guid emailSchedulerInstance; + /// The Info class for Messaging. + [Serializable] + public class Message : IHydratable + { + private string body; + private Guid conversation; + private bool emailSent; + private int fromUserID; + private string fromUserName; + private DateTime messageDate; + private int messageID; + private int portalID; + private int replyTo; + private MessageStatusType status; + private string subject; + private int toRoleId; + private int toUserID; + private string toUserName; + + private bool allowReply; + private bool skipInbox; + + private Guid emailSchedulerInstance; private DateTime emailSentDate; /// Initializes a new instance of the class. - public Message() - { - this.Conversation = Guid.Empty; - this.Status = MessageStatusType.Draft; - this.MessageDate = DateTime.Now; - } - - public string FromUserName - { - get - { - return this.fromUserName; - } - - private set - { - this.fromUserName = value; - } - } - - public int FromUserID - { - get - { - return this.fromUserID; - } - - set - { - this.fromUserID = value; - } - } - - public int ToRoleID - { - get - { - return this.toRoleId; - } - - set - { - this.toRoleId = value; - } - } - - public bool AllowReply - { - get - { - return this.allowReply; - } - - set - { - this.allowReply = value; - } - } - - public bool SkipInbox - { - get - { - return this.skipInbox; - } - - set - { - this.skipInbox = value; - } - } - - public bool EmailSent - { - get - { - return this.emailSent; - } - - set - { - this.emailSent = value; - } - } - - public string Body - { - get - { - return this.body; - } - - set - { - this.body = value; - } - } - - public DateTime MessageDate - { - get - { - return this.messageDate; - } - - set - { - this.messageDate = value; - } - } - - public Guid Conversation - { - get - { - return this.conversation; - } - - set - { - this.conversation = value; - } - } - - public int MessageID - { - get - { - return this.messageID; - } - - private set - { - this.messageID = value; - } - } - - public int PortalID - { - get - { - return this.portalID; - } - - set - { - this.portalID = value; - } - } - - public int ReplyTo - { - get - { - return this.replyTo; - } - - private set - { - this.replyTo = value; - } - } - - public MessageStatusType Status - { - get - { - return this.status; - } - - set - { - this.status = value; - } - } - - public string Subject - { - get - { - var ps = PortalSecurity.Instance; - return ps.InputFilter(this.subject, PortalSecurity.FilterFlag.NoMarkup); - } - - set - { - var ps = PortalSecurity.Instance; - ps.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); - this.subject = ps.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); - } - } - - public int ToUserID - { - get - { - return this.toUserID; - } - - set - { - this.toUserID = value; - } - } - - public string ToUserName - { - get - { - return this.toUserName; - } - - private set - { - this.toUserName = value; - } - } - - public DateTime EmailSentDate - { - get - { - return this.emailSentDate; - } - - private set - { - this.emailSentDate = value; - } - } - - public Guid EmailSchedulerInstance - { - get - { - return this.emailSchedulerInstance; - } - - private set - { - this.emailSchedulerInstance = value; - } + public Message() + { + this.Conversation = Guid.Empty; + this.Status = MessageStatusType.Draft; + this.MessageDate = DateTime.Now; + } + + public string FromUserName + { + get + { + return this.fromUserName; + } + + private set + { + this.fromUserName = value; + } + } + + public int FromUserID + { + get + { + return this.fromUserID; + } + + set + { + this.fromUserID = value; + } + } + + public int ToRoleID + { + get + { + return this.toRoleId; + } + + set + { + this.toRoleId = value; + } + } + + public bool AllowReply + { + get + { + return this.allowReply; + } + + set + { + this.allowReply = value; + } + } + + public bool SkipInbox + { + get + { + return this.skipInbox; + } + + set + { + this.skipInbox = value; + } + } + + public bool EmailSent + { + get + { + return this.emailSent; + } + + set + { + this.emailSent = value; + } + } + + public string Body + { + get + { + return this.body; + } + + set + { + this.body = value; + } + } + + public DateTime MessageDate + { + get + { + return this.messageDate; + } + + set + { + this.messageDate = value; + } + } + + public Guid Conversation + { + get + { + return this.conversation; + } + + set + { + this.conversation = value; + } + } + + public int MessageID + { + get + { + return this.messageID; + } + + private set + { + this.messageID = value; + } + } + + public int PortalID + { + get + { + return this.portalID; + } + + set + { + this.portalID = value; + } + } + + public int ReplyTo + { + get + { + return this.replyTo; + } + + private set + { + this.replyTo = value; + } + } + + public MessageStatusType Status + { + get + { + return this.status; + } + + set + { + this.status = value; + } + } + + public string Subject + { + get + { + var ps = PortalSecurity.Instance; + return ps.InputFilter(this.subject, PortalSecurity.FilterFlag.NoMarkup); + } + + set + { + var ps = PortalSecurity.Instance; + ps.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + this.subject = ps.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + } + } + + public int ToUserID + { + get + { + return this.toUserID; + } + + set + { + this.toUserID = value; + } + } + + public string ToUserName + { + get + { + return this.toUserName; + } + + private set + { + this.toUserName = value; + } + } + + public DateTime EmailSentDate + { + get + { + return this.emailSentDate; + } + + private set + { + this.emailSentDate = value; + } + } + + public Guid EmailSchedulerInstance + { + get + { + return this.emailSchedulerInstance; + } + + private set + { + this.emailSchedulerInstance = value; + } } /// - public int KeyID - { - get - { - return this.MessageID; - } - - set - { - this.MessageID = value; - } - } - - public Message GetReplyMessage() - { - var message = new Message(); - message.AllowReply = this.AllowReply; - message.Body = string.Format("


    On {0} {1} wrote ", this.MessageDate, this.FromUserName) + this.Body; - message.Conversation = this.Conversation; - message.FromUserID = this.ToUserID; - message.ToUserID = this.FromUserID; - message.ToUserName = this.FromUserName; - message.PortalID = this.PortalID; - message.ReplyTo = this.MessageID; - message.SkipInbox = this.SkipInbox; - message.Subject = "RE:" + this.Subject; - - return message; + public int KeyID + { + get + { + return this.MessageID; + } + + set + { + this.MessageID = value; + } + } + + public Message GetReplyMessage() + { + return new Message + { + AllowReply = this.AllowReply, + Body = $"


    On {this.MessageDate} {this.FromUserName} wrote {this.Body}", + Conversation = this.Conversation, + FromUserID = this.ToUserID, + ToUserID = this.FromUserID, + ToUserName = this.FromUserName, + PortalID = this.PortalID, + ReplyTo = this.MessageID, + SkipInbox = this.SkipInbox, + Subject = "RE:" + this.Subject, + }; } /// - public void Fill(IDataReader dr) - { - this.MessageID = Null.SetNullInteger(dr["MessageID"]); - this.PortalID = Null.SetNullInteger(dr["PortalID"]); - this.FromUserID = Null.SetNullInteger(dr["FromUserID"]); - this.FromUserName = Null.SetNullString(dr["FromUserName"]); - this.ToUserID = Null.SetNullInteger(dr["ToUserID"]); - - // '_ToUserName = Null.SetNullString(dr.Item("ToUserName")) - this.ReplyTo = Null.SetNullInteger(dr["ReplyTo"]); - this.Status = (MessageStatusType)Enum.Parse(typeof(MessageStatusType), Null.SetNullString(dr["Status"])); - this.Body = Null.SetNullString(dr["Body"]); - this.Subject = Null.SetNullString(dr["Subject"]); - this.MessageDate = Null.SetNullDateTime(dr["Date"]); - this.ToRoleID = Null.SetNullInteger(dr["ToRoleID"]); - this.AllowReply = Null.SetNullBoolean(dr["AllowReply"]); - this.SkipInbox = Null.SetNullBoolean(dr["SkipPortal"]); - this.EmailSent = Null.SetNullBoolean(dr["EmailSent"]); - this.ToUserName = Null.SetNullString(dr["ToUserName"]); - string g = Null.SetNullString(dr["Conversation"]); - this.EmailSentDate = Null.SetNullDateTime(dr["EmailSentDate"]); - this.EmailSchedulerInstance = Null.SetNullGuid(dr["EmailSchedulerInstance"]); - this.Conversation = Null.SetNullGuid(dr["Conversation"]); - - // 'Conversation = New Guid(g) - } - } -} + public void Fill(IDataReader dr) + { + this.MessageID = Null.SetNullInteger(dr["MessageID"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.FromUserID = Null.SetNullInteger(dr["FromUserID"]); + this.FromUserName = Null.SetNullString(dr["FromUserName"]); + this.ToUserID = Null.SetNullInteger(dr["ToUserID"]); + + // '_ToUserName = Null.SetNullString(dr.Item("ToUserName")) + this.ReplyTo = Null.SetNullInteger(dr["ReplyTo"]); + this.Status = (MessageStatusType)Enum.Parse(typeof(MessageStatusType), Null.SetNullString(dr["Status"])); + this.Body = Null.SetNullString(dr["Body"]); + this.Subject = Null.SetNullString(dr["Subject"]); + this.MessageDate = Null.SetNullDateTime(dr["Date"]); + this.ToRoleID = Null.SetNullInteger(dr["ToRoleID"]); + this.AllowReply = Null.SetNullBoolean(dr["AllowReply"]); + this.SkipInbox = Null.SetNullBoolean(dr["SkipPortal"]); + this.EmailSent = Null.SetNullBoolean(dr["EmailSent"]); + this.ToUserName = Null.SetNullString(dr["ToUserName"]); + string g = Null.SetNullString(dr["Conversation"]); + this.EmailSentDate = Null.SetNullDateTime(dr["EmailSentDate"]); + this.EmailSchedulerInstance = Null.SetNullGuid(dr["EmailSchedulerInstance"]); + this.Conversation = Null.SetNullGuid(dr["Conversation"]); + + // 'Conversation = New Guid(g) + } + } +} diff --git a/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs b/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs index 0aaa986805a..2139ffc9cfd 100644 --- a/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs +++ b/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs @@ -1,87 +1,89 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Messaging.Data -{ - using System; - using System.Data; +namespace DotNetNuke.Services.Messaging.Data +{ + using System; + using System.Data; + using System.Diagnostics.CodeAnalysis; using DotNetNuke.Data; - public class MessagingDataService : IMessagingDataService - { + public class MessagingDataService : IMessagingDataService + { private readonly DataProvider provider = DataProvider.Instance(); /// - public IDataReader GetMessageByID(int messageId) - { - return this.provider.ExecuteReader("Messaging_GetMessage", messageId); + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] + public IDataReader GetMessageByID(int messageId) + { + return this.provider.ExecuteReader("Messaging_GetMessage", messageId); } /// - public IDataReader GetUserInbox(int portalID, int userID, int pageNumber, int pageSize) - { - return this.provider.ExecuteReader("Messaging_GetInbox", portalID, userID, pageNumber, pageSize); + public IDataReader GetUserInbox(int portalID, int userID, int pageNumber, int pageSize) + { + return this.provider.ExecuteReader("Messaging_GetInbox", portalID, userID, pageNumber, pageSize); } /// - public int GetInboxCount(int portalID, int userID) - { - return this.provider.ExecuteScalar("Messaging_GetInboxCount", portalID, userID); + public int GetInboxCount(int portalID, int userID) + { + return this.provider.ExecuteScalar("Messaging_GetInboxCount", portalID, userID); } /// - public long SaveMessage(Message objMessaging) - { - return this.provider.ExecuteScalar( - "Messaging_Save_Message", - objMessaging.PortalID, - objMessaging.FromUserID, - objMessaging.ToUserID, - objMessaging.ToRoleID, - (int)objMessaging.Status, - objMessaging.Subject, - objMessaging.Body, - objMessaging.MessageDate, - objMessaging.Conversation, - objMessaging.ReplyTo, - objMessaging.AllowReply, - objMessaging.SkipInbox); + public long SaveMessage(Message objMessaging) + { + return this.provider.ExecuteScalar( + "Messaging_Save_Message", + objMessaging.PortalID, + objMessaging.FromUserID, + objMessaging.ToUserID, + objMessaging.ToRoleID, + (int)objMessaging.Status, + objMessaging.Subject, + objMessaging.Body, + objMessaging.MessageDate, + objMessaging.Conversation, + objMessaging.ReplyTo, + objMessaging.AllowReply, + objMessaging.SkipInbox); } /// - public int GetNewMessageCount(int portalID, int userID) - { - return this.provider.ExecuteScalar("Messaging_GetNewMessageCount", portalID, userID); + public int GetNewMessageCount(int portalID, int userID) + { + return this.provider.ExecuteScalar("Messaging_GetNewMessageCount", portalID, userID); } /// - public IDataReader GetNextMessageForDispatch(Guid schedulerInstance) - { - return this.provider.ExecuteReader("Messaging_GetNextMessageForDispatch", schedulerInstance); + public IDataReader GetNextMessageForDispatch(Guid schedulerInstance) + { + return this.provider.ExecuteReader("Messaging_GetNextMessageForDispatch", schedulerInstance); } /// - public void MarkMessageAsDispatched(int messageID) - { - this.provider.ExecuteNonQuery("Messaging_MarkMessageAsDispatched", messageID); + public void MarkMessageAsDispatched(int messageID) + { + this.provider.ExecuteNonQuery("Messaging_MarkMessageAsDispatched", messageID); } /// - public void UpdateMessage(Message message) - { - this.provider.ExecuteNonQuery( - "Messaging_UpdateMessage", - message.MessageID, - message.ToUserID, - message.ToRoleID, - (int)message.Status, - message.Subject, - message.Body, - message.MessageDate, - message.ReplyTo, - message.AllowReply, - message.SkipInbox); - } - } -} + public void UpdateMessage(Message message) + { + this.provider.ExecuteNonQuery( + "Messaging_UpdateMessage", + message.MessageID, + message.ToUserID, + message.ToRoleID, + (int)message.Status, + message.Subject, + message.Body, + message.MessageDate, + message.ReplyTo, + message.AllowReply, + message.SkipInbox); + } + } +} diff --git a/DNN Platform/Library/Services/Mobile/MatchRule.cs b/DNN Platform/Library/Services/Mobile/MatchRule.cs index d4577ce811b..73384000097 100644 --- a/DNN Platform/Library/Services/Mobile/MatchRule.cs +++ b/DNN Platform/Library/Services/Mobile/MatchRule.cs @@ -1,71 +1,72 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Mobile -{ - using System; - using System.Xml.Serialization; +namespace DotNetNuke.Services.Mobile +{ + using System; + using System.Globalization; + using System.Xml.Serialization; using DotNetNuke.Entities.Modules; - [Serializable] - public class MatchRule : IMatchRule, IHydratable - { - private int id = -1; - - /// Gets or sets match rule's primary key. - [XmlAttribute] - public int Id - { - get - { - return this.id; - } - - set - { - this.id = value; - } - } - - /// Gets or sets capability's name. - [XmlAttribute] - public string Capability - { - get; - set; - } - - /// Gets or sets the value to match the capability from request. - [XmlAttribute] - public string Expression - { - get; - set; - } - - /// Gets or sets iHydratable.KeyID. - [XmlAttribute] - public int KeyID - { - get - { - return this.Id; - } - - set - { - this.Id = value; - } - } - - /// Fill the object with data from database. - /// the data reader. - public void Fill(System.Data.IDataReader dr) - { - this.Id = Convert.ToInt32(dr["Id"]); - this.Capability = dr["Capability"].ToString(); - this.Expression = dr["Expression"].ToString(); - } - } -} + [Serializable] + public class MatchRule : IMatchRule, IHydratable + { + private int id = -1; + + /// Gets or sets match rule's primary key. + [XmlAttribute] + public int Id + { + get + { + return this.id; + } + + set + { + this.id = value; + } + } + + /// Gets or sets capability's name. + [XmlAttribute] + public string Capability + { + get; + set; + } + + /// Gets or sets the value to match the capability from request. + [XmlAttribute] + public string Expression + { + get; + set; + } + + /// Gets or sets iHydratable.KeyID. + [XmlAttribute] + public int KeyID + { + get + { + return this.Id; + } + + set + { + this.Id = value; + } + } + + /// Fill the object with data from database. + /// the data reader. + public void Fill(System.Data.IDataReader dr) + { + this.Id = Convert.ToInt32(dr["Id"], CultureInfo.InvariantCulture); + this.Capability = dr["Capability"].ToString(); + this.Expression = dr["Expression"].ToString(); + } + } +} diff --git a/DNN Platform/Library/Services/Mobile/PreviewProfile.cs b/DNN Platform/Library/Services/Mobile/PreviewProfile.cs index d3de98cf34f..0bf1d240045 100644 --- a/DNN Platform/Library/Services/Mobile/PreviewProfile.cs +++ b/DNN Platform/Library/Services/Mobile/PreviewProfile.cs @@ -1,94 +1,95 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Mobile -{ - using System; - using System.Data; - using System.Xml.Serialization; +namespace DotNetNuke.Services.Mobile +{ + using System; + using System.Data; + using System.Globalization; + using System.Xml.Serialization; using DotNetNuke.Entities.Modules; using Newtonsoft.Json; - [Serializable] - public class PreviewProfile : IPreviewProfile, IHydratable - { - private int id = -1; - - /// Gets or sets primary key. - [XmlAttribute] - public int Id - { - get - { - return this.id; - } - - set - { - this.id = value; - } - } - - /// Gets or sets the profiles' effected portal. - [XmlAttribute] - public int PortalId - { - get; - set; - } - - /// Gets or sets profile's name. - [XmlAttribute] - public string Name - { - get; - set; - } - - /// Gets or sets the preview device's width. - [XmlAttribute] - public int Width { get; set; } - - /// Gets or sets the preview device's height. - [XmlAttribute] - public int Height { get; set; } - - /// Gets or sets the preview device's user agent. - [XmlAttribute] - public string UserAgent { get; set; } - - /// Gets or sets profile's sort order. - [XmlAttribute] - public int SortOrder { get; set; } - - /// Gets or sets iHydratable.KeyID. + [Serializable] + public class PreviewProfile : IPreviewProfile, IHydratable + { + private int id = -1; + + /// Gets or sets primary key. + [XmlAttribute] + public int Id + { + get + { + return this.id; + } + + set + { + this.id = value; + } + } + + /// Gets or sets the profiles' effected portal. + [XmlAttribute] + public int PortalId + { + get; + set; + } + + /// Gets or sets profile's name. + [XmlAttribute] + public string Name + { + get; + set; + } + + /// Gets or sets the preview device's width. + [XmlAttribute] + public int Width { get; set; } + + /// Gets or sets the preview device's height. + [XmlAttribute] + public int Height { get; set; } + + /// Gets or sets the preview device's user agent. + [XmlAttribute] + public string UserAgent { get; set; } + + /// Gets or sets profile's sort order. + [XmlAttribute] + public int SortOrder { get; set; } + + /// Gets or sets iHydratable.KeyID. [XmlIgnore] - [JsonIgnore] - public int KeyID - { - get - { - return this.Id; - } - - set - { - this.Id = value; - } - } - - /// Fill the object with data from database. - /// the data reader. - public void Fill(IDataReader dr) - { - this.Id = Convert.ToInt32(dr["Id"]); - this.PortalId = Convert.ToInt32(dr["PortalId"]); - this.Name = dr["Name"].ToString(); - this.Width = Convert.ToInt32(dr["Width"]); - this.Height = Convert.ToInt32(dr["Height"]); - this.UserAgent = dr["UserAgent"].ToString(); - this.SortOrder = Convert.ToInt32(dr["SortOrder"]); - } - } -} + [JsonIgnore] + public int KeyID + { + get + { + return this.Id; + } + + set + { + this.Id = value; + } + } + + /// Fill the object with data from database. + /// the data reader. + public void Fill(IDataReader dr) + { + this.Id = Convert.ToInt32(dr["Id"], CultureInfo.InvariantCulture); + this.PortalId = Convert.ToInt32(dr["PortalId"], CultureInfo.InvariantCulture); + this.Name = dr["Name"].ToString(); + this.Width = Convert.ToInt32(dr["Width"], CultureInfo.InvariantCulture); + this.Height = Convert.ToInt32(dr["Height"], CultureInfo.InvariantCulture); + this.UserAgent = dr["UserAgent"].ToString(); + this.SortOrder = Convert.ToInt32(dr["SortOrder"], CultureInfo.InvariantCulture); + } + } +} diff --git a/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs b/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs index 5a9d3972f73..27f2e0c6965 100644 --- a/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs +++ b/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Mobile { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Xml.Serialization; @@ -46,7 +47,7 @@ public void Save(IPreviewProfile profile) profile.Id = id; - var logContent = string.Format("{0} Mobile Preview Profile '{1}'", profile.Id == Null.NullInteger ? "Add" : "Update", profile.Name); + var logContent = $"{(profile.Id == Null.NullInteger ? "Add" : "Update")} Mobile Preview Profile '{profile.Name}'"; AddLog(logContent); ClearCache(profile.PortalId); @@ -68,8 +69,7 @@ public void Delete(int portalId, int id) }); DataProvider.Instance().DeletePreviewProfile(id); - var logContent = string.Format("Delete Mobile Preview Profile '{0}'", id); - AddLog(logContent); + AddLog(string.Format(CultureInfo.InvariantCulture, "Delete Mobile Preview Profile '{0}'", id)); ClearCache(portalId); } @@ -84,7 +84,7 @@ public IList GetProfilesByPortal(int portalId) } /// get a specific preview profile by id. - /// the profile belong's portal. + /// the ID of the portal to which the profile belongs. /// profile's id. /// profile object. public IPreviewProfile GetProfileById(int portalId, int id) @@ -94,7 +94,7 @@ public IPreviewProfile GetProfileById(int portalId, int id) private static void ClearCache(int portalId) { - DataCache.RemoveCache(string.Format(DataCache.PreviewProfilesCacheKey, portalId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.PreviewProfilesCacheKey, portalId)); } private static void AddLog(string logContent) @@ -104,7 +104,7 @@ private static void AddLog(string logContent) private IList GetProfilesByPortal(int portalId, bool addDefault) { - string cacheKey = string.Format(DataCache.PreviewProfilesCacheKey, portalId); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PreviewProfilesCacheKey, portalId); var cacheArg = new CacheItemArgs(cacheKey, DataCache.PreviewProfilesCacheTimeOut, DataCache.PreviewProfilesCachePriority, portalId, addDefault); return CBO.GetCachedObject>(cacheArg, this.GetProfilesByPortalIdCallBack); } @@ -125,11 +125,10 @@ private IList GetProfilesByPortalIdCallBack(CacheItemArgs cache private List CreateDefaultDevices(int portalId) { - string defaultPreviewProfiles; var settings = PortalController.Instance.GetPortalSettings(portalId); - List profiles = new List(); + List profiles = []; - if (!settings.TryGetValue("DefPreviewProfiles_Created", out defaultPreviewProfiles) || defaultPreviewProfiles != DotNetNukeContext.Current.Application.Name) + if (!settings.TryGetValue("DefPreviewProfiles_Created", out var defaultPreviewProfiles) || defaultPreviewProfiles != DotNetNukeContext.Current.Application.Name) { try { @@ -143,15 +142,11 @@ private List CreateDefaultDevices(int portalId) var serializer = new XmlSerializer(typeof(List)); profiles = (List)serializer.Deserialize(File.OpenRead(dataPath)); - if (profiles != null) + profiles?.ForEach(p => { - profiles.ForEach(p => - { - p.PortalId = portalId; - - this.Save(p); - }); - } + p.PortalId = portalId; + this.Save(p); + }); } } diff --git a/DNN Platform/Library/Services/Mobile/Redirection.cs b/DNN Platform/Library/Services/Mobile/Redirection.cs index 1f51532f822..98e498659d6 100644 --- a/DNN Platform/Library/Services/Mobile/Redirection.cs +++ b/DNN Platform/Library/Services/Mobile/Redirection.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Mobile { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Xml.Serialization; @@ -135,16 +136,16 @@ public int KeyID /// the data reader. public void Fill(System.Data.IDataReader dr) { - this.Id = Convert.ToInt32(dr["Id"]); - this.PortalId = Convert.ToInt32(dr["PortalId"]); + this.Id = Convert.ToInt32(dr["Id"], CultureInfo.InvariantCulture); + this.PortalId = Convert.ToInt32(dr["PortalId"], CultureInfo.InvariantCulture); this.Name = dr["Name"].ToString(); - this.Type = (RedirectionType)Convert.ToInt32(dr["Type"]); - this.SourceTabId = Convert.ToInt32(dr["SourceTabId"]); - this.IncludeChildTabs = Convert.ToBoolean(dr["IncludeChildTabs"]); - this.SortOrder = Convert.ToInt32(dr["SortOrder"]); - this.TargetType = (TargetType)Convert.ToInt32(dr["TargetType"]); + this.Type = (RedirectionType)Convert.ToInt32(dr["Type"], CultureInfo.InvariantCulture); + this.SourceTabId = Convert.ToInt32(dr["SourceTabId"], CultureInfo.InvariantCulture); + this.IncludeChildTabs = Convert.ToBoolean(dr["IncludeChildTabs"], CultureInfo.InvariantCulture); + this.SortOrder = Convert.ToInt32(dr["SortOrder"], CultureInfo.InvariantCulture); + this.TargetType = (TargetType)Convert.ToInt32(dr["TargetType"], CultureInfo.InvariantCulture); this.TargetValue = dr["TargetValue"]; - this.Enabled = Convert.ToBoolean(dr["Enabled"]); + this.Enabled = Convert.ToBoolean(dr["Enabled"], CultureInfo.InvariantCulture); } } } diff --git a/DNN Platform/Library/Services/Mobile/RedirectionController.cs b/DNN Platform/Library/Services/Mobile/RedirectionController.cs index fccea28baab..1164afef858 100644 --- a/DNN Platform/Library/Services/Mobile/RedirectionController.cs +++ b/DNN Platform/Library/Services/Mobile/RedirectionController.cs @@ -56,7 +56,7 @@ public RedirectionController(IPortalController portalController, IEventLogger ev this.eventLogger = eventLogger ?? Globals.DependencyProvider.GetRequiredService(); } - private static string AllRedirectionsCacheKey => string.Format(DataCache.RedirectionsCacheKey, "All"); + private static string AllRedirectionsCacheKey => string.Format(CultureInfo.InvariantCulture, DataCache.RedirectionsCacheKey, "All"); /// /// Is Redirection Allowed for the session. Method analyzes the query string for special parameters to enable / disable redirects. @@ -170,7 +170,7 @@ public string GetRedirectUrl(string userAgent, int portalId, int currentTabId) } // try to get content from cache - var cacheKey = string.Format(RedirectionUrlCacheKey, userAgent, portalId, currentTabId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, RedirectionUrlCacheKey, userAgent, portalId, currentTabId); redirectUrl = GetUrlFromCache(cacheKey); if (!string.IsNullOrEmpty(redirectUrl)) { @@ -273,7 +273,7 @@ public string GetFullSiteUrl(int portalId, int currentTabId) } // try to get content from cache - var cacheKey = string.Format(FullSiteUrlCacheKey, portalId, currentTabId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, FullSiteUrlCacheKey, portalId, currentTabId); fullSiteUrl = GetUrlFromCache(cacheKey); if (!string.IsNullOrEmpty(fullSiteUrl)) { @@ -288,7 +288,7 @@ public string GetFullSiteUrl(int portalId, int currentTabId) if (redirection.TargetType == TargetType.Tab) { // page within same site - int targetTabId = int.Parse(redirection.TargetValue.ToString()); + int targetTabId = int.Parse(redirection.TargetValue.ToString(), CultureInfo.InvariantCulture); if (targetTabId == currentTabId) { // target tab is same as current tab @@ -298,7 +298,7 @@ public string GetFullSiteUrl(int portalId, int currentTabId) else if (redirection.TargetType == TargetType.Portal) { // home page of another portal - int targetPortalId = int.Parse(redirection.TargetValue.ToString()); + int targetPortalId = int.Parse(redirection.TargetValue.ToString(), CultureInfo.InvariantCulture); if (targetPortalId == portalId) { // target portal is same as current portal @@ -335,7 +335,7 @@ public string GetFullSiteUrl(int portalId, int currentTabId) // append special query string if (!string.IsNullOrEmpty(fullSiteUrl)) { - fullSiteUrl += string.Format("{0}{1}=1", fullSiteUrl.Contains("?") ? "&" : "?", DisableMobileRedirectQueryStringName); + fullSiteUrl += $"{(fullSiteUrl.Contains("?") ? "&" : "?")}{DisableMobileRedirectQueryStringName}=1"; } // update cache content @@ -377,14 +377,14 @@ public string GetMobileSiteUrl(int portalId, int currentTabId) } // try to get content from cache - var cacheKey = string.Format(MobileSiteUrlCacheKey, portalId, currentTabId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, MobileSiteUrlCacheKey, portalId, currentTabId); mobileSiteUrl = GetUrlFromCache(cacheKey); if (!string.IsNullOrEmpty(mobileSiteUrl)) { return mobileSiteUrl; } - // let's try to find if this tab has any specifc rules + // let's try to find if this tab has any specific rules foreach (var redirection in redirections) { if (redirection.Enabled) @@ -410,7 +410,7 @@ public string GetMobileSiteUrl(int portalId, int currentTabId) // append special query string if (!string.IsNullOrEmpty(mobileSiteUrl)) { - mobileSiteUrl += string.Format("{0}{1}=0", mobileSiteUrl.Contains("?") ? "&" : "?", DisableMobileRedirectQueryStringName); + mobileSiteUrl += $"{(mobileSiteUrl.Contains("?") ? "&" : "?")}{DisableMobileRedirectQueryStringName}=0"; } // update cache content @@ -470,7 +470,7 @@ public void PurgeInvalidRedirections(int portalId) // remove rules for deleted target tabs redirects = this.GetRedirectionsByPortal(portalId); // fresh get of rules in case some were deleted above - foreach (var r in redirects.Where(r => r.TargetType == TargetType.Tab && allTabs.All(t => t.Key != int.Parse(r.TargetValue.ToString())))) + foreach (var r in redirects.Where(r => r.TargetType == TargetType.Tab && allTabs.All(t => t.Key != int.Parse(r.TargetValue.ToString(), CultureInfo.InvariantCulture)))) { this.Delete(portalId, r.Id); } @@ -483,7 +483,7 @@ public void PurgeInvalidRedirections(int portalId) bool found = false; foreach (PortalInfo portal in allPortals) { - if (portal.PortalID == int.Parse(r.TargetValue.ToString())) + if (portal.PortalID == int.Parse(r.TargetValue.ToString(), CultureInfo.InvariantCulture)) { found = true; break; @@ -506,15 +506,17 @@ public void Delete(int portalId, int id) if (delRedirection != null) { // update the list order - this.GetRedirectionsByPortal(portalId).Where(p => p.SortOrder > delRedirection.SortOrder).ToList().ForEach(p => - { - p.SortOrder--; - this.Save(p); - }); + this.GetRedirectionsByPortal(portalId) + .Where(p => p.SortOrder > delRedirection.SortOrder) + .ToList() + .ForEach(p => + { + p.SortOrder--; + this.Save(p); + }); DataProvider.Instance().DeleteRedirection(id); - var logContent = string.Format("Id '{0}' Deleted", id); - this.AddLog(logContent); + this.AddLog(string.Format(CultureInfo.InvariantCulture, "Id '{0}' Deleted", id)); ClearCache(portalId); } @@ -528,7 +530,7 @@ public void DeleteRule(int portalId, int redirectionId, int ruleId) { DataProvider.Instance().DeleteRedirectionRule(ruleId); - var logContent = string.Format("Id '{0}' Removed from Redirection Id '{1}'", ruleId, redirectionId); + var logContent = $"Id '{ruleId}' Removed from Redirection Id '{redirectionId}'"; this.AddLog(logContent); ClearCache(portalId); @@ -547,7 +549,7 @@ public IList GetAllRedirections() /// List of redirection. public IList GetRedirectionsByPortal(int portalId) { - string cacheKey = string.Format(DataCache.RedirectionsCacheKey, portalId); + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.RedirectionsCacheKey, portalId); var cacheArg = new CacheItemArgs(cacheKey, DataCache.RedirectionsCacheTimeOut, DataCache.RedirectionsCachePriority, portalId); return CBO.GetCachedObject>(cacheArg, GetRedirectionsByPortalCallBack); } @@ -578,13 +580,13 @@ public string GetRedirectUrlFromRule(IRedirection redirection, int portalId, int else if (redirection.TargetType == TargetType.Tab) { // page within same site - int targetTabId = int.Parse(redirection.TargetValue.ToString()); + int targetTabId = int.Parse(redirection.TargetValue.ToString(), CultureInfo.InvariantCulture); // ensure it's not redirecting to itself if (targetTabId != currentTabId) { var tab = TabController.Instance.GetTab(targetTabId, portalId, false); - if (tab != null && !tab.IsDeleted) + if (tab is { IsDeleted: false, }) { redirectUrl = TestableGlobals.Instance.NavigateURL(targetTabId); } @@ -593,7 +595,7 @@ public string GetRedirectUrlFromRule(IRedirection redirection, int portalId, int else if (redirection.TargetType == TargetType.Portal) { // home page of another portal - int targetPortalId = int.Parse(redirection.TargetValue.ToString()); + int targetPortalId = int.Parse(redirection.TargetValue.ToString(), CultureInfo.InvariantCulture); // ensure it's not redirecting to itself if (targetPortalId != portalId) @@ -632,7 +634,7 @@ private static IList GetRedirectionsByPortalCallBack(CacheItemArgs private static void ClearCache(int portalId) { - DataCache.RemoveCache(string.Format(DataCache.RedirectionsCacheKey, portalId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.RedirectionsCacheKey, portalId)); DataCache.RemoveCache(AllRedirectionsCacheKey); DataCache.RemoveCache(UrlsCacheKey); } diff --git a/DNN Platform/Library/Services/ModuleCache/FileProvider.cs b/DNN Platform/Library/Services/ModuleCache/FileProvider.cs index 741c0b28b7b..e0847489657 100644 --- a/DNN Platform/Library/Services/ModuleCache/FileProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/FileProvider.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.ModuleCache { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Security.Cryptography; @@ -79,14 +80,14 @@ public override void PurgeExpiredItems(int portalId) string cacheFolder = GetCacheFolder(portalId); if (Directory.Exists(cacheFolder) && IsPathInApplication(cacheFolder)) { - foreach (string file in Directory.GetFiles(cacheFolder, string.Format("*{0}", AttribFileExtension))) + foreach (string file in Directory.GetFiles(cacheFolder, $"*{AttribFileExtension}")) { if (IsFileExpired(file)) { string fileToDelete = file.Replace(AttribFileExtension, DataFileExtension); if (!FileSystemUtils.DeleteFileWithWait(fileToDelete, 100, 200)) { - filesNotDeleted.Append(string.Format("{0};", fileToDelete)); + filesNotDeleted.Append($"{fileToDelete};"); } else { @@ -98,7 +99,7 @@ public override void PurgeExpiredItems(int portalId) if (filesNotDeleted.Length > 0) { - throw new IOException(string.Format("Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); + throw new IOException(string.Format(CultureInfo.InvariantCulture, "Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); } } catch (Exception ex) @@ -108,6 +109,7 @@ public override void PurgeExpiredItems(int portalId) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override void SetModule(int tabModuleId, string cacheKey, TimeSpan duration, byte[] output) { try @@ -176,7 +178,7 @@ private static string GetAttribFileName(int tabModuleId, string cacheKey) private static int GetCachedItemCount(int tabModuleId) { - return Directory.GetFiles(GetCacheFolder(), string.Format("*{0}", DataFileExtension)).Length; + return Directory.GetFiles(GetCacheFolder(), $"*{DataFileExtension}").Length; } private static string GetCachedOutputFileName(int tabModuleId, string cacheKey) diff --git a/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs b/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs index fd7aef6510b..3f12895ef61 100644 --- a/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.ModuleCache using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.Text; using System.Web.Caching; @@ -24,11 +25,11 @@ public override string GenerateCacheKey(int tabModuleId, SortedDictionary kvp in varyBy) { - cacheKey.Append(string.Concat(kvp.Key.ToLowerInvariant(), "=", kvp.Value, "|")); + cacheKey.Append($"{kvp.Key.ToLowerInvariant()}={kvp.Value}|"); } } - return string.Concat(CachePrefix, "|", tabModuleId.ToString(), "|", cacheKey.ToString()); + return $"{CachePrefix}|{tabModuleId.ToString(CultureInfo.InvariantCulture)}|{cacheKey}"; } /// @@ -52,7 +53,7 @@ public override void PurgeCache(int portalId) /// public override void Remove(int tabModuleId) { - DataCache.ClearCache(string.Concat(CachePrefix, "|", tabModuleId.ToString())); + DataCache.ClearCache($"{CachePrefix}|{tabModuleId.ToString(CultureInfo.InvariantCulture)}"); } /// @@ -74,7 +75,7 @@ private static List GetCacheKeys(int tabModuleId) IDictionaryEnumerator cacheEnum = CachingProvider.Instance().GetEnumerator(); while (cacheEnum.MoveNext()) { - if (cacheEnum.Key.ToString().StartsWith(string.Concat(CachePrefix, "|", tabModuleId.ToString(), "|"))) + if (cacheEnum.Key.ToString().StartsWith($"{CachePrefix}|{tabModuleId.ToString(CultureInfo.InvariantCulture)}|", StringComparison.Ordinal)) { keys.Add(cacheEnum.Key.ToString()); } diff --git a/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs b/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs index fcb9a190580..321231b9580 100644 --- a/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.ModuleCache using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Text; using DotNetNuke.ComponentModel; @@ -55,7 +56,7 @@ protected string ByteArrayToString(byte[] arrInput) var sOutput = new StringBuilder(arrInput.Length); for (i = 0; i <= arrInput.Length - 1; i++) { - sOutput.Append(arrInput[i].ToString("X2")); + sOutput.Append(arrInput[i].ToString("X2", CultureInfo.InvariantCulture)); } return sOutput.ToString(); diff --git a/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs b/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs index 4ff2a2d88ef..07855189003 100644 --- a/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs +++ b/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs @@ -34,7 +34,7 @@ public override void DoWork() foreach (PortalInfo portal in portals) { kvp.Value.PurgeExpiredItems(portal.PortalID); - this.ScheduleHistoryItem.AddLogNote(string.Format("Purged Module cache for {0}. ", kvp.Key)); + this.ScheduleHistoryItem.AddLogNote($"Purged Module cache for {kvp.Key}. "); } } catch (NotSupportedException exc) @@ -50,7 +50,7 @@ public override void DoWork() { this.ScheduleHistoryItem.Succeeded = false; // REQUIRED - this.ScheduleHistoryItem.AddLogNote(string.Format("Purging Module cache task failed: {0}.", exc.ToString())); + this.ScheduleHistoryItem.AddLogNote($"Purging Module cache task failed: {exc}."); // notification that we have errored this.Errored(ref exc); // REQUIRED diff --git a/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs index 49bc07db3fb..cf9cc390fd1 100644 --- a/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs @@ -4,10 +4,12 @@ namespace DotNetNuke.Services.OutputCache { using System; + using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; // helper class to capture the response into a file + [SuppressMessage("Microsoft.Design", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Breaking change")] public abstract class OutputCacheResponseFilter : Stream { private Stream captureStream; diff --git a/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs b/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs index c6ca73b1754..4798828003c 100644 --- a/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Services.OutputCache using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; @@ -80,7 +81,7 @@ protected string ByteArrayToString(byte[] arrInput) var sOutput = new StringBuilder(arrInput.Length); for (i = 0; i <= arrInput.Length - 1; i++) { - sOutput.Append(arrInput[i].ToString("X2")); + sOutput.Append(arrInput[i].ToString("X2", CultureInfo.InvariantCulture)); } return sOutput.ToString(); @@ -89,11 +90,9 @@ protected string ByteArrayToString(byte[] arrInput) protected string GenerateCacheKeyHash(int tabId, string cacheKey) { byte[] hash = Encoding.ASCII.GetBytes(cacheKey); - using (var sha256 = new SHA256CryptoServiceProvider()) - { - hash = sha256.ComputeHash(hash); - return string.Concat(tabId.ToString(), "_", this.ByteArrayToString(hash)); - } + using var sha256 = new SHA256CryptoServiceProvider(); + hash = sha256.ComputeHash(hash); + return string.Concat(tabId.ToString(CultureInfo.InvariantCulture), "_", this.ByteArrayToString(hash)); } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Breaking change")] diff --git a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs index 0ae0b642b03..fd6510d8902 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs @@ -2,122 +2,120 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.OutputCache.Providers -{ - using System; - using System.Data; - using System.IO; - using System.Text; - using System.Web; +namespace DotNetNuke.Services.OutputCache.Providers +{ + using System; + using System.Data; + using System.Globalization; + using System.IO; + using System.Text; + using System.Web; - using DotNetNuke.Data; + using DotNetNuke.Data; - /// DatabaseProvider implements the OutputCachingProvider for database storage. - public class DatabaseProvider : OutputCachingProvider + /// DatabaseProvider implements the OutputCachingProvider for database storage. + public class DatabaseProvider : OutputCachingProvider { /// - public override int GetItemCount(int tabId) - { - return DataProvider.Instance().GetOutputCacheItemCount(tabId); + public override int GetItemCount(int tabId) + { + return DataProvider.Instance().GetOutputCacheItemCount(tabId); } /// - public override byte[] GetOutput(int tabId, string cacheKey) - { - IDataReader dr = null; - try - { - dr = DataProvider.Instance().GetOutputCacheItem(cacheKey); - if (dr == null) - { - return null; - } - else - { - if (!dr.Read()) - { - return null; - } - - return Encoding.UTF8.GetBytes(dr["Data"].ToString()); - } - } - finally - { - if (dr != null) - { - dr.Close(); - } - } + public override byte[] GetOutput(int tabId, string cacheKey) + { + IDataReader dr = null; + try + { + dr = DataProvider.Instance().GetOutputCacheItem(cacheKey); + if (dr == null) + { + return null; + } + else + { + if (!dr.Read()) + { + return null; + } + + return Encoding.UTF8.GetBytes(dr["Data"].ToString()); + } + } + finally + { + if (dr != null) + { + dr.Close(); + } + } } /// - public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVaryByCount, Stream responseFilter, string cacheKey, TimeSpan cacheDuration) - { - return new DatabaseResponseFilter(tabId, maxVaryByCount, responseFilter, cacheKey, cacheDuration); + public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVaryByCount, Stream responseFilter, string cacheKey, TimeSpan cacheDuration) + { + return new DatabaseResponseFilter(tabId, maxVaryByCount, responseFilter, cacheKey, cacheDuration); } /// - public override void PurgeCache(int portalId) - { - DataProvider.Instance().PurgeOutputCache(); + public override void PurgeCache(int portalId) + { + DataProvider.Instance().PurgeOutputCache(); } /// - public override void PurgeExpiredItems(int portalId) - { - DataProvider.Instance().PurgeExpiredOutputCacheItems(); + public override void PurgeExpiredItems(int portalId) + { + DataProvider.Instance().PurgeExpiredOutputCacheItems(); } /// - public override void Remove(int tabId) - { - DataProvider.Instance().RemoveOutputCacheItem(tabId); + public override void Remove(int tabId) + { + DataProvider.Instance().RemoveOutputCacheItem(tabId); } /// - public override void SetOutput(int tabId, string cacheKey, TimeSpan duration, byte[] output) - { - string data = Encoding.UTF8.GetString(output); - DataProvider.Instance().AddOutputCacheItem(tabId, cacheKey, data, DateTime.UtcNow.Add(duration)); + public override void SetOutput(int tabId, string cacheKey, TimeSpan duration, byte[] output) + { + string data = Encoding.UTF8.GetString(output); + DataProvider.Instance().AddOutputCacheItem(tabId, cacheKey, data, DateTime.UtcNow.Add(duration)); } /// - public override bool StreamOutput(int tabId, string cacheKey, HttpContext context) - { - IDataReader dr = null; - try - { - dr = DataProvider.Instance().GetOutputCacheItem(cacheKey); - if (dr == null) - { - return false; - } - else - { - if (!dr.Read()) - { - return false; - } - - var expireTime = Convert.ToDateTime(dr["Expiration"]); - if (expireTime < DateTime.UtcNow) - { - DataProvider.Instance().RemoveOutputCacheItem(tabId); - return false; - } - - context.Response.BinaryWrite(Encoding.Default.GetBytes(dr["Data"].ToString())); - return true; - } - } - finally - { - if (dr != null) - { - dr.Close(); - } - } - } - } -} + public override bool StreamOutput(int tabId, string cacheKey, HttpContext context) + { + IDataReader dr = null; + try + { + dr = DataProvider.Instance().GetOutputCacheItem(cacheKey); + if (dr == null) + { + return false; + } + else + { + if (!dr.Read()) + { + return false; + } + + var expireTime = Convert.ToDateTime(dr["Expiration"], CultureInfo.InvariantCulture); + if (expireTime < DateTime.UtcNow) + { + DataProvider.Instance().RemoveOutputCacheItem(tabId); + return false; + } + + context.Response.BinaryWrite(Encoding.Default.GetBytes(dr["Data"].ToString())); + return true; + } + } + finally + { + dr?.Close(); + } + } + } +} diff --git a/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs index 2358d6cdb58..5c68c4dda1a 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs @@ -196,7 +196,7 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex string captureFile = GetCachedOutputFileName(tabId, cacheKey); StreamReader oRead = File.OpenText(attribFile); - DateTime expires = Convert.ToDateTime(oRead.ReadLine()); + DateTime expires = Convert.ToDateTime(oRead.ReadLine(), CultureInfo.InvariantCulture); oRead.Close(); if (expires < DateTime.UtcNow) { @@ -282,7 +282,7 @@ private static bool IsFileExpired(string file) try { oRead = File.OpenText(file); - DateTime expires = Convert.ToDateTime(oRead.ReadLine()); + var expires = Convert.ToDateTime(oRead.ReadLine(), CultureInfo.InvariantCulture); if (expires < DateTime.UtcNow) { return true; @@ -294,10 +294,7 @@ private static bool IsFileExpired(string file) } finally { - if (oRead != null) - { - oRead.Close(); - } + oRead?.Close(); } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs index f3dd30117c2..348da2053bf 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Services.OutputCache.Providers using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -38,14 +39,6 @@ internal static System.Web.Caching.Cache Cache } } - internal static string CachePrefix - { - get - { - return cachePrefix; - } - } - /// public override string GenerateCacheKey(int tabId, System.Collections.Specialized.StringCollection includeVaryByKeys, System.Collections.Specialized.StringCollection excludeVaryByKeys, SortedDictionary varyBy) { @@ -119,7 +112,7 @@ internal static List GetCacheKeys() IDictionaryEnumerator cacheEnum = Cache.GetEnumerator(); while (cacheEnum.MoveNext()) { - if (cacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix))) + if (cacheEnum.Key.ToString().StartsWith(cachePrefix, StringComparison.Ordinal)) { keys.Add(cacheEnum.Key.ToString()); } @@ -134,7 +127,7 @@ internal static List GetCacheKeys(int tabId) IDictionaryEnumerator cacheEnum = Cache.GetEnumerator(); while (cacheEnum.MoveNext()) { - if (cacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix, tabId.ToString(), "_"))) + if (cacheEnum.Key.ToString().StartsWith($"{cachePrefix}{tabId.ToString(CultureInfo.InvariantCulture)}_", StringComparison.Ordinal)) { keys.Add(cacheEnum.Key.ToString()); } diff --git a/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs b/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs index 763431bf7ff..8e3e77befc0 100644 --- a/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs +++ b/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs @@ -34,7 +34,7 @@ public override void DoWork() foreach (PortalInfo portal in portals) { kvp.Value.PurgeExpiredItems(portal.PortalID); - this.ScheduleHistoryItem.AddLogNote(string.Format("Purged output cache for {0}. ", kvp.Key)); + this.ScheduleHistoryItem.AddLogNote($"Purged output cache for {kvp.Key}. "); } } catch (NotSupportedException exc) @@ -50,7 +50,7 @@ public override void DoWork() { this.ScheduleHistoryItem.Succeeded = false; // REQUIRED - this.ScheduleHistoryItem.AddLogNote(string.Format("Purging output cache task failed: {0}.", exc.ToString())); // OPTIONAL + this.ScheduleHistoryItem.AddLogNote($"Purging output cache task failed: {exc}."); // OPTIONAL // notification that we have errored this.Errored(ref exc); diff --git a/DNN Platform/Library/Services/Personalization/Personalization.cs b/DNN Platform/Library/Services/Personalization/Personalization.cs index c8b59fb52f1..532d8c37f39 100644 --- a/DNN Platform/Library/Services/Personalization/Personalization.cs +++ b/DNN Platform/Library/Services/Personalization/Personalization.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Personalization { using System; + using System.Globalization; using System.Web; using DotNetNuke.Common; @@ -209,7 +210,7 @@ public static Mode GetUserMode() if (HttpContextSource.Current?.Request.IsAuthenticated == true) { mode = PortalSettings.Current.DefaultControlPanelMode; - string setting = Convert.ToString(Personalization.GetProfile("Usability", "UserMode" + PortalController.Instance.GetCurrentSettings().PortalId)); + string setting = Convert.ToString(Personalization.GetProfile("Usability", "UserMode" + PortalController.Instance.GetCurrentSettings().PortalId), CultureInfo.InvariantCulture); switch (setting.ToUpperInvariant()) { case "VIEW": diff --git a/DNN Platform/Library/Services/Personalization/PersonalizationController.cs b/DNN Platform/Library/Services/Personalization/PersonalizationController.cs index 1e85aff1a0a..adc2d91af2c 100644 --- a/DNN Platform/Library/Services/Personalization/PersonalizationController.cs +++ b/DNN Platform/Library/Services/Personalization/PersonalizationController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Personalization using System; using System.Collections; using System.Data; + using System.Globalization; using System.Web; using DotNetNuke.Abstractions.Application; @@ -50,11 +51,11 @@ public void LoadProfile(HttpContextBase httpContext, int userId, int portalId) // override allows for manipulation of PersonalizationInfo outside of HTTPContext public PersonalizationInfo LoadProfile(int userId, int portalId) { - var personalization = new PersonalizationInfo { UserId = userId, PortalId = portalId, IsModified = false }; + var personalization = new PersonalizationInfo { UserId = userId, PortalId = portalId, IsModified = false, }; string profileData = Null.NullString; if (userId > Null.NullInteger) { - var cacheKey = string.Format(DataCache.UserPersonalizationCacheKey, portalId, userId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.UserPersonalizationCacheKey, portalId, userId); profileData = CBO.GetCachedObject( new CacheItemArgs( cacheKey, @@ -104,7 +105,7 @@ public void SaveProfile(HttpContext httpContext, int userId, int portalId) // override allows for manipulation of PersonalizationInfo outside of HTTPContext public void SaveProfile(PersonalizationInfo personalization, int userId, int portalId) { - if (personalization != null && personalization.IsModified) + if (personalization is { IsModified: true, }) { var profileData = XmlUtils.SerializeDictionary(personalization.Profile, "profile"); if (userId > Null.NullInteger) @@ -112,7 +113,7 @@ public void SaveProfile(PersonalizationInfo personalization, int userId, int por DataProvider.Instance().UpdateProfile(userId, portalId, profileData); // remove then re-add the updated one - var cacheKey = string.Format(DataCache.UserPersonalizationCacheKey, portalId, userId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.UserPersonalizationCacheKey, portalId, userId); DataCache.RemoveCache(cacheKey); CBO.GetCachedObject( new CacheItemArgs( diff --git a/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs b/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs index d9c847894e4..b7d3291402d 100644 --- a/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs +++ b/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Registration { using System; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Linq; using DotNetNuke.Common.Lists; @@ -15,6 +16,7 @@ namespace DotNetNuke.Services.Registration public class RegistrationProfileController : ServiceLocator, IRegistrationProfileController { /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public IEnumerable Search(int portalId, string searchTerm) { var controller = new ListController(); diff --git a/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs b/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs index d59ff3f0e6d..c3df5f60015 100644 --- a/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs +++ b/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Scheduling { using System; + using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Web.Compilation; @@ -15,42 +16,22 @@ public class ProcessGroup { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ProcessGroup)); - private static int numberOfProcessesInQueue; private static int numberOfProcesses; - private static int processesCompleted; - private static int ticksElapsed; // '''''''''''''''''''''''''''''''''''''''''''''''''' // This class represents a process group for // our threads to run in. // '''''''''''''''''''''''''''''''''''''''''''''''''' + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public delegate void CompletedEventHandler(); public event CompletedEventHandler Completed; - private static int GetTicksElapsed - { - get - { - return ticksElapsed; - } - } + private static int GetTicksElapsed { get; set; } - private static int GetProcessesCompleted - { - get - { - return processesCompleted; - } - } + private static int GetProcessesCompleted { get; set; } - private static int GetProcessesInQueue - { - get - { - return numberOfProcessesInQueue; - } - } + private static int GetProcessesInQueue { get; set; } public void Run(ScheduleHistoryItem objScheduleHistoryItem) { @@ -59,7 +40,7 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) try { // This is called from RunPooledThread() - ticksElapsed = Environment.TickCount - ticksElapsed; + GetTicksElapsed = Environment.TickCount - GetTicksElapsed; serviceScope = Globals.DependencyProvider.CreateScope(); process = GetSchedulerClient(serviceScope.ServiceProvider, objScheduleHistoryItem.TypeFullName, objScheduleHistoryItem); process.ScheduleHistoryItem = objScheduleHistoryItem; @@ -107,11 +88,11 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) // I don't think this is necessary with the // other events. I'll leave it for now and // will probably take it out later. - if (processesCompleted == numberOfProcesses) + if (GetProcessesCompleted == numberOfProcesses) { - if (processesCompleted == numberOfProcesses) + if (GetProcessesCompleted == numberOfProcesses) { - ticksElapsed = Environment.TickCount - ticksElapsed; + GetTicksElapsed = Environment.TickCount - GetTicksElapsed; if (this.Completed != null) { this.Completed(); @@ -148,8 +129,8 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) // Track how many processes have completed for // this instanciation of the ProcessGroup - numberOfProcessesInQueue -= 1; - processesCompleted += 1; + GetProcessesInQueue -= 1; + GetProcessesCompleted += 1; } } @@ -157,7 +138,7 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) // callback to RunPooledThread which calls Run() public void AddQueueUserWorkItem(ScheduleItem s) { - numberOfProcessesInQueue += 1; + GetProcessesInQueue += 1; numberOfProcesses += 1; var obj = new ScheduleHistoryItem(s); try diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs b/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs index ade2978480d..543517df82f 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Scheduling using System; using System.Collections; using System.Data; + using System.Globalization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities; @@ -134,20 +135,18 @@ public virtual void Fill(IDataReader dr) /// A value indicating whether the item has object dependencies. public bool HasObjectDependencies(string strObjectDependencies) { - if (strObjectDependencies.IndexOf(",") > -1) + if (strObjectDependencies.IndexOf(",", StringComparison.Ordinal) > -1) { - string[] a; - a = strObjectDependencies.ToLowerInvariant().Split(','); - int i; - for (i = 0; i <= a.Length - 1; i++) + var dependencies = strObjectDependencies.Split(','); + for (var i = 0; i <= dependencies.Length - 1; i++) { - if (this.ObjectDependencies.IndexOf(a[i].Trim(), StringComparison.InvariantCultureIgnoreCase) > -1) + if (this.ObjectDependencies.Contains(dependencies[i].Trim(), StringComparison.OrdinalIgnoreCase)) { return true; } } } - else if (this.ObjectDependencies.IndexOf(strObjectDependencies, StringComparison.InvariantCultureIgnoreCase) > -1) + else if (this.ObjectDependencies.Contains(strObjectDependencies, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -175,7 +174,7 @@ public virtual string GetSetting(string key) if (this.scheduleItemSettings != null && this.scheduleItemSettings.ContainsKey(key)) { - return Convert.ToString(this.scheduleItemSettings[key]); + return Convert.ToString(this.scheduleItemSettings[key], CultureInfo.InvariantCulture); } else { diff --git a/DNN Platform/Library/Services/Scheduling/Scheduler.cs b/DNN Platform/Library/Services/Scheduling/Scheduler.cs index dca149ff296..fda037bb3fe 100644 --- a/DNN Platform/Library/Services/Scheduling/Scheduler.cs +++ b/DNN Platform/Library/Services/Scheduling/Scheduler.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Scheduling using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Security.Principal; using System.Text; @@ -27,9 +28,11 @@ internal static class CoreScheduler // If KeepRunning gets switched to false, // the scheduler stops running. [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static bool KeepThreadAlive = true; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static bool KeepRunning = true; private static readonly SharedList ScheduleQueue; @@ -278,7 +281,7 @@ public static Collection GetScheduleInProgress() { foreach (ScheduleHistoryItem item in ScheduleInProgress) { - c.Add(item, item.ScheduleID.ToString(), null, null); + c.Add(item, item.ScheduleID.ToString(CultureInfo.InvariantCulture), null, null); } } } @@ -333,7 +336,7 @@ public static Collection GetScheduleQueue() { foreach (ScheduleItem item in ScheduleQueue) { - c.Add(item, item.ScheduleID.ToString(), null, null); + c.Add(item, item.ScheduleID.ToString(CultureInfo.InvariantCulture), null, null); } } @@ -930,15 +933,15 @@ public static void WorkCompleted(SchedulerClient schedulerClient) { var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_COMPLETED" }; log.AddProperty("TYPE", schedulerClient.GetType().FullName); - log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); - log.AddProperty("NEXT START", Convert.ToString(scheduleHistoryItem.NextStart)); + log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString(CultureInfo.InvariantCulture)); + log.AddProperty("NEXT START", Convert.ToString(scheduleHistoryItem.NextStart, CultureInfo.InvariantCulture)); log.AddProperty("SOURCE", schedulerClient.ScheduleHistoryItem.ScheduleSource.ToString()); - log.AddProperty("ACTIVE THREADS", activeThreadCount.ToString()); - log.AddProperty("FREE THREADS", FreeThreads.ToString()); - log.AddProperty("READER TIMEOUTS", readerTimeouts.ToString()); - log.AddProperty("WRITER TIMEOUTS", writerTimeouts.ToString()); - log.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString()); - log.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString()); + log.AddProperty("ACTIVE THREADS", activeThreadCount.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("FREE THREADS", FreeThreads.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("READER TIMEOUTS", readerTimeouts.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("WRITER TIMEOUTS", writerTimeouts.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString(CultureInfo.InvariantCulture)); + log.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -1019,21 +1022,21 @@ public static void WorkErrored(ScheduleHistoryItem scheduleHistoryItem, Exceptio { // Write out the log entry for this event var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_FAILURE" }; - log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); + log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString(CultureInfo.InvariantCulture)); log.AddProperty("TYPE", scheduleHistoryItem.TypeFullName); if (exception != null) { log.AddProperty("EXCEPTION", exception.Message); } - log.AddProperty("RESCHEDULED FOR", Convert.ToString(scheduleHistoryItem.NextStart)); + log.AddProperty("RESCHEDULED FOR", Convert.ToString(scheduleHistoryItem.NextStart, CultureInfo.InvariantCulture)); log.AddProperty("SOURCE", scheduleHistoryItem.ScheduleSource.ToString()); - log.AddProperty("ACTIVE THREADS", activeThreadCount.ToString()); - log.AddProperty("FREE THREADS", FreeThreads.ToString()); - log.AddProperty("READER TIMEOUTS", readerTimeouts.ToString()); - log.AddProperty("WRITER TIMEOUTS", writerTimeouts.ToString()); - log.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString()); - log.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString()); + log.AddProperty("ACTIVE THREADS", activeThreadCount.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("FREE THREADS", FreeThreads.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("READER TIMEOUTS", readerTimeouts.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("WRITER TIMEOUTS", writerTimeouts.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString(CultureInfo.InvariantCulture)); + log.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -1053,15 +1056,15 @@ public static void WorkProgressing(SchedulerClient schedulerClient) { // Write out the log entry for this event var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_PROGRESSING" }; - log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); + log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString(CultureInfo.InvariantCulture)); log.AddProperty("TYPE", schedulerClient.GetType().FullName); log.AddProperty("SOURCE", schedulerClient.ScheduleHistoryItem.ScheduleSource.ToString()); - log.AddProperty("ACTIVE THREADS", activeThreadCount.ToString()); - log.AddProperty("FREE THREADS", FreeThreads.ToString()); - log.AddProperty("READER TIMEOUTS", readerTimeouts.ToString()); - log.AddProperty("WRITER TIMEOUTS", writerTimeouts.ToString()); - log.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString()); - log.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString()); + log.AddProperty("ACTIVE THREADS", activeThreadCount.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("FREE THREADS", FreeThreads.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("READER TIMEOUTS", readerTimeouts.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("WRITER TIMEOUTS", writerTimeouts.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString(CultureInfo.InvariantCulture)); + log.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -1102,15 +1105,15 @@ public static void WorkStarted(ScheduleHistoryItem scheduleHistoryItem) { // Write out the log entry for this event var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_STARTED" }; - log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); + log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString(CultureInfo.InvariantCulture)); log.AddProperty("TYPE", scheduleHistoryItem.TypeFullName); log.AddProperty("SOURCE", scheduleHistoryItem.ScheduleSource.ToString()); - log.AddProperty("ACTIVE THREADS", activeThreadCount.ToString()); - log.AddProperty("FREE THREADS", FreeThreads.ToString()); - log.AddProperty("READER TIMEOUTS", readerTimeouts.ToString()); - log.AddProperty("WRITER TIMEOUTS", writerTimeouts.ToString()); - log.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString()); - log.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString()); + log.AddProperty("ACTIVE THREADS", activeThreadCount.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("FREE THREADS", FreeThreads.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("READER TIMEOUTS", readerTimeouts.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("WRITER TIMEOUTS", writerTimeouts.ToString(CultureInfo.InvariantCulture)); + log.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString(CultureInfo.InvariantCulture)); + log.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -1246,8 +1249,8 @@ public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHis var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_COMPLETED" }; log.AddProperty("REASON", "Scheduler task has been stopped manually"); log.AddProperty("TYPE", scheduleHistoryItem.TypeFullName); - log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString()); - log.AddProperty("NEXT START", Convert.ToString(scheduleHistoryItem.NextStart)); + log.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString(CultureInfo.InvariantCulture)); + log.AddProperty("NEXT START", Convert.ToString(scheduleHistoryItem.NextStart, CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } } @@ -1494,7 +1497,7 @@ private static void LogWhyTaskNotRun(ScheduleItem scheduleItem) var log = new LogInfo(); log.AddProperty("EVENT NOT RUN REASON", strDebug.ToString()); - log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString()); + log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString(CultureInfo.InvariantCulture)); log.AddProperty("TYPE FULL NAME", scheduleItem.TypeFullName); log.LogTypeKey = "DEBUG"; LogController.Instance.AddLog(log); @@ -1507,7 +1510,7 @@ private static void LogEventAddedToProcessGroup(ScheduleItem scheduleItem) { var log = new LogInfo(); log.AddProperty("EVENT ADDED TO PROCESS GROUP " + scheduleItem.ProcessGroup, scheduleItem.TypeFullName); - log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString()); + log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString(CultureInfo.InvariantCulture)); log.LogTypeKey = "DEBUG"; LogController.Instance.AddLog(log); } diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingController.cs b/DNN Platform/Library/Services/Scheduling/SchedulingController.cs index e778492ddbd..98615d6cd40 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingController.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Scheduling using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; @@ -56,7 +57,7 @@ public static void DeleteSchedule(int scheduleID) DataProvider.Instance().DeleteSchedule(scheduleID); EventLogController.Instance.AddLog( "ScheduleID", - scheduleID.ToString(), + scheduleID.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.SCHEDULE_DELETED); diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs index 1605c4d88d7..badd10ea2f7 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs @@ -36,11 +36,13 @@ public enum EventName // it will not reliably complete /// The application starting. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] APPLICATION_START = 0, } public enum ScheduleSource { +#pragma warning disable CA1707 // Identifiers should not contain underscores /// The source is not known. NOT_SET = 0, @@ -55,10 +57,12 @@ public enum ScheduleSource /// The beginning of a request triggered the scheduled task. STARTED_FROM_BEGIN_REQUEST = 4, +#pragma warning restore CA1707 } public enum ScheduleStatus { +#pragma warning disable CA1707 // Identifiers should not contain underscores /// The status is not set. NOT_SET = 0, @@ -82,11 +86,13 @@ public enum ScheduleStatus /// The scheduler is stopped. STOPPED = 7, +#pragma warning restore CA1707 } /// public enum SchedulerMode { +#pragma warning disable CA1707 // Identifiers should not contain underscores /// DISABLED = 0, @@ -95,11 +101,13 @@ public enum SchedulerMode /// REQUEST_METHOD = 2, +#pragma warning restore CA1707 } public abstract class SchedulingProvider { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public EventName EventName; /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs b/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs index 6dde60ebbab..a6639040784 100644 --- a/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Services.Search.Controllers using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Web.Caching; @@ -147,13 +148,13 @@ public override string GetDocUrl(SearchResult searchResult) return url; } - private static ArrayList GetModuleTabs(int moduleID) + private static ArrayList GetModuleTabs(int moduleId) { - // no manual clearing of the cache exists; let is just expire - var cacheKey = string.Format(ModuleByIdCacheKey, moduleID); + // no manual clearing of the cache exists; let it just expire + var cacheKey = string.Format(CultureInfo.InvariantCulture, ModuleByIdCacheKey, moduleId); return CBO.GetCachedObject( - new CacheItemArgs(cacheKey, ModuleByIdCacheTimeOut, ModuleByIdCachePriority, moduleID), - (args) => CBO.FillCollection(DataProvider.Instance().GetModule(moduleID, Null.NullInteger), typeof(ModuleInfo))); + new CacheItemArgs(cacheKey, ModuleByIdCacheTimeOut, ModuleByIdCachePriority, moduleId), + (args) => CBO.FillCollection(DataProvider.Instance().GetModule(moduleId, Null.NullInteger), typeof(ModuleInfo))); } private static bool ModuleIsAvailable(TabInfo tab, ModuleInfo module) diff --git a/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs b/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs index 01d73b5a51c..28be51b1ea3 100644 --- a/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs @@ -152,12 +152,11 @@ private static void FillTagsValues(Document doc, SearchResult result) break; case Constants.ModifiedTimeTag: - DateTime modifiedTimeUtc; - DateTime.TryParseExact(field.StringValue, Constants.DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out modifiedTimeUtc); + DateTime.TryParseExact(field.StringValue, Constants.DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var modifiedTimeUtc); result.ModifiedTimeUtc = modifiedTimeUtc; break; default: - if (field.Name.StartsWith(Constants.NumericKeyPrefixTag)) + if (field.Name.StartsWith(Constants.NumericKeyPrefixTag, StringComparison.Ordinal)) { var key = field.Name.Substring(Constants.NumericKeyPrefixTag.Length); if (int.TryParse(field.StringValue, out intField)) @@ -168,7 +167,7 @@ private static void FillTagsValues(Document doc, SearchResult result) } } } - else if (field.Name.StartsWith(Constants.KeywordsPrefixTag)) + else if (field.Name.StartsWith(Constants.KeywordsPrefixTag, StringComparison.Ordinal)) { var key = field.Name.Substring(Constants.KeywordsPrefixTag.Length); if (!result.Keywords.ContainsKey(key)) @@ -342,7 +341,18 @@ private Tuple> GetResults(SearchQuery searchQuery) if (searchQuery.BeginModifiedTimeUtc > DateTime.MinValue && searchQuery.EndModifiedTimeUtc >= searchQuery.BeginModifiedTimeUtc) { - query.Add(NumericRangeQuery.NewLongRange(Constants.ModifiedTimeTag, long.Parse(searchQuery.BeginModifiedTimeUtc.ToString(Constants.DateTimeFormat)), long.Parse(searchQuery.EndModifiedTimeUtc.ToString(Constants.DateTimeFormat)), true, true), Occur.MUST); + query.Add( + NumericRangeQuery.NewLongRange( + Constants.ModifiedTimeTag, + long.Parse( + searchQuery.BeginModifiedTimeUtc.ToString(Constants.DateTimeFormat, CultureInfo.InvariantCulture), + CultureInfo.CurrentCulture), + long.Parse( + searchQuery.EndModifiedTimeUtc.ToString(Constants.DateTimeFormat, CultureInfo.InvariantCulture), + CultureInfo.CurrentCulture), + true, + true), + Occur.MUST); } if (searchQuery.RoleId > 0) diff --git a/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs b/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs index 31702b9d2a9..fd45115cf79 100644 --- a/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Search.Controllers { using System; + using System.Globalization; using System.Linq; using System.Text.RegularExpressions; @@ -46,7 +47,7 @@ public override bool HasViewPermission(SearchResult searchResult) return false; } - if (searchResult.UniqueKey.Contains("adminonly")) + if (searchResult.UniqueKey.Contains("adminonly", StringComparison.OrdinalIgnoreCase)) { var currentUser = UserController.Instance.GetCurrentUserInfo(); return currentUser.IsSuperUser @@ -54,20 +55,21 @@ public override bool HasViewPermission(SearchResult searchResult) || currentUser.UserID == userId; } - if (searchResult.UniqueKey.Contains("friendsandgroups")) + if (searchResult.UniqueKey.Contains("friendsandgroups", StringComparison.OrdinalIgnoreCase)) { - var extendedVisibility = searchResult.UniqueKey.IndexOf("_") != searchResult.UniqueKey.LastIndexOf("_") - ? searchResult.UniqueKey.Split('_')[2] - : string.Empty; + var extendedVisibility = + searchResult.UniqueKey.IndexOf("_", StringComparison.Ordinal) != searchResult.UniqueKey.LastIndexOf("_", StringComparison.Ordinal) + ? searchResult.UniqueKey.Split('_')[2] + : string.Empty; return HasSocialRelationship(userInSearchResult, UserController.Instance.GetCurrentUserInfo(), extendedVisibility); } - if (searchResult.UniqueKey.Contains("membersonly")) + if (searchResult.UniqueKey.Contains("membersonly", StringComparison.OrdinalIgnoreCase)) { return UserController.Instance.GetCurrentUserInfo().UserID != Null.NullInteger; } - if (searchResult.UniqueKey.Contains("allusers")) + if (searchResult.UniqueKey.Contains("allusers", StringComparison.OrdinalIgnoreCase)) { var scopeForRoles = PortalController.GetPortalSetting("SearchResult_ScopeForRoles", searchResult.PortalId, string.Empty) @@ -99,7 +101,7 @@ public override string GetDocUrl(SearchResult searchResult) private static int GetUserId(SearchDocumentToDelete searchResult) { var match = SearchResultMatchRegex.Match(searchResult.UniqueKey); - return match.Success ? Convert.ToInt32(match.Groups[1].Value) : Null.NullInteger; + return match.Success ? Convert.ToInt32(match.Groups[1].Value, CultureInfo.InvariantCulture) : Null.NullInteger; } private static bool HasSocialRelationship(UserInfo targetUser, UserInfo accessingUser, string extendedVisibility) diff --git a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs index ee753d92c3f..fcde0a05c3c 100644 --- a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs +++ b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Search { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -92,7 +93,7 @@ private string ScheduleItemSettingKey(int portalId, string propertyId) { Requires.NotNullOrEmpty("propertyId", propertyId); var t = this.GetType(); - return string.Join("_", "Search", t.Name, t.FullName.GetHashCode().ToString("x8"), portalId.ToString(), propertyId); + return string.Join("_", "Search", t.Name, t.FullName.GetHashCode().ToString("x8", CultureInfo.InvariantCulture), portalId.ToString(CultureInfo.InvariantCulture), propertyId); } } } diff --git a/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs b/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs index d16a7bfdd3e..cd245349749 100644 --- a/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs @@ -13,6 +13,7 @@ namespace DotNetNuke.Services.Search.Internals using System.Web; using System.Web.Caching; + using DotNetNuke.Abstractions.Portals; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; @@ -74,6 +75,7 @@ public IEnumerable GetSearchContentSourceList(int portalId) { var searchableModuleDefsCacheArgs = new CacheItemArgs( string.Format( + CultureInfo.InvariantCulture, SearchableModuleDefsKey, SearchableModuleDefsCacheKey, portalId, @@ -124,7 +126,7 @@ public void AddSearchDocuments(IEnumerable searchDocuments) } catch (Exception ex) { - Logger.ErrorFormat("Search Document error: {0}{1}{2}", searchDoc, Environment.NewLine, ex); + Logger.ErrorFormat(CultureInfo.InvariantCulture, "Search Document error: {0}{1}{2}", searchDoc, Environment.NewLine, ex); } } @@ -201,16 +203,13 @@ internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) case "module": // module crawler // get searchable module definition list - var portalId = int.Parse(cacheItem.CacheKey.Split('-')[1]); + var portalId = int.Parse(cacheItem.CacheKey.Split('-')[1], CultureInfo.InvariantCulture); var modules = ModuleController.Instance.GetSearchModules(portalId); var modDefIds = new HashSet(); foreach (ModuleInfo module in modules) { - if (!modDefIds.Contains(module.ModuleDefID)) - { - modDefIds.Add(module.ModuleDefID); - } + modDefIds.Add(module.ModuleDefID); } var list = modDefIds.Select(ModuleDefinitionController.GetModuleDefinitionByID).ToList(); @@ -332,12 +331,12 @@ private static string StripTagsRetainAttributes(string html, IEnumerable private object SearchDocumentTypeDisplayNameCallBack(CacheItemArgs cacheItem) { var data = new Dictionary(); - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + foreach (IPortalInfo portal in PortalController.Instance.GetPortals()) { - var searchContentSources = this.GetSearchContentSourceList(portal.PortalID); + var searchContentSources = this.GetSearchContentSourceList(portal.PortalId); foreach (var searchContentSource in searchContentSources) { - var key = string.Format("{0}-{1}-{2}", searchContentSource.SearchTypeId, searchContentSource.ModuleDefinitionId, Thread.CurrentThread.CurrentCulture); + var key = $"{searchContentSource.SearchTypeId}-{searchContentSource.ModuleDefinitionId}-{Thread.CurrentThread.CurrentCulture}"; if (!data.ContainsKey(key)) { data.Add(key, searchContentSource.LocalizedName); diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs b/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs index b2f7d420978..665b700edeb 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Search.Internals using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -377,14 +378,15 @@ public Analyzer GetCustomAnalyzer() { analyzer = Reflection.CreateInstance(analyzerType) as Analyzer; } - else if (analyzerType?.GetConstructor(new Type[] { typeof(Lucene.Net.Util.Version) }) != null) + else if (analyzerType?.GetConstructor([typeof(Lucene.Net.Util.Version),]) != null) { - analyzer = Reflection.CreateInstance(analyzerType, new object[] { Constants.LuceneVersion }) as Analyzer; + analyzer = Reflection.CreateInstance(analyzerType, [Constants.LuceneVersion,]) as Analyzer; } if (analyzer == null) { throw new ArgumentException(string.Format( + CultureInfo.CurrentCulture, Localization.GetExceptionMessage("InvalidAnalyzerClass", "The class '{0}' cannot be created because it's invalid or is not an analyzer, will use default analyzer."), customAnalyzerType)); } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs b/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs index d6f8791aafa..5fd2fbd47de 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs @@ -57,8 +57,7 @@ public SearchType GetSearchTypeByName(string searchTypeName) public IEnumerable GetSynonyms(int portalId, string cultureCode, string term) { var terms = this.GetSynonymTerms(portalId, cultureCode); - IList synonyms; - if (terms == null || !terms.TryGetValue((term ?? string.Empty).ToLowerInvariant(), out synonyms)) + if (terms == null || !terms.TryGetValue((term ?? string.Empty).ToLowerInvariant(), out var synonyms)) { synonyms = this.emptySynonums; } @@ -69,9 +68,9 @@ public IEnumerable GetSynonyms(int portalId, string cultureCode, string /// public IEnumerable GetSynonymsGroups(int portalId, string cultureCode) { - var cacheKey = string.Format(CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); - var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); - return CBO.GetCachedObject>(cachArg, GetSynonymsGroupsCallBack); + var cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); + var cacheArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); + return CBO.GetCachedObject>(cacheArg, GetSynonymsGroupsCallBack); } /// @@ -108,10 +107,10 @@ public int AddSynonymsGroup(string synonymsTags, int portalId, string cultureCod } var newId = DataProvider.Instance().AddSynonymsGroup(synonymsTags, userId, portalId, cultureCode); - var cacheKey = string.Format(CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); + var cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); - cacheKey = string.Format(CacheKeyFormat, SynonymTermsCacheKey, portalId, cultureCode); + cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SynonymTermsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); return newId; @@ -154,10 +153,10 @@ public int UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags, int por } DataProvider.Instance().UpdateSynonymsGroup(synonymsGroupId, synonymsTags, userId); - var cacheKey = string.Format(CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); + var cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); - cacheKey = string.Format(CacheKeyFormat, SynonymTermsCacheKey, portalId, cultureCode); + cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SynonymTermsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); return synonymsGroupId; } @@ -171,20 +170,20 @@ public void DeleteSynonymsGroup(int synonymsGroupId, int portalId, string cultur } DataProvider.Instance().DeleteSynonymsGroup(synonymsGroupId); - var cacheKey = string.Format(CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); + var cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); - cacheKey = string.Format(CacheKeyFormat, SynonymTermsCacheKey, portalId, cultureCode); + cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SynonymTermsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); } /// public SearchStopWords GetSearchStopWords(int portalId, string cultureCode) { - var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); - var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); - var list = CBO.GetCachedObject>(cachArg, this.GetSearchStopWordsCallBack); - return list == null ? null : list.FirstOrDefault(); + var cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); + var cacheArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); + var list = CBO.GetCachedObject>(cacheArg, this.GetSearchStopWordsCallBack); + return list?.FirstOrDefault(); } /// @@ -213,7 +212,7 @@ public int AddSearchStopWords(string stopWords, int portalId, string cultureCode var userId = PortalSettings.Current.UserId; var newId = DataProvider.Instance().AddSearchStopWords(stopWords, userId, portalId, cultureCode); - var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); + var cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); return newId; } @@ -249,7 +248,7 @@ public int UpdateSearchStopWords(int stopWordsId, string stopWords, int portalId var userId = PortalSettings.Current.UserId; DataProvider.Instance().UpdateSearchStopWords(stopWordsId, stopWords, userId); - var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); + var cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); return stopWordsId; } @@ -263,7 +262,7 @@ public void DeleteSearchStopWords(int stopWordsId, int portalId, string cultureC } DataProvider.Instance().DeleteSearchStopWords(stopWordsId); - var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); + var cacheKey = string.Format(CultureInfo.InvariantCulture, CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); } @@ -288,7 +287,7 @@ public DateTime GetSearchReindexRequestTime(int portalId) public DateTime SetSearchReindexRequestTime(int portalId) { var now = DateTime.Now; - var text = now.ToString(Constants.ReindexDateTimeFormat); + var text = now.ToString(Constants.ReindexDateTimeFormat, CultureInfo.InvariantCulture); if (portalId < 0) { @@ -350,13 +349,12 @@ public DateTime GetLastSuccessfulIndexingDateTime(int scheduleId) if (string.IsNullOrEmpty(lastValue)) { // try to fallback to old location where this was stored - var name = string.Format(LastIndexKeyFormat, Constants.SearchLastSuccessIndexName, scheduleId); + var name = string.Format(CultureInfo.InvariantCulture, LastIndexKeyFormat, Constants.SearchLastSuccessIndexName, scheduleId); lastValue = HostController.Instance.GetString(name, Null.NullString); } - DateTime lastTime; if (!string.IsNullOrEmpty(lastValue) && - DateTime.TryParseExact(lastValue, Constants.ReindexDateTimeFormat, null, DateTimeStyles.None, out lastTime)) + DateTime.TryParseExact(lastValue, Constants.ReindexDateTimeFormat, null, DateTimeStyles.None, out var lastTime)) { // retrieves the date as UTC but returns to caller as local lastTime = FixSqlDateTime(lastTime).ToLocalTime().ToLocalTime(); @@ -380,7 +378,7 @@ public void SetLastSuccessfulIndexingDateTime(int scheduleId, DateTime startDate .AddScheduleItemSetting( scheduleId, Constants.SearchLastSuccessIndexName, - startDateLocal.ToUniversalTime().ToString(Constants.ReindexDateTimeFormat)); + startDateLocal.ToUniversalTime().ToString(Constants.ReindexDateTimeFormat, CultureInfo.InvariantCulture)); } /// @@ -389,9 +387,8 @@ public DateTime GetIndexerCheckpointUtcTime(int scheduleId, string indexerKey) var settings = SchedulingProvider.Instance().GetScheduleItemSettings(scheduleId); var lastValue = settings[indexerKey] as string; - DateTime lastUtcTime; if (!string.IsNullOrEmpty(lastValue) && - DateTime.TryParseExact(lastValue, Constants.ReindexDateTimeFormat, null, DateTimeStyles.None, out lastUtcTime)) + DateTime.TryParseExact(lastValue, Constants.ReindexDateTimeFormat, null, DateTimeStyles.None, out var lastUtcTime)) { lastUtcTime = FixSqlDateTime(lastUtcTime); } @@ -406,7 +403,7 @@ public DateTime GetIndexerCheckpointUtcTime(int scheduleId, string indexerKey) /// public void SetIndexerCheckpointUtcTime(int scheduleId, string indexerKey, DateTime lastUtcTime) { - SchedulingProvider.Instance().AddScheduleItemSetting(scheduleId, indexerKey, lastUtcTime.ToString(Constants.ReindexDateTimeFormat)); + SchedulingProvider.Instance().AddScheduleItemSetting(scheduleId, indexerKey, lastUtcTime.ToString(Constants.ReindexDateTimeFormat, CultureInfo.InvariantCulture)); } /// @@ -453,7 +450,7 @@ public Tuple GetSearchMinMaxLength() { var exceptionMessage = Localization.GetExceptionMessage("SearchAnalyzerMinWordLength", "Search Analyzer: min word length ({0}) is greater than max word length ({1}) value"); throw new InvalidDataException( - string.Format(exceptionMessage, minWordLength, maxWordLength)); + string.Format(CultureInfo.InvariantCulture, exceptionMessage, minWordLength, maxWordLength)); } return new Tuple(minWordLength, maxWordLength); @@ -565,13 +562,13 @@ private static string FixLastWord(string lastWord, bool allowLeadingWildcard) var c1 = lastWord[0]; var c2 = lastWord[wordEndPos - 1]; - if (c1 == '(' || c1 == '{' || c1 == '[') + if (c1 is '(' or '{' or '[') { wordStartPos++; beginIsGroup = true; } - if (c2 == ')' || c2 == '}' || c2 == ']') + if (c2 is ')' or '}' or ']') { wordEndPos--; endIsGroup = true; @@ -585,8 +582,8 @@ private static string FixLastWord(string lastWord, bool allowLeadingWildcard) if (lastWord.Length > 0 && lastWord != "AND" && lastWord != "OR") { lastWord = (beginIsGroup && endIsGroup) - ? string.Format("{0} OR {1}{0}*", lastWord, allowLeadingWildcard ? "*" : string.Empty) - : string.Format("({0} OR {1}{0}*)", lastWord, allowLeadingWildcard ? "*" : string.Empty); + ? string.Format(CultureInfo.InvariantCulture, "{0} OR {1}{0}*", lastWord, allowLeadingWildcard ? "*" : string.Empty) + : string.Format(CultureInfo.InvariantCulture, "({0} OR {1}{0}*)", lastWord, allowLeadingWildcard ? "*" : string.Empty); } if (beginIsGroup) @@ -711,7 +708,7 @@ private static string GetResourceFile(string cultureCode) private static object GetSynonymsGroupsCallBack(CacheItemArgs cacheItem) { - var portalId = int.Parse(cacheItem.CacheKey.Split('_')[1]); + var portalId = int.Parse(cacheItem.CacheKey.Split('_')[1], CultureInfo.InvariantCulture); var cultureCode = cacheItem.CacheKey.Split('_')[2]; EnsurePortalDefaultsAreSet(portalId); @@ -730,7 +727,7 @@ private static string FoldToAscii(string searchPhrase) string space = string.Empty; while (asciiFilter.IncrementToken()) { - sb.AppendFormat("{0}{1}", space ?? string.Empty, asciiFilter.GetAttribute().Term); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", space, asciiFilter.GetAttribute().Term); if (string.IsNullOrEmpty(space)) { space = " "; @@ -751,7 +748,7 @@ private object SynonymTermsCallBack(CacheItemArgs cacheItem) { var parts = cacheItem.CacheKey.Split('_'); var allTerms = new Dictionary>(); - var portalId = int.Parse(parts[1]); + var portalId = int.Parse(parts[1], CultureInfo.InvariantCulture); var cultureCode = parts[2]; var groups = this.GetSynonymsGroups(portalId, cultureCode); if (groups == null) @@ -797,7 +794,7 @@ private object SynonymTermsCallBack(CacheItemArgs cacheItem) private object GetSearchStopWordsCallBack(CacheItemArgs cacheItem) { var splittedKeys = cacheItem.CacheKey.Split('_'); - var portalId = int.Parse(splittedKeys[1]); + var portalId = int.Parse(splittedKeys[1], CultureInfo.InvariantCulture); var cultureCode = splittedKeys[2]; EnsurePortalDefaultsAreSet(portalId); diff --git a/DNN Platform/Library/Services/Search/ModuleIndexer.cs b/DNN Platform/Library/Services/Search/ModuleIndexer.cs index ec1ed91da7e..f4fb0e6fa86 100644 --- a/DNN Platform/Library/Services/Search/ModuleIndexer.cs +++ b/DNN Platform/Library/Services/Search/ModuleIndexer.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Services.Search using System.Collections.Generic; using System.Data.SqlTypes; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using DotNetNuke.Abstractions.Modules; @@ -107,6 +108,7 @@ public override int IndexSearchDocuments(int portalId, ScheduleHistoryItem sched if (Logger.IsTraceEnabled) { Logger.TraceFormat( + CultureInfo.InvariantCulture, "ModuleIndexer: {0} search documents found for module [{1} mid:{2}]", searchItems.Count, module.DesktopModule.ModuleName, @@ -204,14 +206,15 @@ private static void ThrowLogError(ModuleInfo module, Exception ex) try { var message = string.Format( - Localization.GetExceptionMessage( - "ErrorCreatingBusinessControllerClass", - "Error Creating BusinessControllerClass '{0}' of module({1}) id=({2}) in tab({3}) and portal({4})"), - module.DesktopModule.BusinessControllerClass, - module.DesktopModule.ModuleName, - module.ModuleID, - module.TabID, - module.PortalID); + CultureInfo.InvariantCulture, + Localization.GetExceptionMessage( + "ErrorCreatingBusinessControllerClass", + "Error Creating BusinessControllerClass '{0}' of module({1}) id=({2}) in tab({3}) and portal({4})"), + module.DesktopModule.BusinessControllerClass, + module.DesktopModule.ModuleName, + module.ModuleID, + module.TabID, + module.PortalID); throw new BusinessControllerClassException(message, ex); } catch (Exception ex1) diff --git a/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs b/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs index 88fab9805a9..6406b524411 100644 --- a/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs @@ -15,10 +15,12 @@ public class SearchContentModuleInfo { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected ModuleSearchBase SearchBaseControllerType; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected ModuleInfo MModInfo; public ModuleSearchBase ModSearchBaseControllerType diff --git a/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs index 8cb47f2b8b4..8050a7ad338 100644 --- a/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs @@ -3,11 +3,10 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { - using System.Collections; + using DotNetNuke.Collections; /// Represents a collection of SearchContentModuleInfo objects. -#pragma warning disable 0618 - public class SearchContentModuleInfoCollection : CollectionBase + public class SearchContentModuleInfoCollection : GenericCollectionBase { /// Initializes a new instance of the class. public SearchContentModuleInfoCollection() @@ -28,64 +27,6 @@ public SearchContentModuleInfoCollection(SearchContentModuleInfo[] value) this.AddRange(value); } - /// - /// Gets the SearchContentModuleInfoCollection at the specified index in the collection. - /// In VB.Net, this property is the indexer for the SearchContentModuleInfoCollection class. - /// - /// The zero-based index of the element to get or set. - public SearchContentModuleInfo this[int index] - { - get - { - return (SearchContentModuleInfo)this.List[index]; - } - - set - { - this.List[index] = value; - } - } - - /// Add an element of the specified SearchContentModuleInfo to the end of the collection. - /// An object of type SearchContentModuleInfo to add to the collection. - /// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection. - public int Add(SearchContentModuleInfo value) - { - return this.List.Add(value); - } - - /// Gets the index in the collection of the specified SearchContentModuleInfoCollection, if it exists in the collection. - /// The SearchContentModuleInfoCollection to locate in the collection. - /// The index in the collection of the specified object, if found; otherwise, -1. - public int IndexOf(SearchContentModuleInfo value) - { - return this.List.IndexOf(value); - } - - /// Add an element of the specified SearchContentModuleInfo to the collection at the designated index. - /// An Integer to indicate the location to add the object to the collection. - /// An object of type SearchContentModuleInfo to add to the collection. - public void Insert(int index, SearchContentModuleInfo value) - { - this.List.Insert(index, value); - } - - /// Remove the specified object of type SearchContentModuleInfo from the collection. - /// An object of type SearchContentModuleInfo to remove to the collection. - public void Remove(SearchContentModuleInfo value) - { - this.List.Remove(value); - } - - /// Gets a value indicating whether the collection contains the specified SearchContentModuleInfoCollection. - /// The SearchContentModuleInfoCollection to search for in the collection. - /// true if the collection contains the specified object; otherwise, false. - public bool Contains(SearchContentModuleInfo value) - { - // If value is not of type SearchContentModuleInfo, this will return false. - return this.List.Contains(value); - } - /// Copies the elements of the specified SearchContentModuleInfo array to the end of the collection. /// An array of type SearchContentModuleInfo containing the objects to add to the collection. public void AddRange(SearchContentModuleInfo[] value) @@ -106,14 +47,6 @@ public void AddRange(SearchContentModuleInfoCollection value) } } - /// Copies the collection objects to a one-dimensional Array instance beginning at the specified index. - /// The one-dimensional Array that is the destination of the values copied from the collection. - /// The index of the array at which to begin inserting. - public void CopyTo(SearchContentModuleInfo[] array, int index) - { - this.List.CopyTo(array, index); - } - /// Creates a one-dimensional Array instance containing the collection items. /// Array of type SearchContentModuleInfo. public SearchContentModuleInfo[] ToArray() @@ -123,5 +56,4 @@ public SearchContentModuleInfo[] ToArray() return arr; } } -#pragma warning restore 0618 } diff --git a/DNN Platform/Library/Services/Search/SearchEngineScheduler.cs b/DNN Platform/Library/Services/Search/SearchEngineScheduler.cs index 9373428d9f7..b3f81105c8f 100644 --- a/DNN Platform/Library/Services/Search/SearchEngineScheduler.cs +++ b/DNN Platform/Library/Services/Search/SearchEngineScheduler.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Search { using System; + using System.Globalization; using DotNetNuke.Abstractions.Modules; using DotNetNuke.Common; @@ -42,8 +43,8 @@ public override void DoWork() try { var lastSuccessFulDateTime = SearchHelper.Instance.GetLastSuccessfulIndexingDateTime(this.ScheduleHistoryItem.ScheduleID); - Logger.Trace("Search: Site Crawler - Starting. Content change start time " + lastSuccessFulDateTime.ToString("g")); - this.ScheduleHistoryItem.AddLogNote(string.Format("Starting. Content change start time {0:g}", lastSuccessFulDateTime)); + Logger.Trace("Search: Site Crawler - Starting. Content change start time " + lastSuccessFulDateTime.ToString("g", CultureInfo.InvariantCulture)); + this.ScheduleHistoryItem.AddLogNote(string.Format(CultureInfo.InvariantCulture, "Starting. Content change start time {0:g}", lastSuccessFulDateTime)); var searchEngine = new SearchEngine(this.ScheduleHistoryItem, lastSuccessFulDateTime, this.businessControllerProvider); try diff --git a/DNN Platform/Library/Services/Search/UserIndexer.cs b/DNN Platform/Library/Services/Search/UserIndexer.cs index f4375395b2e..1fde87b9024 100644 --- a/DNN Platform/Library/Services/Search/UserIndexer.cs +++ b/DNN Platform/Library/Services/Search/UserIndexer.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Services.Search using System.Collections.Generic; using System.Data; using System.Data.SqlTypes; + using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; @@ -87,7 +88,7 @@ public override int IndexSearchDocuments(int portalId, ScheduleHistoryItem sched DeleteDocuments(portalId, indexedUsers); var values = searchDocuments.Values; totalIndexed += IndexCollectedDocs(indexer, values); - this.SetLastCheckpointData(portalId, schedule.ScheduleID, startUserId.ToString()); + this.SetLastCheckpointData(portalId, schedule.ScheduleID, startUserId.ToString(CultureInfo.InvariantCulture)); this.SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, values.Last().ModifiedTimeUtc.ToLocalTime()); searchDocuments.Clear(); checkpointModified = true; @@ -118,7 +119,7 @@ public override int IndexSearchDocuments(int portalId, ScheduleHistoryItem sched if (checkpointModified) { // at last reset start user pointer - this.SetLastCheckpointData(portalId, schedule.ScheduleID, Null.NullInteger.ToString()); + this.SetLastCheckpointData(portalId, schedule.ScheduleID, Null.NullInteger.ToString(CultureInfo.InvariantCulture)); this.SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, DateTime.Now); } @@ -165,9 +166,9 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, Dict var splitValues = Regex.Split(propertyValue, Regex.Escape(ValueSplitFlag)); propertyValue = splitValues[0]; - var visibilityMode = (UserVisibilityMode)Convert.ToInt32(splitValues[1]); + var visibilityMode = (UserVisibilityMode)Convert.ToInt32(splitValues[1], CultureInfo.InvariantCulture); var extendedVisibility = splitValues[2]; - var modifiedTime = Convert.ToDateTime(splitValues[3]).ToUniversalTime(); + var modifiedTime = Convert.ToDateTime(splitValues[3], CultureInfo.InvariantCulture).ToUniversalTime(); if (string.IsNullOrEmpty(propertyValue)) { @@ -248,9 +249,7 @@ private static void AddBasicInformation(Dictionary searc searchDocuments.Add(searchDoc.UniqueKey, searchDoc); } - if (!searchDocuments.ContainsKey( - string.Format("{0}_{1}", userSearch.UserId, UserVisibilityMode.AdminOnly) - .ToLowerInvariant())) + if (!searchDocuments.ContainsKey($"{userSearch.UserId}_{UserVisibilityMode.AdminOnly}".ToLowerInvariant())) { if (!indexedUsers.Contains(userSearch.UserId)) { @@ -273,7 +272,7 @@ private static void AddBasicInformation(Dictionary searc searchDoc.NumericKeys.Add("superuser", Convert.ToInt32(userSearch.SuperUser)); searchDoc.Keywords.Add("username", userSearch.UserName); searchDoc.Keywords.Add("email", userSearch.Email); - searchDoc.Keywords.Add("createdondate", userSearch.CreatedOnDate.ToString(Constants.DateTimeFormat)); + searchDoc.Keywords.Add("createdondate", userSearch.CreatedOnDate.ToString(Constants.DateTimeFormat, CultureInfo.InvariantCulture)); searchDocuments.Add(searchDoc.UniqueKey, searchDoc); } } @@ -286,13 +285,13 @@ private static UserSearch GetUserSearch(IDataRecord reader) var modifiedOn = reader["LastModifiedOnDate"] as DateTime? ?? createdOn; var userSearch = new UserSearch { - UserId = Convert.ToInt32(reader["UserId"]), + UserId = Convert.ToInt32(reader["UserId"], CultureInfo.InvariantCulture), DisplayName = reader["DisplayName"].ToString(), Email = reader["Email"].ToString(), UserName = reader["Username"].ToString(), - SuperUser = Convert.ToBoolean(reader["IsSuperUser"]), - LastModifiedOnDate = Convert.ToDateTime(modifiedOn).ToUniversalTime(), - CreatedOnDate = Convert.ToDateTime(createdOn).ToUniversalTime(), + SuperUser = Convert.ToBoolean(reader["IsSuperUser"], CultureInfo.InvariantCulture), + LastModifiedOnDate = Convert.ToDateTime(modifiedOn, CultureInfo.InvariantCulture).ToUniversalTime(), + CreatedOnDate = Convert.ToDateTime(createdOn, CultureInfo.InvariantCulture).ToUniversalTime(), }; if (!string.IsNullOrEmpty(userSearch.FirstName) && userSearch.FirstName.Contains(ValueSplitFlag)) @@ -326,6 +325,7 @@ private static void DeleteDocuments(int portalId, ICollection usersList) { var mode = Enum.GetName(typeof(UserVisibilityMode), item); keyword.AppendFormat( + CultureInfo.InvariantCulture, "{2} {0}_{1} OR {0}_{1}* ", userId, mode, diff --git a/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs b/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs index 9ec7072e20b..03e56a840be 100644 --- a/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs +++ b/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs @@ -64,7 +64,7 @@ public override List GetUrls(int portalId, PortalSettings ps, string } catch (Exception) { - Logger.ErrorFormat("Error has occurred getting PageUrl for {0}", tab.TabName); + Logger.ErrorFormat(CultureInfo.InvariantCulture, "Error has occurred getting PageUrl for {0}", tab.TabName); } } } @@ -97,7 +97,7 @@ public virtual bool IsTabPublic(TabPermissionCollection objTabPermissions) if (!string.IsNullOrEmpty(role)) { // Deny permission - if (role.StartsWith("!")) + if (role.StartsWith("!", StringComparison.Ordinal)) { string denyRole = role.Replace("!", string.Empty); if (denyRole is Globals.glbRoleUnauthUserName or Globals.glbRoleAllUsersName) @@ -110,7 +110,7 @@ public virtual bool IsTabPublic(TabPermissionCollection objTabPermissions) } else { - if (role == Globals.glbRoleUnauthUserName || role == Globals.glbRoleAllUsersName) + if (role is Globals.glbRoleUnauthUserName or Globals.glbRoleAllUsersName) { hasPublicRole = true; break; @@ -162,7 +162,7 @@ private SitemapUrl GetPageUrl(TabInfo objTab, string language, PortalSettings ps { var pageUrl = new SitemapUrl(); var url = TestableGlobals.Instance.NavigateURL(objTab.TabID, objTab.IsSuperTab, ps, string.Empty, language); - if ((ps.SSLSetup == Abstractions.Security.SiteSslSetup.On || ps.SSLEnforced || (objTab.IsSecure && ps.SSLEnabled)) && url.StartsWith("http://")) + if ((ps.SSLSetup == Abstractions.Security.SiteSslSetup.On || ps.SSLEnforced || (objTab.IsSecure && ps.SSLEnabled)) && url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { url = "https://" + url.Substring("http://".Length); } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs b/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs index c4d79d1ba6f..1550464bb0d 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs @@ -57,7 +57,7 @@ public string CacheFileName currentCulture = Localization.GetPageLocale(this.portalSettings).Name.ToLowerInvariant(); } - this.cacheFileName = string.Format("sitemap" + ".{0}.xml", currentCulture); + this.cacheFileName = $"sitemap.{currentCulture}.xml"; } return this.cacheFileName; @@ -85,7 +85,7 @@ public string CacheIndexFileNameFormat /// The writer to which the sitemap is to be written. public void BuildSiteMap(TextWriter output) { - int cacheDays = int.Parse(PortalController.GetPortalSetting("SitemapCacheDays", this.portalSettings.PortalId, "1")); + int cacheDays = int.Parse(PortalController.GetPortalSetting("SitemapCacheDays", this.portalSettings.PortalId, "1"), CultureInfo.InvariantCulture); bool cached = cacheDays > 0; if (cached && this.CacheIsValid()) @@ -115,10 +115,10 @@ public void BuildSiteMap(TextWriter output) isProviderPriorityOverrided = bool.Parse(PortalController.GetPortalSetting(provider.Name + "Override", this.portalSettings.PortalId, "False")); // stored as an integer (pr * 100) to prevent from translating errors with the decimal point - providerPriorityValue = float.Parse(PortalController.GetPortalSetting(provider.Name + "Value", this.portalSettings.PortalId, "50")) / 100; + providerPriorityValue = float.Parse(PortalController.GetPortalSetting(provider.Name + "Value", this.portalSettings.PortalId, "50"), CultureInfo.InvariantCulture) / 100; // Get all urls from provider - List urls = new List(); + List urls = []; try { urls = provider.GetUrls(this.portalSettings.PortalId, this.portalSettings, SitemapVersion); @@ -206,7 +206,7 @@ public void BuildSiteMap(TextWriter output) public void GetSitemapIndexFile(string index, TextWriter output) { var currentCulture = Localization.GetPageLocale(this.portalSettings).Name.ToLowerInvariant(); - this.WriteSitemapFileToOutput(string.Format("sitemap_{0}.{1}.xml", index, currentCulture), output); + this.WriteSitemapFileToOutput($"sitemap_{index}.{currentCulture}.xml", output); } private static void LoadProviders() @@ -216,9 +216,9 @@ private static void LoadProviders() { lock (Lock) { - providers = new List(); + providers = []; - foreach (KeyValuePair comp in ComponentFactory.GetComponents()) + foreach (var comp in ComponentFactory.GetComponents()) { comp.Value.Name = comp.Key; comp.Value.Description = comp.Value.Description; @@ -236,7 +236,7 @@ private static void AddUrl(SitemapUrl sitemapUrl, XmlWriter writer) { writer.WriteStartElement("url"); writer.WriteElementString("loc", sitemapUrl.Url); - writer.WriteElementString("lastmod", sitemapUrl.LastModified.ToString("yyyy-MM-dd")); + writer.WriteElementString("lastmod", sitemapUrl.LastModified.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); writer.WriteElementString("changefreq", sitemapUrl.ChangeFrequency.ToString().ToLowerInvariant()); writer.WriteElementString("priority", sitemapUrl.Priority.ToString("F01", CultureInfo.InvariantCulture)); @@ -265,7 +265,7 @@ private static bool IsChildPortal(PortalSettings ps, HttpContext context) { IPortalAliasInfo portalAlias = arr[0]; portalName = Globals.GetPortalDomainName(ps.PortalAlias.HTTPAlias, null, true); - if (portalAlias.HttpAlias.IndexOf("/") > -1) + if (portalAlias.HttpAlias.IndexOf("/", StringComparison.Ordinal) > -1) { portalName = PortalController.GetPortalFolder(portalAlias.HttpAlias); } @@ -302,7 +302,7 @@ private void WriteSitemap(bool cached, TextWriter output, int index, List 0) ? string.Format(this.CacheIndexFileNameFormat, index) : this.CacheFileName; + var cachedFile = (index > 0) ? string.Format(CultureInfo.InvariantCulture, this.CacheIndexFileNameFormat, index) : this.CacheFileName; sitemapOutput = new StreamWriter(this.portalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + cachedFile, false, Encoding.UTF8); } @@ -318,8 +318,8 @@ private void WriteSitemap(bool cached, TextWriter output, int index, ListTrue is the cached file exists and is still valid, false otherwise. private bool CacheIsValid() { - int cacheDays = int.Parse(PortalController.GetPortalSetting("SitemapCacheDays", this.portalSettings.PortalId, "1")); + int cacheDays = int.Parse(PortalController.GetPortalSetting("SitemapCacheDays", this.portalSettings.PortalId, "1"), CultureInfo.InvariantCulture); var isValid = File.Exists(this.portalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + this.CacheFileName); if (!isValid) diff --git a/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs b/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs index 4dc920ad838..413a265edd7 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs @@ -367,7 +367,7 @@ public IList GetMessageAttachmentsByMessage(int messageId) { while (dr.Read()) { - var fileId = Convert.ToInt32(dr["FileID"]); + var fileId = Convert.ToInt32(dr["FileID"], CultureInfo.InvariantCulture); var file = FileManager.Instance.GetFile(fileId); if (file == null) diff --git a/DNN Platform/Library/Services/Social/Messaging/Exceptions/AttachmentsNotAllowed.cs b/DNN Platform/Library/Services/Social/Messaging/Exceptions/AttachmentsNotAllowed.cs index bf6768a4246..23cadcb26ee 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Exceptions/AttachmentsNotAllowed.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Exceptions/AttachmentsNotAllowed.cs @@ -5,9 +5,11 @@ namespace DotNetNuke.Services.Social.Messaging.Exceptions { using System; + using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; [Serializable] + [SuppressMessage("Microsoft.Design", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Breaking change")] public class AttachmentsNotAllowed : Exception { /// Initializes a new instance of the class. diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs index 65da3c7b2b5..de68876863b 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Social.Messaging.Internal { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using DotNetNuke.Common; @@ -334,7 +335,7 @@ public virtual int CountConversations(int userId, int portalId) return 0; } - var cacheKey = string.Format(DataCache.UserNotificationsConversationCountCacheKey, portalId, userId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.UserNotificationsConversationCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); if (cacheObject is int) @@ -360,7 +361,7 @@ public virtual int CountUnreadMessages(int userId, int portalId) return 0; } - var cacheKey = string.Format(DataCache.UserNewThreadsCountCacheKey, portalId, userId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.UserNewThreadsCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); if (cacheObject is int) @@ -424,7 +425,7 @@ public int CountLegacyMessages() { while (dr.Read()) { - totalRecords = Convert.ToInt32(dr["TotalRecords"]); + totalRecords = Convert.ToInt32(dr["TotalRecords"], CultureInfo.InvariantCulture); } } finally @@ -444,7 +445,7 @@ public IList GetNextMessagesForInstantDispatch(Guid schedulerI /// public IList GetNextMessagesForDigestDispatch(Frequency frequency, Guid schedulerInstance, int batchSize) { - return CBO.FillCollection(this.dataService.GetNextMessagesForDigestDispatch(Convert.ToInt32(frequency), schedulerInstance, batchSize)); + return CBO.FillCollection(this.dataService.GetNextMessagesForDigestDispatch((int)frequency, schedulerInstance, batchSize)); } /// diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs index 44b0c7743c1..1960cba2d2d 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Social.Messaging.Internal.Views { using System; using System.Data; + using System.Globalization; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; @@ -109,18 +110,18 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.MessageID = Convert.ToInt32(dr["MessageID"]); + this.MessageID = Convert.ToInt32(dr["MessageID"], CultureInfo.InvariantCulture); this.To = Null.SetNullString(dr["To"]); this.From = Null.SetNullString(dr["From"]); this.Subject = Null.SetNullString(dr["Subject"]); this.Body = HtmlUtils.ConvertToHtml(Null.SetNullString(dr["Body"])); this.ConversationId = Null.SetNullInteger(dr["ConversationID"]); this.ReplyAllAllowed = Null.SetNullBoolean(dr["ReplyAllAllowed"]); - this.SenderUserID = Convert.ToInt32(dr["SenderUserID"]); - this.RowNumber = Convert.ToInt32(dr["RowNumber"]); - this.AttachmentCount = Convert.ToInt32(dr["AttachmentCount"]); - this.NewThreadCount = Convert.ToInt32(dr["NewThreadCount"]); - this.ThreadCount = Convert.ToInt32(dr["ThreadCount"]); + this.SenderUserID = Convert.ToInt32(dr["SenderUserID"], CultureInfo.InvariantCulture); + this.RowNumber = Convert.ToInt32(dr["RowNumber"], CultureInfo.InvariantCulture); + this.AttachmentCount = Convert.ToInt32(dr["AttachmentCount"], CultureInfo.InvariantCulture); + this.NewThreadCount = Convert.ToInt32(dr["NewThreadCount"], CultureInfo.InvariantCulture); + this.ThreadCount = Convert.ToInt32(dr["ThreadCount"], CultureInfo.InvariantCulture); this.createdOnDate = Null.SetNullDateTime(dr["CreatedOnDate"]); } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs index 230dd6cea1a..95f534fa867 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs @@ -31,8 +31,7 @@ public string Size set { - long bytes; - if (!long.TryParse(value, out bytes)) + if (!long.TryParse(value, out var bytes)) { return; } @@ -44,7 +43,7 @@ public string Size { if (bytes > max) { - this.size = string.Format("{0:##.##} {1}", decimal.Divide(bytes, max), order); + this.size = $"{decimal.Divide(bytes, max):##.##} {order}"; return; } diff --git a/DNN Platform/Library/Services/Social/Messaging/Message.cs b/DNN Platform/Library/Services/Social/Messaging/Message.cs index f467f46a1af..102cafbe405 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Message.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Message.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Social.Messaging { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; @@ -108,7 +109,7 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.MessageID = Convert.ToInt32(dr["MessageID"]); + this.MessageID = Convert.ToInt32(dr["MessageID"], CultureInfo.InvariantCulture); this.PortalID = Null.SetNullInteger(dr["PortalId"]); this.To = Null.SetNullString(dr["To"]); this.From = Null.SetNullString(dr["From"]); @@ -116,7 +117,7 @@ public void Fill(IDataReader dr) this.Body = Null.SetNullString(dr["Body"]); this.ConversationId = Null.SetNullInteger(dr["ConversationID"]); this.ReplyAllAllowed = Null.SetNullBoolean(dr["ReplyAllAllowed"]); - this.SenderUserID = Convert.ToInt32(dr["SenderUserID"]); + this.SenderUserID = Convert.ToInt32(dr["SenderUserID"], CultureInfo.InvariantCulture); this.NotificationTypeID = Null.SetNullInteger(dr["NotificationTypeID"]); // add audit column data diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs b/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs index 8080c3db42b..b02e7b724ae 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Social.Messaging { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Entities; @@ -60,9 +61,9 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.MessageAttachmentID = Convert.ToInt32(dr["MessageAttachmentID"]); - this.MessageID = Convert.ToInt32(dr["MessageID"]); - this.FileID = Convert.ToInt32(dr["FileID"]); + this.MessageAttachmentID = Convert.ToInt32(dr["MessageAttachmentID"], CultureInfo.InvariantCulture); + this.MessageID = Convert.ToInt32(dr["MessageID"], CultureInfo.InvariantCulture); + this.FileID = Convert.ToInt32(dr["FileID"], CultureInfo.InvariantCulture); // add audit column data this.FillInternal(dr); diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs b/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs index 1b371155a49..3265494354f 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Social.Messaging { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; @@ -69,9 +70,9 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.RecipientID = Convert.ToInt32(dr["RecipientID"]); - this.MessageID = Convert.ToInt32(dr["MessageID"]); - this.UserID = Convert.ToInt32(dr["UserID"]); + this.RecipientID = Convert.ToInt32(dr["RecipientID"], CultureInfo.InvariantCulture); + this.MessageID = Convert.ToInt32(dr["MessageID"], CultureInfo.InvariantCulture); + this.UserID = Convert.ToInt32(dr["UserID"], CultureInfo.InvariantCulture); this.Archived = Null.SetNullBoolean(dr["Archived"]); this.Read = Null.SetNullBoolean(dr["Read"]); diff --git a/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs index 7a76b988f87..7dff1a31bd2 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Social.Messaging { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Text; @@ -84,10 +85,10 @@ public virtual void SendMessage(Message message, IList roles, IList MaxSubjectLength) { - throw new ArgumentException(string.Format(Localization.GetString("MsgSubjectTooBigError", Localization.ExceptionsResourceFile), MaxSubjectLength, message.Subject.Length)); + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Localization.GetString("MsgSubjectTooBigError", Localization.ExceptionsResourceFile), MaxSubjectLength, message.Subject.Length)); } - if (roles != null && roles.Count > 0 && !this.IsAdminOrHost(sender)) + if (roles is { Count: > 0, } && !this.IsAdminOrHost(sender)) { if (!roles.All(role => sender.Social.Roles.Any(userRoleInfo => role.RoleID == userRoleInfo.RoleID && userRoleInfo.IsOwner))) { @@ -121,7 +122,7 @@ public virtual void SendMessage(Message message, IList roles, IList MaxRecipients) { - throw new ArgumentException(string.Format(Localization.GetString("MsgToListTooBigError", Localization.ExceptionsResourceFile), MaxRecipients, sbTo.Length)); + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Localization.GetString("MsgToListTooBigError", Localization.ExceptionsResourceFile), MaxRecipients, sbTo.Length)); } // Cannot send message if within ThrottlingInterval @@ -129,11 +130,11 @@ public virtual void SendMessage(Message message, IList roles, IList 0) { var interval = this.GetPortalSettingAsDouble("MessagingThrottlingInterval", sender.PortalID, DefaultMessagingThrottlingIntervalMinutes); - throw new ThrottlingIntervalNotMetException(string.Format(Localization.GetString("MsgThrottlingIntervalNotMet", Localization.ExceptionsResourceFile), interval)); + throw new ThrottlingIntervalNotMetException(string.Format(CultureInfo.CurrentCulture, Localization.GetString("MsgThrottlingIntervalNotMet", Localization.ExceptionsResourceFile), interval)); } // Cannot have attachments if it's not enabled - if (fileIDs != null && fileIDs.Count > 0 && !InternalMessagingController.Instance.AttachmentsAllowed(sender.PortalID)) + if (fileIDs is { Count: > 0, } && !InternalMessagingController.Instance.AttachmentsAllowed(sender.PortalID)) { throw new AttachmentsNotAllowed(Localization.GetString("MsgAttachmentsNotAllowed", Localization.ExceptionsResourceFile)); } diff --git a/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs b/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs index 8d4caf2389a..c0f74055123 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs @@ -104,7 +104,7 @@ private static bool IsUserAbleToReceiveAnEmail(UserInfo recipientUser) /// The formatted sender address. private static string GetSenderAddress(string sender, string fromAddress) { - return string.Format("{0} < {1} >", sender, fromAddress); + return $"{sender} < {fromAddress} >"; } /// Gets the email body. @@ -115,8 +115,8 @@ private static string GetSenderAddress(string sender, string fromAddress) /// A string containing the email body with any tokens replaced. private static string GetEmailBody(string template, string messageBody, PortalSettings portalSettings, UserInfo recipientUser) { - template = template.Replace("[MESSAGEBODY]", messageBody); // moved to top since that we we can replace tokens in there too... - template = template.Replace("[RECIPIENTUSERID]", recipientUser.UserID.ToString(CultureInfo.InvariantCulture)); + template = template.Replace("[MESSAGEBODY]", messageBody); // moved to top since we can replace tokens in there too... + template = template.Replace("[RECIPIENTUSERID]", recipientUser.UserID.ToString(CultureInfo.CurrentCulture)); template = template.Replace("[RECIPIENTDISPLAYNAME]", recipientUser.DisplayName); template = template.Replace("[RECIPIENTEMAIL]", recipientUser.Email); template = template.Replace("[SITEURL]", GetPortalHomeUrl(portalSettings)); @@ -124,7 +124,7 @@ private static string GetEmailBody(string template, string messageBody, PortalSe template = template.Replace("[PORTALNAME]", portalSettings.PortalName); template = template.Replace("[LOGOURL]", GetPortalLogoUrl(portalSettings)); template = template.Replace("[UNSUBSCRIBEURL]", GetSubscriptionsUrl(portalSettings, recipientUser.UserID)); - template = template.Replace("[YEAR]", DateTime.Now.Year.ToString()); + template = template.Replace("[YEAR]", DateTime.Now.Year.ToString(CultureInfo.CurrentCulture)); template = ResolveUrl(portalSettings, template); return template; @@ -156,7 +156,7 @@ private static string GetEmailItemContent(PortalSettings portalSettings, Message var acceptUrl = GetRelationshipAcceptRequestUrl(portalSettings, authorId, "AcceptFriend"); var profileUrl = GetProfileUrl(portalSettings, authorId); var linkContent = GetFriendRequestActionsTemplate(portalSettings, defaultLanguage); - emailItemContent = emailItemContent.Replace("[FRIENDREQUESTACTIONS]", string.Format(linkContent, acceptUrl, profileUrl)); + emailItemContent = emailItemContent.Replace("[FRIENDREQUESTACTIONS]", string.Format(CultureInfo.CurrentCulture, linkContent, acceptUrl, profileUrl)); } if (messageDetails.NotificationTypeID == 3) @@ -167,7 +167,7 @@ private static string GetEmailItemContent(PortalSettings portalSettings, Message var acceptUrl = GetRelationshipAcceptRequestUrl(portalSettings, authorId, "FollowBack"); var profileUrl = GetProfileUrl(portalSettings, authorId); var linkContent = GetFollowRequestActionsTemplate(portalSettings, defaultLanguage); - emailItemContent = emailItemContent.Replace("[FOLLOWREQUESTACTIONS]", string.Format(linkContent, acceptUrl, profileUrl)); + emailItemContent = emailItemContent.Replace("[FOLLOWREQUESTACTIONS]", string.Format(CultureInfo.CurrentCulture, linkContent, acceptUrl, profileUrl)); } // No social actions for the rest of notifications types @@ -242,12 +242,7 @@ private static string GetSenderName(string displayName, string portalName) /// The handler url to fetch the picture for the specified userId. private static string GetProfilePicUrl(PortalSettings portalSettings, int userId) { - return string.Format( - "http://{0}/DnnImageHandler.ashx?mode=profilepic&userId={1}&h={2}&w={3}", - portalSettings.DefaultPortalAlias, - userId, - 64, - 64); + return $"http://{portalSettings.DefaultPortalAlias}/DnnImageHandler.ashx?mode=profilepic&userId={userId}&h={64}&w={64}"; } /// Gets the relationship accept request URL. @@ -257,13 +252,7 @@ private static string GetProfilePicUrl(PortalSettings portalSettings, int userId /// The handler url to fetch the relationship picture for the specified userId. private static string GetRelationshipAcceptRequestUrl(PortalSettings portalSettings, int userId, string action) { - return string.Format( - "http://{0}/tabid/{1}/userId/{2}/action/{3}/{4}", - portalSettings.DefaultPortalAlias, - portalSettings.UserTabId, - userId.ToString(CultureInfo.InvariantCulture), - action, - Globals.glbDefaultPage); + return $"http://{portalSettings.DefaultPortalAlias}/tabid/{portalSettings.UserTabId}/userId/{userId.ToString(CultureInfo.InvariantCulture)}/action/{action}/{Globals.glbDefaultPage}"; } /// Gets the profile URL. @@ -272,12 +261,7 @@ private static string GetRelationshipAcceptRequestUrl(PortalSettings portalSetti /// The handler url to fetch the profile picture for the specified userId. private static string GetProfileUrl(PortalSettings portalSettings, int userId) { - return string.Format( - "http://{0}/tabid/{1}/userId/{2}/{3}", - portalSettings.DefaultPortalAlias, - portalSettings.UserTabId, - userId.ToString(CultureInfo.InvariantCulture), - Globals.glbDefaultPage); + return $"http://{portalSettings.DefaultPortalAlias}/tabid/{portalSettings.UserTabId}/userId/{userId.ToString(CultureInfo.InvariantCulture)}/{Globals.glbDefaultPage}"; } /// Gets the display name. @@ -297,7 +281,7 @@ private static string GetDisplayName(PortalSettings portalSettings, int userId) /// The handler url to fetch a notification for the specified userId. private static string GetNotificationUrl(PortalSettings portalSettings, int userId) { - var cacheKey = string.Format("MessageCenterTab:{0}:{1}", portalSettings.PortalId, portalSettings.CultureCode); + var cacheKey = $"MessageCenterTab:{portalSettings.PortalId}:{portalSettings.CultureCode}"; var messageTabId = DataCache.GetCache(cacheKey); if (messageTabId <= 0) { @@ -323,12 +307,7 @@ private static string GetNotificationUrl(PortalSettings portalSettings, int user DataCache.SetCache(cacheKey, messageTabId, TimeSpan.FromMinutes(20)); } - return string.Format( - "http://{0}/tabid/{1}/userId/{2}/{3}#dnnCoreNotification", - portalSettings.DefaultPortalAlias, - messageTabId, - userId, - Globals.glbDefaultPage); + return $"http://{portalSettings.DefaultPortalAlias}/tabid/{messageTabId}/userId/{userId}/{Globals.glbDefaultPage}#dnnCoreNotification"; } /// Gets the portal logo URL. @@ -336,11 +315,7 @@ private static string GetNotificationUrl(PortalSettings portalSettings, int user /// A Url to the portal logo. private static string GetPortalLogoUrl(PortalSettings portalSettings) { - return string.Format( - "http://{0}/{1}/{2}", - GetDomainName(portalSettings), - portalSettings.HomeDirectory, - portalSettings.LogoFile); + return $"http://{GetDomainName(portalSettings)}/{portalSettings.HomeDirectory}/{portalSettings.LogoFile}"; } /// Gets the name of the domain. @@ -359,7 +334,7 @@ private static string GetDomainName(PortalSettings portalSettings) /// The default portal alias url. private static string GetPortalHomeUrl(PortalSettings portalSettings) { - return string.Format("http://{0}", portalSettings.DefaultPortalAlias); + return $"http://{portalSettings.DefaultPortalAlias}"; } /// Gets the subscriptions URL. @@ -368,11 +343,7 @@ private static string GetPortalHomeUrl(PortalSettings portalSettings) /// The url for viewing subscriptions. private static string GetSubscriptionsUrl(PortalSettings portalSettings, int userId) { - return string.Format( - "http://{0}/tabid/{1}/ctl/Profile/userId/{2}/pageno/3", - portalSettings.DefaultPortalAlias, - GetMessageTab(portalSettings), - userId); + return $"http://{portalSettings.DefaultPortalAlias}/tabid/{GetMessageTab(portalSettings)}/ctl/Profile/userId/{userId}/pageno/3"; } /// Gets the message tab. @@ -380,7 +351,7 @@ private static string GetSubscriptionsUrl(PortalSettings portalSettings, int use /// The tabId for where the Message Center is installed. private static int GetMessageTab(PortalSettings sendingPortal) { - var cacheKey = string.Format("MessageTab:{0}", sendingPortal.PortalId); + var cacheKey = $"MessageTab:{sendingPortal.PortalId}"; var cacheItemArgs = new CacheItemArgs(cacheKey, 30, CacheItemPriority.Default, sendingPortal); @@ -389,7 +360,7 @@ private static int GetMessageTab(PortalSettings sendingPortal) /// Gets the message tab callback. /// The cache item arguments. - /// The tab Id for the Message Center OR the user profile page tab Id. + /// The tab ID for the Message Center OR the user profile page tab ID. private static object GetMessageTabCallback(CacheItemArgs cacheItemArgs) { var portalSettings = cacheItemArgs.Params[0] as PortalSettings; @@ -415,9 +386,9 @@ private static object GetMessageTabCallback(CacheItemArgs cacheItemArgs) return portalSettings.UserTabId; } - private static string RemoveHttpUrlsIfSiteisSSLEnabled(string stringContainingHttp, PortalSettings portalSettings) + private static string RemoveHttpUrlsIfSiteIsSslEnabled(string stringContainingHttp, PortalSettings portalSettings) { - if (stringContainingHttp.IndexOf("http") > -1 && portalSettings != null && (portalSettings.SSLEnabled || portalSettings.SSLEnforced)) + if (stringContainingHttp.IndexOf("http", StringComparison.Ordinal) > -1 && portalSettings != null && (portalSettings.SSLEnabled || portalSettings.SSLEnforced)) { var urlToReplace = GetPortalHomeUrl(portalSettings); var urlReplaceWith = $"https://{portalSettings.DefaultPortalAlias}"; @@ -489,9 +460,9 @@ private static void SendDigest(IEnumerable messages, PortalSet var senderName = GetSenderName(senderUser.DisplayName, portalSettings.PortalName); var senderAddress = GetSenderAddress(senderName, fromAddress); - var subject = string.Format(emailSubjectTemplate, portalSettings.PortalName); + var subject = string.Format(CultureInfo.CurrentCulture, emailSubjectTemplate, portalSettings.PortalName); var body = GetEmailBody(emailBodyTemplate, emailBodyItemContent, portalSettings, recipientUser); - body = RemoveHttpUrlsIfSiteisSSLEnabled(body, portalSettings); + body = RemoveHttpUrlsIfSiteIsSslEnabled(body, portalSettings); Mail.Mail.SendEmail(fromAddress, senderAddress, toAddress, subject, body); @@ -524,8 +495,10 @@ private static void SendMessage(MessageRecipient messageRecipient) var emailBodyItemTemplate = GetEmailBodyItemTemplate(portalSettings, defaultLanguage); var author = UserController.Instance.GetUser(message.PortalID, message.SenderUserID); - var fromAddress = (UserController.GetUserByEmail(portalSettings.PortalId, portalSettings.Email) != null) ? - string.Format("{0} < {1} >", UserController.GetUserByEmail(portalSettings.PortalId, portalSettings.Email).DisplayName, portalSettings.Email) : portalSettings.Email; + var user = UserController.GetUserByEmail(portalSettings.PortalId, portalSettings.Email); + var fromAddress = (user != null) + ? $"{user.DisplayName} < {portalSettings.Email} >" + : portalSettings.Email; var toAddress = toUser.Email; if (Mail.Mail.IsValidEmailAddress(toUser.Email, toUser.PortalID)) @@ -536,11 +509,11 @@ private static void SendMessage(MessageRecipient messageRecipient) var subject = InternalMessagingController.Instance.GetMessage(message.MessageID).Subject; if (string.IsNullOrEmpty(subject)) { - subject = string.Format(GetEmailSubjectTemplate(portalSettings, defaultLanguage), portalSettings.PortalName); + subject = string.Format(CultureInfo.CurrentCulture, GetEmailSubjectTemplate(portalSettings, defaultLanguage), portalSettings.PortalName); } var body = GetEmailBody(emailBodyTemplate, emailBodyItemContent, portalSettings, toUser); - body = RemoveHttpUrlsIfSiteisSSLEnabled(body, portalSettings); + body = RemoveHttpUrlsIfSiteIsSslEnabled(body, portalSettings); // Include the attachment in the email message if configured to do so if (InternalMessagingController.Instance.AttachmentsAllowed(message.PortalID)) diff --git a/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs b/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs index ab48b3f78fa..c8b50ea929e 100644 --- a/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs @@ -35,7 +35,7 @@ public UserPreferencesController(IDataService dataService) /// public void SetUserPreference(UserPreference userPreference) { - this.dataService.SetUserPreference(userPreference.PortalId, userPreference.UserId, Convert.ToInt32(userPreference.MessagesEmailFrequency), Convert.ToInt32(userPreference.NotificationsEmailFrequency)); + this.dataService.SetUserPreference(userPreference.PortalId, userPreference.UserId, (int)userPreference.MessagesEmailFrequency, (int)userPreference.NotificationsEmailFrequency); } /// diff --git a/DNN Platform/Library/Services/Social/Notifications/Notification.cs b/DNN Platform/Library/Services/Social/Notifications/Notification.cs index 60e3488b8f0..a9e2e53c373 100644 --- a/DNN Platform/Library/Services/Social/Notifications/Notification.cs +++ b/DNN Platform/Library/Services/Social/Notifications/Notification.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Social.Notifications { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; @@ -119,14 +120,14 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.NotificationID = Convert.ToInt32(dr["MessageID"]); - this.NotificationTypeID = Convert.ToInt32(dr["NotificationTypeID"]); + this.NotificationID = Convert.ToInt32(dr["MessageID"], CultureInfo.InvariantCulture); + this.NotificationTypeID = Convert.ToInt32(dr["NotificationTypeID"], CultureInfo.InvariantCulture); this.To = Null.SetNullString(dr["To"]); this.From = Null.SetNullString(dr["From"]); this.Subject = Null.SetNullString(dr["Subject"]); this.Body = Null.SetNullString(dr["Body"]); this.Context = Null.SetNullString(dr["Context"]); - this.SenderUserID = Convert.ToInt32(dr["SenderUserID"]); + this.SenderUserID = Convert.ToInt32(dr["SenderUserID"], CultureInfo.InvariantCulture); this.ExpirationDate = Null.SetNullDateTime(dr["ExpirationDate"]); this.IncludeDismissAction = Null.SetNullBoolean(dr["IncludeDismissAction"]); diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs index 853c1985a8b..5d4b3cef71d 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Social.Notifications { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; @@ -91,7 +92,7 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"]); + this.NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"], CultureInfo.InvariantCulture); this.Name = dr["Name"].ToString(); this.Description = Null.SetNullString(dr["Description"]); var timeToLive = Null.SetNullInteger(dr["TTL"]); diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs index af5c28d88e8..e7800bec00a 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Social.Notifications { using System; using System.Data; + using System.Globalization; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; @@ -71,12 +72,12 @@ public int KeyID /// the data reader. public void Fill(IDataReader dr) { - this.NotificationTypeActionId = Convert.ToInt32(dr["NotificationTypeActionID"]); - this.NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"]); + this.NotificationTypeActionId = Convert.ToInt32(dr["NotificationTypeActionID"], CultureInfo.InvariantCulture); + this.NotificationTypeId = Convert.ToInt32(dr["NotificationTypeID"], CultureInfo.InvariantCulture); this.NameResourceKey = dr["NameResourceKey"].ToString(); this.DescriptionResourceKey = Null.SetNullString(dr["DescriptionResourceKey"]); this.ConfirmResourceKey = Null.SetNullString(dr["ConfirmResourceKey"]); - this.Order = Convert.ToInt32(dr["Order"]); + this.Order = Convert.ToInt32(dr["Order"], CultureInfo.InvariantCulture); this.APICall = dr["APICall"].ToString(); // add audit column data diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs index e34d7c11408..fc666dee1ce 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Social.Notifications { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Text; @@ -99,15 +100,15 @@ public virtual int CountNotifications(int userId, int portalId) return 0; } - var cacheKey = string.Format(DataCache.UserNotificationsCountCacheKey, portalId, userId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.UserNotificationsCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); - if (cacheObject is int) + if (cacheObject is int count) { - return (int)cacheObject; + return count; } - var count = this.dataService.CountNotifications(userId, portalId); + count = this.dataService.CountNotifications(userId, portalId); cache.Insert( cacheKey, count, @@ -145,7 +146,7 @@ public virtual void SendNotification(Notification notification, int portalId, IL if (!string.IsNullOrEmpty(notification.Subject) && notification.Subject.Length > ConstMaxSubject) { - throw new ArgumentException(string.Format(Localization.GetString("MsgSubjectTooBigError", Localization.ExceptionsResourceFile), ConstMaxSubject, notification.Subject.Length)); + throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("MsgSubjectTooBigError", Localization.ExceptionsResourceFile), ConstMaxSubject, notification.Subject.Length)); } var sbTo = new StringBuilder(); @@ -172,7 +173,7 @@ public virtual void SendNotification(Notification notification, int portalId, IL if (sbTo.Length > ConstMaxTo) { - throw new ArgumentException(string.Format(Localization.GetString("MsgToListTooBigError", Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length)); + throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Localization.GetString("MsgToListTooBigError", Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length)); } notification.To = sbTo.ToString().Trim(','); @@ -257,7 +258,7 @@ public virtual void DeleteNotification(int notificationId) var recipients = InternalMessagingController.Instance.GetMessageRecipients(notificationId); foreach (var recipient in recipients) { - DataCache.RemoveCache(string.Format(ToastsCacheKey, recipient.UserID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, ToastsCacheKey, recipient.UserID)); } this.dataService.DeleteNotification(notificationId); @@ -266,14 +267,14 @@ public virtual void DeleteNotification(int notificationId) /// public int DeleteUserNotifications(UserInfo user) { - DataCache.RemoveCache(string.Format(ToastsCacheKey, user.UserID)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, ToastsCacheKey, user.UserID)); return this.dataService.DeleteUserNotifications(user.UserID, user.PortalID); } /// public virtual void DeleteNotificationRecipient(int notificationId, int userId) { - DataCache.RemoveCache(string.Format(ToastsCacheKey, userId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, ToastsCacheKey, userId)); InternalMessagingController.Instance.DeleteMessageRecipient(notificationId, userId); var recipients = InternalMessagingController.Instance.GetMessageRecipients(notificationId); if (recipients.Count == 0) @@ -345,7 +346,7 @@ public virtual IList GetNotifications(int userId, int portalId, in /// public virtual NotificationType GetNotificationType(int notificationTypeId) { - var notificationTypeCacheKey = string.Format(DataCache.NotificationTypesCacheKey, notificationTypeId); + var notificationTypeCacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.NotificationTypesCacheKey, notificationTypeId); var cacheItemArgs = new CacheItemArgs(notificationTypeCacheKey, DataCache.NotificationTypesTimeOut, DataCache.NotificationTypesCachePriority, notificationTypeId); return CBO.GetCachedObject(cacheItemArgs, this.GetNotificationTypeCallBack); } @@ -355,7 +356,7 @@ public virtual NotificationType GetNotificationType(string name) { Requires.NotNullOrEmpty("name", name); - var notificationTypeCacheKey = string.Format(DataCache.NotificationTypesCacheKey, name); + var notificationTypeCacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.NotificationTypesCacheKey, name); var cacheItemArgs = new CacheItemArgs(notificationTypeCacheKey, DataCache.NotificationTypesTimeOut, DataCache.NotificationTypesCachePriority, name); return CBO.GetCachedObject(cacheItemArgs, this.GetNotificationTypeByNameCallBack); } @@ -363,7 +364,7 @@ public virtual NotificationType GetNotificationType(string name) /// public virtual NotificationTypeAction GetNotificationTypeAction(int notificationTypeActionId) { - var notificationTypeActionCacheKey = string.Format(DataCache.NotificationTypeActionsCacheKey, notificationTypeActionId); + var notificationTypeActionCacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.NotificationTypeActionsCacheKey, notificationTypeActionId); var cacheItemArgs = new CacheItemArgs(notificationTypeActionCacheKey, DataCache.NotificationTypeActionsTimeOut, DataCache.NotificationTypeActionsPriority, notificationTypeActionId); return CBO.GetCachedObject(cacheItemArgs, this.GetNotificationTypeActionCallBack); } @@ -373,7 +374,7 @@ public virtual NotificationTypeAction GetNotificationTypeAction(int notification { Requires.NotNullOrEmpty("name", name); - var notificationTypeActionCacheKey = string.Format(DataCache.NotificationTypeActionsByNameCacheKey, notificationTypeId, name); + var notificationTypeActionCacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.NotificationTypeActionsByNameCacheKey, notificationTypeId, name); var cacheItemArgs = new CacheItemArgs(notificationTypeActionCacheKey, DataCache.NotificationTypeActionsTimeOut, DataCache.NotificationTypeActionsPriority, notificationTypeId, name); return CBO.GetCachedObject(cacheItemArgs, this.GetNotificationTypeActionByNameCallBack); } @@ -398,7 +399,7 @@ public void MarkReadyForToast(Notification notification, UserInfo userInfo) public void MarkReadyForToast(Notification notification, int userId) { - DataCache.RemoveCache(string.Format(ToastsCacheKey, userId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, ToastsCacheKey, userId)); this.dataService.MarkReadyForToast(notification.NotificationID, userId); } @@ -411,7 +412,7 @@ public void MarkToastSent(int notificationId, int userId) /// public IList GetToasts(UserInfo userInfo) { - var cacheKey = string.Format(ToastsCacheKey, userInfo.UserID); + var cacheKey = string.Format(CultureInfo.InvariantCulture, ToastsCacheKey, userInfo.UserID); var toasts = DataCache.GetCache>(cacheKey); if (toasts == null) diff --git a/DNN Platform/Library/Services/Syndication/RssHandler.cs b/DNN Platform/Library/Services/Syndication/RssHandler.cs index 975d3c45579..43fb915e672 100644 --- a/DNN Platform/Library/Services/Syndication/RssHandler.cs +++ b/DNN Platform/Library/Services/Syndication/RssHandler.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Syndication { using System; using System.Collections.Generic; + using System.Globalization; using System.Web; using DotNetNuke.Common; @@ -40,8 +41,7 @@ public RssHandler(ISearchController searchController) /// protected override void PopulateChannel(string channelName, string userName) { - ModuleInfo objModule; - if (this.Request == null || this.Settings == null || this.Settings.ActiveTab == null || this.ModuleId == Null.NullInteger) + if (this.Request == null || this.Settings?.ActiveTab == null || this.ModuleId == Null.NullInteger) { return; } @@ -58,15 +58,17 @@ protected override void PopulateChannel(string channelName, string userName) } this.Channel["language"] = this.Settings.DefaultLanguage; - this.Channel["copyright"] = !string.IsNullOrEmpty(this.Settings.FooterText) ? this.Settings.FooterText.Replace("[year]", DateTime.Now.Year.ToString()) : string.Empty; + this.Channel["copyright"] = !string.IsNullOrEmpty(this.Settings.FooterText) ? this.Settings.FooterText.Replace("[year]", DateTime.Now.Year.ToString(CultureInfo.CurrentCulture)) : string.Empty; this.Channel["webMaster"] = this.Settings.Email; IList searchResults = null; - var query = new SearchQuery(); - query.PortalIds = new[] { this.Settings.PortalId }; - query.TabId = this.TabId; - query.ModuleId = this.ModuleId; - query.SearchTypeIds = new[] { SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId }; + var query = new SearchQuery + { + PortalIds = [this.Settings.PortalId,], + TabId = this.TabId, + ModuleId = this.ModuleId, + SearchTypeIds = [SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId,], + }; try { @@ -81,12 +83,12 @@ protected override void PopulateChannel(string channelName, string userName) { foreach (var result in searchResults) { - if (!result.UniqueKey.StartsWith(Constants.ModuleMetaDataPrefixTag) && TabPermissionController.CanViewPage()) + if (!result.UniqueKey.StartsWith(Constants.ModuleMetaDataPrefixTag, StringComparison.Ordinal) && TabPermissionController.CanViewPage()) { if (this.Settings.ActiveTab.StartDate < DateTime.Now && this.Settings.ActiveTab.EndDate > DateTime.Now) { - objModule = ModuleController.Instance.GetModule(result.ModuleId, query.TabId, false); - if (objModule != null && objModule.DisplaySyndicate && objModule.IsDeleted == false) + var objModule = ModuleController.Instance.GetModule(result.ModuleId, query.TabId, false); + if (objModule is { DisplaySyndicate: true, IsDeleted: false, }) { if (ModulePermissionController.CanViewModule(objModule)) { diff --git a/DNN Platform/Library/Services/SystemHealth/WebServerMonitor.cs b/DNN Platform/Library/Services/SystemHealth/WebServerMonitor.cs index 1f6774e790c..11a893f112c 100644 --- a/DNN Platform/Library/Services/SystemHealth/WebServerMonitor.cs +++ b/DNN Platform/Library/Services/SystemHealth/WebServerMonitor.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.SystemHealth { using System; + using System.Globalization; using System.Linq; using DotNetNuke.Entities.Host; @@ -52,7 +53,7 @@ public override void DoWork() this.ScheduleHistoryItem.Succeeded = false; this.ScheduleHistoryItem.AddLogNote($"Updating server health failed: {exc}."); this.Errored(ref exc); - Logger.ErrorFormat("Error in WebServerMonitor: {0}. {1}", exc.Message, exc.StackTrace); + Logger.ErrorFormat(CultureInfo.InvariantCulture, "Error in WebServerMonitor: {0}. {1}", exc.Message, exc.StackTrace); Exceptions.LogException(exc); } } diff --git a/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs b/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs index acad08973fc..7a93d97ebf9 100644 --- a/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs @@ -19,6 +19,7 @@ public abstract class BaseCustomTokenReplace : BaseTokenReplace { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected Dictionary PropertySource; @@ -155,7 +156,7 @@ protected override string replacedTokenValue(string objectName, string propertyN message = "Error accessing [{0}:{1}], {0} is an unknown datasource"; } - result = string.Format(message, objectName, propertyName); + result = string.Format(CultureInfo.CurrentCulture, message, objectName, propertyName); } if (this.DebugMessages && propertyNotFound) @@ -175,7 +176,7 @@ protected override string replacedTokenValue(string objectName, string propertyN message = "Error accessing [{0}:{1}], {1} is unknown for datasource {0}"; } - result = string.Format(message, objectName, propertyName); + result = string.Format(CultureInfo.CurrentCulture, message, objectName, propertyName); } return result; diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccess.cs index b723973cafd..3636710d71b 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccess.cs @@ -44,7 +44,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format outputFormat = "g"; } - int intIndex = int.Parse(propertyName); + int intIndex = int.Parse(propertyName, CultureInfo.InvariantCulture); if ((this.custom != null) && this.custom.Count > intIndex) { valueObject = this.custom[intIndex].ToString(); diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs index ba05a59aa19..3f1876c4a7a 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs @@ -1,118 +1,117 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Tokens -{ - using System; - using System.Globalization; +namespace DotNetNuke.Services.Tokens +{ + using System; + using System.Globalization; - using DotNetNuke.Entities.Users; + using DotNetNuke.Entities.Users; using DotNetNuke.Services.Localization; - public class CulturePropertyAccess : IPropertyAccess + public class CulturePropertyAccess : IPropertyAccess { /// - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } } /// - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) - { - CultureInfo ci = formatProvider; - if (propertyName.Equals(CultureDropDownTypes.EnglishName.ToString(), StringComparison.OrdinalIgnoreCase)) - { - return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.EnglishName), format); - } - - if (propertyName.Equals(CultureDropDownTypes.Lcid.ToString(), StringComparison.OrdinalIgnoreCase)) - { - return ci.LCID.ToString(); - } - - if (propertyName.Equals(CultureDropDownTypes.Name.ToString(), StringComparison.OrdinalIgnoreCase)) - { - return PropertyAccess.FormatString(ci.Name, format); - } - - if (propertyName.Equals(CultureDropDownTypes.NativeName.ToString(), StringComparison.OrdinalIgnoreCase)) - { - return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.NativeName), format); - } - - if (propertyName.Equals(CultureDropDownTypes.TwoLetterIsoCode.ToString(), StringComparison.OrdinalIgnoreCase)) - { - return PropertyAccess.FormatString(ci.TwoLetterISOLanguageName, format); - } - - if (propertyName.Equals(CultureDropDownTypes.ThreeLetterIsoCode.ToString(), StringComparison.OrdinalIgnoreCase)) - { - return PropertyAccess.FormatString(ci.ThreeLetterISOLanguageName, format); - } - - if (propertyName.Equals(CultureDropDownTypes.DisplayName.ToString(), StringComparison.OrdinalIgnoreCase)) - { - return PropertyAccess.FormatString(ci.DisplayName, format); - } - - if (propertyName.Equals("languagename", StringComparison.OrdinalIgnoreCase)) - { - if (ci.IsNeutralCulture) - { - return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.EnglishName), format); - } - else - { - return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.Parent.EnglishName), format); - } - } - - if (propertyName.Equals("languagenativename", StringComparison.OrdinalIgnoreCase)) - { - if (ci.IsNeutralCulture) - { - return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.NativeName), format); - } - else - { - return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.Parent.NativeName), format); - } - } - - if (propertyName.Equals("countryname", StringComparison.OrdinalIgnoreCase)) - { - if (ci.IsNeutralCulture) - { - // Neutral culture do not include region information - return string.Empty; - } - else - { - RegionInfo country = new RegionInfo(new CultureInfo(ci.Name, false).LCID); - return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(country.EnglishName), format); - } - } - - if (propertyName.Equals("countrynativename", StringComparison.OrdinalIgnoreCase)) - { - if (ci.IsNeutralCulture) - { - // Neutral culture do not include region information - return string.Empty; - } - else - { - RegionInfo country = new RegionInfo(new CultureInfo(ci.Name, false).LCID); - return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(country.NativeName), format); - } - } - - propertyNotFound = true; - return string.Empty; - } - } -} + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { + if (propertyName.Equals(nameof(CultureDropDownTypes.EnglishName), StringComparison.OrdinalIgnoreCase)) + { + return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(formatProvider.EnglishName), format); + } + + if (propertyName.Equals(nameof(CultureDropDownTypes.Lcid), StringComparison.OrdinalIgnoreCase)) + { + return formatProvider.LCID.ToString(formatProvider); + } + + if (propertyName.Equals(nameof(CultureDropDownTypes.Name), StringComparison.OrdinalIgnoreCase)) + { + return PropertyAccess.FormatString(formatProvider.Name, format); + } + + if (propertyName.Equals(nameof(CultureDropDownTypes.NativeName), StringComparison.OrdinalIgnoreCase)) + { + return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(formatProvider.NativeName), format); + } + + if (propertyName.Equals(nameof(CultureDropDownTypes.TwoLetterIsoCode), StringComparison.OrdinalIgnoreCase)) + { + return PropertyAccess.FormatString(formatProvider.TwoLetterISOLanguageName, format); + } + + if (propertyName.Equals(nameof(CultureDropDownTypes.ThreeLetterIsoCode), StringComparison.OrdinalIgnoreCase)) + { + return PropertyAccess.FormatString(formatProvider.ThreeLetterISOLanguageName, format); + } + + if (propertyName.Equals(nameof(CultureDropDownTypes.DisplayName), StringComparison.OrdinalIgnoreCase)) + { + return PropertyAccess.FormatString(formatProvider.DisplayName, format); + } + + if (propertyName.Equals("languagename", StringComparison.OrdinalIgnoreCase)) + { + if (formatProvider.IsNeutralCulture) + { + return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(formatProvider.EnglishName), format); + } + else + { + return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(formatProvider.Parent.EnglishName), format); + } + } + + if (propertyName.Equals("languagenativename", StringComparison.OrdinalIgnoreCase)) + { + if (formatProvider.IsNeutralCulture) + { + return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(formatProvider.NativeName), format); + } + else + { + return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(formatProvider.Parent.NativeName), format); + } + } + + if (propertyName.Equals("countryname", StringComparison.OrdinalIgnoreCase)) + { + if (formatProvider.IsNeutralCulture) + { + // Neutral culture do not include region information + return string.Empty; + } + else + { + RegionInfo country = new RegionInfo(new CultureInfo(formatProvider.Name, false).LCID); + return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(country.EnglishName), format); + } + } + + if (propertyName.Equals("countrynativename", StringComparison.OrdinalIgnoreCase)) + { + if (formatProvider.IsNeutralCulture) + { + // Neutral culture do not include region information + return string.Empty; + } + else + { + RegionInfo country = new RegionInfo(new CultureInfo(formatProvider.Name, false).LCID); + return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(country.NativeName), format); + } + } + + propertyNotFound = true; + return string.Empty; + } + } +} diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs index 654d9c8527d..92dcadcaf38 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs @@ -49,9 +49,9 @@ public string GetProperty(string propertyName, string format, CultureInfo format switch (valueObject.GetType().Name) { case "String": - return PropertyAccess.FormatString(Convert.ToString(valueObject), format); + return PropertyAccess.FormatString(Convert.ToString(valueObject, CultureInfo.InvariantCulture), format); case "Boolean": - return PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject), formatProvider); + return PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject, CultureInfo.InvariantCulture), formatProvider); case "DateTime": case "Double": case "Single": diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs index 2b373771c9b..41ecf47f999 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs @@ -49,9 +49,9 @@ public virtual string GetProperty(string propertyName, string format, CultureInf switch (valueObject.GetType().Name) { case "String": - return PropertyAccess.FormatString(Convert.ToString(valueObject), format); + return PropertyAccess.FormatString(Convert.ToString(valueObject, CultureInfo.InvariantCulture), format); case "Boolean": - return PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject), formatProvider); + return PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject, CultureInfo.InvariantCulture), formatProvider); case "DateTime": case "Double": case "Single": diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/JsonPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/JsonPropertyAccess.cs index 4f64cae9a56..1bfa572de6d 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/JsonPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/JsonPropertyAccess.cs @@ -2,37 +2,37 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -// ReSharper disable once CheckNamespace -namespace DotNetNuke.Services.Tokens -{ - using System; - using System.Globalization; +// ReSharper disable once CheckNamespace +namespace DotNetNuke.Services.Tokens +{ + using System; + using System.Globalization; - using DotNetNuke.Entities.Users; - using Newtonsoft.Json; + using DotNetNuke.Entities.Users; + using Newtonsoft.Json; - public abstract class JsonPropertyAccess : IPropertyAccess + public abstract class JsonPropertyAccess : IPropertyAccess { /// - public virtual CacheLevel Cacheability - { - get { return CacheLevel.notCacheable; } + public virtual CacheLevel Cacheability + { + get { return CacheLevel.notCacheable; } } /// - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) - { - var json = propertyName.Trim(); - if (!(json.StartsWith("{") && json.EndsWith("}"))) - { - throw new ArgumentException("The token argument is not property formatted JSON"); - } - - var deserializedObject = JsonConvert.DeserializeObject(json); - - return this.ProcessToken(deserializedObject, accessingUser, accessLevel); - } - - protected abstract string ProcessToken(TModel model, UserInfo accessingUser, Scope accessLevel); - } -} + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { + var json = propertyName.Trim(); + if (!(json.StartsWith("{", StringComparison.Ordinal) && json.EndsWith("}", StringComparison.Ordinal))) + { + throw new ArgumentException("The token argument is not property formatted JSON"); + } + + var deserializedObject = JsonConvert.DeserializeObject(json); + + return this.ProcessToken(deserializedObject, accessingUser, accessLevel); + } + + protected abstract string ProcessToken(TModel model, UserInfo accessingUser, Scope accessLevel); + } +} diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs index b6fb5a43bb9..9e241a1deb4 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs @@ -63,7 +63,7 @@ public static string FormatString(string value, string format) } else if (value != string.Empty) { - return string.Format(format, value); + return string.Format(CultureInfo.CurrentCulture, format, value); } else { @@ -80,9 +80,8 @@ public static string FormatString(string value, string format) /// Localized Property. public static string GetObjectProperty(object objObject, string strPropertyName, string strFormat, CultureInfo formatProvider, ref bool propertyNotFound) { - PropertyInfo objProperty = null; propertyNotFound = false; - if (CBO.GetProperties(objObject.GetType()).TryGetValue(strPropertyName, out objProperty)) + if (CBO.GetProperties(objObject.GetType()).TryGetValue(strPropertyName, out var objProperty)) { object propValue = objProperty.GetValue(objObject, null); Type t = typeof(string); @@ -91,9 +90,9 @@ public static string GetObjectProperty(object objObject, string strPropertyName, switch (objProperty.PropertyType.Name) { case "String": - return FormatString(Convert.ToString(propValue), strFormat); + return FormatString(Convert.ToString(propValue, CultureInfo.InvariantCulture), strFormat); case "Boolean": - return Boolean2LocalizedYesNo(Convert.ToBoolean(propValue), formatProvider); + return Boolean2LocalizedYesNo(Convert.ToBoolean(propValue, CultureInfo.InvariantCulture), formatProvider); case "DateTime": case "Double": case "Single": diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs index 01e7a8a6dc5..74d19fc4bb1 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs @@ -27,10 +27,7 @@ internal class InstallControllerImpl : IInstallController private static readonly string[] VersionSeparator = [".",]; /// - public string InstallerLogName - { - get { return "InstallerLog" + DateTime.Now.ToString("yyyyMMdd") + ".resources"; } - } + public string InstallerLogName => "InstallerLog" + DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".resources"; /// GetConnectionFromWebConfig - Returns Connection Configuration in web.config file. /// ConnectionConfig object. Null if information is not present in the config file. @@ -41,7 +38,7 @@ public ConnectionConfig GetConnectionFromWebConfig() string connection = Config.GetConnectionString(); foreach (string connectionParam in connection.Split(';')) { - int index = connectionParam.IndexOf("="); + int index = connectionParam.IndexOf("=", StringComparison.Ordinal); if (index > 0) { string key = connectionParam.Substring(0, index); @@ -421,44 +418,40 @@ public bool IsValidSqlServerVersion(string connectionString) { // todo: check if we can use globals.DatabaseEngineVersion instead var isValidVersion = false; - using (var sqlConnection = new SqlConnection(connectionString)) + using var sqlConnection = new SqlConnection(connectionString); + try { - try - { - sqlConnection.Open(); + sqlConnection.Open(); - var serverVersion = sqlConnection.ServerVersion; - if (serverVersion != null) - { - var serverVersionDetails = serverVersion.Split(VersionSeparator, StringSplitOptions.None); + var serverVersion = sqlConnection.ServerVersion; + if (serverVersion != null) + { + var serverVersionDetails = serverVersion.Split(VersionSeparator, StringSplitOptions.None); - var versionNumber = int.Parse(serverVersionDetails[0]); + var versionNumber = int.Parse(serverVersionDetails[0], CultureInfo.InvariantCulture); - // SQL Server 2017 and up, traditional version numbers are ok - if (versionNumber >= 14) - { - isValidVersion = true; - } - else if (versionNumber == 12) - { - // We need to check to see if this is actually Azure SQL, as it is compatible with DNN as well - using (var testCommand = new SqlCommand("select serverproperty('Edition')", sqlConnection)) - { - var result = testCommand.ExecuteScalar(); - isValidVersion = result.ToString().Equals("SQL Azure", StringComparison.OrdinalIgnoreCase); - } - } + // SQL Server 2017 and up, traditional version numbers are ok + if (versionNumber >= 14) + { + isValidVersion = true; + } + else if (versionNumber == 12) + { + // We need to check to see if this is actually Azure SQL, as it is compatible with DNN as well + using var testCommand = new SqlCommand("select serverproperty('Edition')", sqlConnection); + var result = testCommand.ExecuteScalar(); + isValidVersion = result.ToString().Equals("SQL Azure", StringComparison.OrdinalIgnoreCase); } } - catch (Exception) - { - // cannot connect with the details - isValidVersion = false; - } - finally - { - sqlConnection.Close(); - } + } + catch (Exception) + { + // cannot connect with the details + isValidVersion = false; + } + finally + { + sqlConnection.Close(); } return isValidVersion; @@ -467,11 +460,11 @@ public bool IsValidSqlServerVersion(string connectionString) /// public bool IsAbleToPerformDatabaseActions(string connectionString) { - var fakeName = "{databaseOwner}[{objectQualifier}FakeTable_" + DateTime.Now.Ticks.ToString("x16") + "]"; - var databaseActions = string.Format(@"CREATE TABLE {0}([fakeColumn] [int] NULL); SELECT * FROM {0}; DROP TABLE {0};", fakeName); + var fakeName = "{databaseOwner}[{objectQualifier}FakeTable_" + DateTime.Now.Ticks.ToString("x16", CultureInfo.InvariantCulture) + "]"; + var databaseActions = $"CREATE TABLE {fakeName}([fakeColumn] [int] NULL); SELECT * FROM {fakeName}; DROP TABLE {fakeName};"; var strExceptions = DataProvider.Instance().ExecuteScript(connectionString, databaseActions); - // if no exceptions we have necessary drop etc permissions + // if no exceptions we have necessary drop etc. permissions return string.IsNullOrEmpty(strExceptions); } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs index 1a4ea22a0ce..42a18476144 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs @@ -4,6 +4,8 @@ namespace DotNetNuke.Services.Upgrade.Internals.Steps { + using System.Globalization; + using DotNetNuke.Common.Utilities; using DotNetNuke.Instrumentation; @@ -24,7 +26,7 @@ public override void Execute() if (!string.IsNullOrEmpty(strError)) { this.Errors.Add(Localization.GetString("FcnMode", this.LocalInstallResourceFile) + ": " + strError); - Logger.TraceFormat("Adding FcnMode : {0}", strError); + Logger.TraceFormat(CultureInfo.InvariantCulture, "Adding FcnMode : {0}", strError); } this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs index 06b2ca9e0b7..cc50375ebff 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs @@ -11,12 +11,14 @@ public abstract class BaseInstallationStep : IInstallationStep { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected string LocalInstallResourceFile = "~/Install/App_LocalResources/InstallWizard.aspx.resx"; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected string LocalUpgradeResourceFile = "~/Install/App_LocalResources/UpgradeWizard.aspx.resx"; diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs index 52c44e16db1..3da110f66e1 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs @@ -1,50 +1,51 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Upgrade.InternalController.Steps -{ - using System.Collections.Generic; - using System.Linq; - using System.Web; +namespace DotNetNuke.Services.Upgrade.InternalController.Steps +{ + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Instrumentation; - using DotNetNuke.Services.Upgrade.Internals.Steps; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Upgrade.Internals.Steps; using Localization = DotNetNuke.Services.Localization.Localization; - /// FilePermissionCheck - Step that performs file permission checks prior to installation. - public class FilePermissionCheckStep : BaseInstallationStep - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FilePermissionCheckStep)); - - /// Main method to execute the step. - public override void Execute() - { - this.Percentage = 0; - this.Status = StepStatus.Running; - - var verifiers = new List - { - new FileSystemPermissionVerifier(HttpContext.Current.Server.MapPath("~")), - new FileSystemPermissionVerifier(HttpContext.Current.Server.MapPath("~/App_Data")), - }; - - this.Details = Localization.GetString("FolderCreateCheck", this.LocalInstallResourceFile) - + Localization.GetString("FileCreateCheck", this.LocalInstallResourceFile) - + Localization.GetString("FileDeleteCheck", this.LocalInstallResourceFile) - + Localization.GetString("FolderDeleteCheck", this.LocalInstallResourceFile); - Logger.TraceFormat("FilePermissionCheck - {0}", this.Details); - - if (!verifiers.All(v => v.VerifyAll())) - { - this.Errors.Add(string.Format(Localization.GetString("StepFailed", this.LocalInstallResourceFile), this.Details)); - } - - this.Percentage = 100; - - this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; - Logger.TraceFormat("FilePermissionCheck Status - {0}", this.Status); - } - } -} + /// FilePermissionCheck - Step that performs file permission checks prior to installation. + public class FilePermissionCheckStep : BaseInstallationStep + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FilePermissionCheckStep)); + + /// Main method to execute the step. + public override void Execute() + { + this.Percentage = 0; + this.Status = StepStatus.Running; + + var verifiers = new List + { + new FileSystemPermissionVerifier(HttpContext.Current.Server.MapPath("~")), + new FileSystemPermissionVerifier(HttpContext.Current.Server.MapPath("~/App_Data")), + }; + + this.Details = Localization.GetString("FolderCreateCheck", this.LocalInstallResourceFile) + + Localization.GetString("FileCreateCheck", this.LocalInstallResourceFile) + + Localization.GetString("FileDeleteCheck", this.LocalInstallResourceFile) + + Localization.GetString("FolderDeleteCheck", this.LocalInstallResourceFile); + Logger.TraceFormat(CultureInfo.InvariantCulture, "FilePermissionCheck - {0}", this.Details); + + if (!verifiers.All(v => v.VerifyAll())) + { + this.Errors.Add(string.Format(CultureInfo.CurrentCulture, Localization.GetString("StepFailed", this.LocalInstallResourceFile), this.Details)); + } + + this.Percentage = 100; + + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + Logger.TraceFormat(CultureInfo.InvariantCulture, "FilePermissionCheck Status - {0}", this.Status); + } + } +} diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IISVerificationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IISVerificationStep.cs index 32ef0406b14..e6f0acc0787 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IISVerificationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IISVerificationStep.cs @@ -2,58 +2,54 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Upgrade.Internals.Steps -{ - using System; - using System.Web; - - using Microsoft.Win32; - - using Localization = DotNetNuke.Services.Localization.Localization; - - /// Performs verifications about the IIS environment. - public class IISVerificationStep : BaseInstallationStep - { - /// Executes verifications on the IIS environment. - public override void Execute() - { - this.Status = StepStatus.Running; - - this.Details = Localization.GetString("CheckingIIS", this.LocalInstallResourceFile); - - // Checks for integrated pipeline mode. - if (!HttpRuntime.UsingIntegratedPipeline) - { - this.Errors.Add(Localization.GetString("IISVerificationFail", this.LocalInstallResourceFile)); - this.Status = StepStatus.Abort; - return; - } - - // Check for .Net Framework 4.8 - if (!IsDotNetVersionAtLeast(528040)) - { - this.Errors.Add(Localization.GetString("DotNetVersion48Required", this.LocalInstallResourceFile)); - this.Status = StepStatus.Abort; - return; - } - - this.Status = StepStatus.Done; - } - - private static bool IsDotNetVersionAtLeast(int version) - { - return GetVersion() >= version; - } - - private static int GetVersion() - { - int release = 0; - using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) - { - release = Convert.ToInt32(key.GetValue("Release")); - } - - return release; - } - } -} +namespace DotNetNuke.Services.Upgrade.Internals.Steps +{ + using System; + using System.Globalization; + using System.Web; + + using Microsoft.Win32; + + using Localization = DotNetNuke.Services.Localization.Localization; + + /// Performs verifications about the IIS environment. + public class IISVerificationStep : BaseInstallationStep + { + /// Executes verifications on the IIS environment. + public override void Execute() + { + this.Status = StepStatus.Running; + + this.Details = Localization.GetString("CheckingIIS", this.LocalInstallResourceFile); + + // Checks for integrated pipeline mode. + if (!HttpRuntime.UsingIntegratedPipeline) + { + this.Errors.Add(Localization.GetString("IISVerificationFail", this.LocalInstallResourceFile)); + this.Status = StepStatus.Abort; + return; + } + + // Check for .Net Framework 4.8 + if (!IsDotNetVersionAtLeast(528040)) + { + this.Errors.Add(Localization.GetString("DotNetVersion48Required", this.LocalInstallResourceFile)); + this.Status = StepStatus.Abort; + return; + } + + this.Status = StepStatus.Done; + } + + private static bool IsDotNetVersionAtLeast(int version) + { + return GetVersion() >= version; + } + + private static int GetVersion() + { + using var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"); + return Convert.ToInt32(key.GetValue("Release"), CultureInfo.InvariantCulture); + } + } +} diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs index a056848daf3..6c479d31ae6 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs @@ -4,9 +4,11 @@ namespace DotNetNuke.Services.Upgrade.Internals.Steps { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; /// This event gets fired when any activity gets recorded. /// The details text. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public delegate void ActivityEventHandler(string status); /// Interface for an Installation Step. diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs index 378795cfdae..52647b247ec 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs @@ -1,54 +1,55 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Upgrade.InternalController.Steps -{ - using System.IO; +namespace DotNetNuke.Services.Upgrade.InternalController.Steps +{ + using System.Globalization; + using System.IO; - using DotNetNuke.Instrumentation; - using DotNetNuke.Services.Upgrade.Internals.Steps; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Upgrade.Internals.Steps; using Localization = DotNetNuke.Services.Localization.Localization; - /// InstallExtensionsStep - Step that installs all the Extensions. - public class InstallExtensionsStep : BaseInstallationStep - { + /// InstallExtensionsStep - Step that installs all the Extensions. + public class InstallExtensionsStep : BaseInstallationStep + { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InstallExtensionsStep)); - /// Main method to execute the step. - public override void Execute() - { - var packages = Upgrade.GetInstallPackages(); - if (packages.Count == 0) - { - this.Percentage = 100; - this.Status = StepStatus.Done; - return; - } - - this.Percentage = 0; - this.Status = StepStatus.Running; - - var percentForEachStep = 100 / packages.Count; - var counter = 0; - foreach (var package in packages) - { - var file = package.Key; - var packageType = package.Value.PackageType; - var message = string.Format(Localization.GetString("InstallingExtension", this.LocalInstallResourceFile), packageType, Path.GetFileName(file)); - this.Details = message; - Logger.Trace(this.Details); - var success = Upgrade.InstallPackage(file, packageType, false); - if (!success) - { - this.Errors.Add(message); - break; - } - - this.Percentage = percentForEachStep * counter++; - } - - this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; - } - } -} + /// Main method to execute the step. + public override void Execute() + { + var packages = Upgrade.GetInstallPackages(); + if (packages.Count == 0) + { + this.Percentage = 100; + this.Status = StepStatus.Done; + return; + } + + this.Percentage = 0; + this.Status = StepStatus.Running; + + var percentForEachStep = 100 / packages.Count; + var counter = 0; + foreach (var package in packages) + { + var file = package.Key; + var packageType = package.Value.PackageType; + var message = string.Format(CultureInfo.CurrentCulture, Localization.GetString("InstallingExtension", this.LocalInstallResourceFile), packageType, Path.GetFileName(file)); + this.Details = message; + Logger.Trace(this.Details); + var success = Upgrade.InstallPackage(file, packageType, false); + if (!success) + { + this.Errors.Add(message); + break; + } + + this.Percentage = percentForEachStep * counter++; + } + + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + } + } +} diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs index 2673b77f6f1..6eb50f4c110 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs @@ -1,182 +1,183 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Upgrade.InternalController.Steps -{ - using System; - using System.IO; - using System.Web; - - using DotNetNuke.Common; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Users; - using DotNetNuke.Security.Membership; - using DotNetNuke.Services.FileSystem; - using DotNetNuke.Services.Localization; - using DotNetNuke.Services.Upgrade.Internals; - using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; +namespace DotNetNuke.Services.Upgrade.InternalController.Steps +{ + using System; + using System.Globalization; + using System.IO; + using System.Web; + + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Membership; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Upgrade.Internals; + using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; using DotNetNuke.Services.Upgrade.Internals.Steps; - /// InstallSiteStep - Step that installs Website. - public class InstallSiteStep : BaseInstallationStep + /// InstallSiteStep - Step that installs Website. + public class InstallSiteStep : BaseInstallationStep { - /// Main method to execute the step. - public override void Execute() - { - this.Percentage = 0; - this.Status = StepStatus.Running; - - // Set Status to None - Globals.SetStatus(Globals.UpgradeStatus.None); - - var installConfig = InstallController.Instance.GetInstallConfig(); - var percentForEachStep = 100 / installConfig.Portals.Count; - var counter = 0; - foreach (var portal in installConfig.Portals) - { - string description = Localization.GetString("CreatingSite", this.LocalInstallResourceFile); - this.Details = string.Format(description, portal.PortalName); - this.CreateSite(portal, installConfig); - - counter++; - this.Percentage = percentForEachStep * counter++; - } - - Globals.ResetAppStartElapseTime(); - - this.Status = StepStatus.Done; - } - - private void CreateSite(PortalConfig portal, InstallConfig installConfig) - { - var domain = string.Empty; - if (HttpContext.Current != null) - { - domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install/launchautoinstall", string.Empty).Replace("/install", string.Empty).Replace("/runinstall", string.Empty); - } - - var serverPath = Globals.ApplicationMapPath + "\\"; - - // Get the Portal Alias - var portalAlias = domain; - if (portal.PortAliases.Count > 0) - { - portalAlias = portal.PortAliases[0]; - } - - // Verify that portal alias is not present - if (PortalAliasController.Instance.GetPortalAlias(portalAlias.ToLowerInvariant()) != null) - { - string description = Localization.GetString("SkipCreatingSite", this.LocalInstallResourceFile); - this.Details = string.Format(description, portalAlias); - return; - } - - // Create default email - var email = portal.AdminEmail; - if (string.IsNullOrEmpty(email)) - { - email = "admin@" + domain.Replace("www.", string.Empty); - - // Remove any domain subfolder information ( if it exists ) - if (email.IndexOf("/") != -1) - { - email = email.Substring(0, email.IndexOf("/")); - } - } - - // install LP if installing in a different language - string culture = installConfig.InstallCulture; - if (!culture.Equals("en-us", StringComparison.OrdinalIgnoreCase)) - { - string installFolder = HttpContext.Current.Server.MapPath("~/Install/language"); - string lpFilePath = installFolder + "\\installlanguage.resources"; - - if (File.Exists(lpFilePath)) - { - if (!Upgrade.InstallPackage(lpFilePath, "Language", false)) - { - culture = Localization.SystemLocale; - } - } - else - { - culture = Localization.SystemLocale; - } - } - - var template = Upgrade.FindBestTemplate(portal.TemplateFileName, culture); - UserInfo userInfo; - - if (!string.IsNullOrEmpty(portal.AdminUserName)) - { - userInfo = Upgrade.CreateUserInfo(portal.AdminFirstName, portal.AdminLastName, portal.AdminUserName, portal.AdminPassword, email); - } - else - { - userInfo = Upgrade.CreateUserInfo(installConfig.SuperUser.FirstName, installConfig.SuperUser.LastName, installConfig.SuperUser.UserName, installConfig.SuperUser.Password, installConfig.SuperUser.Email); - } - - var childPath = string.Empty; - if (portal.IsChild) - { - childPath = portalAlias.Substring(portalAlias.LastIndexOf("/") + 1); - } - - // Create Folder Mappings config - if (!string.IsNullOrEmpty(installConfig.FolderMappingsSettings)) - { - FolderMappingsConfigController.Instance.SaveConfig(installConfig.FolderMappingsSettings); - } - - // add item to identity install from install wizard. - if (HttpContext.Current != null) - { - HttpContext.Current.Items.Add("InstallFromWizard", true); - } - - // Create Portal - var portalId = PortalController.Instance.CreatePortal( - portal.PortalName, - userInfo, - portal.Description, - portal.Keywords, - template, - portal.HomeDirectory, - portalAlias, - serverPath, - serverPath + childPath, - portal.IsChild); - - if (portalId > -1) - { - foreach (var alias in portal.PortAliases) - { - PortalController.Instance.AddPortalAlias(portalId, alias); - } - } - - // remove en-US from portal if installing in a different language - if (!culture.Equals("en-us", StringComparison.OrdinalIgnoreCase)) - { - var locale = LocaleController.Instance.GetLocale("en-US"); - Localization.RemoveLanguageFromPortal(portalId, locale.LanguageId, true); - } - - // Log user in to site - var loginStatus = UserLoginStatus.LOGIN_FAILURE; - UserController.UserLogin(portalId, userInfo.Username, installConfig.SuperUser.Password, string.Empty, string.Empty, string.Empty, ref loginStatus, false); - - InstallController.Instance.RemoveFromInstallConfig("//dotnetnuke/superuser/password"); - } - - // private void CreateFolderMappingConfig(string folderMappinsSettings) - // { - // string folderMappingsConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); - // if (!File.Exists(folderMappingsConfigPath)) - // { - // File.AppendAllText(folderMappingsConfigPath, "" + folderMappinsSettings + ""); - // } - // } - } -} + /// Main method to execute the step. + public override void Execute() + { + this.Percentage = 0; + this.Status = StepStatus.Running; + + // Set Status to None + Globals.SetStatus(Globals.UpgradeStatus.None); + + var installConfig = InstallController.Instance.GetInstallConfig(); + var percentForEachStep = 100 / installConfig.Portals.Count; + var counter = 0; + foreach (var portal in installConfig.Portals) + { + string description = Localization.GetString("CreatingSite", this.LocalInstallResourceFile); + this.Details = string.Format(CultureInfo.CurrentCulture, description, portal.PortalName); + this.CreateSite(portal, installConfig); + + counter++; + this.Percentage = percentForEachStep * counter++; + } + + Globals.ResetAppStartElapseTime(); + + this.Status = StepStatus.Done; + } + + private void CreateSite(PortalConfig portal, InstallConfig installConfig) + { + var domain = string.Empty; + if (HttpContext.Current != null) + { + domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install/launchautoinstall", string.Empty).Replace("/install", string.Empty).Replace("/runinstall", string.Empty); + } + + var serverPath = Globals.ApplicationMapPath + @"\"; + + // Get the Portal Alias + var portalAlias = domain; + if (portal.PortAliases.Count > 0) + { + portalAlias = portal.PortAliases[0]; + } + + // Verify that portal alias is not present + if (PortalAliasController.Instance.GetPortalAlias(portalAlias.ToLowerInvariant()) != null) + { + string description = Localization.GetString("SkipCreatingSite", this.LocalInstallResourceFile); + this.Details = string.Format(CultureInfo.CurrentCulture, description, portalAlias); + return; + } + + // Create default email + var email = portal.AdminEmail; + if (string.IsNullOrEmpty(email)) + { + email = "admin@" + domain.Replace("www.", string.Empty); + + // Remove any domain subfolder information ( if it exists ) + if (email.IndexOf("/", StringComparison.Ordinal) != -1) + { + email = email.Substring(0, email.IndexOf("/", StringComparison.Ordinal)); + } + } + + // install LP if installing in a different language + string culture = installConfig.InstallCulture; + if (!culture.Equals("en-us", StringComparison.OrdinalIgnoreCase)) + { + string installFolder = HttpContext.Current.Server.MapPath("~/Install/language"); + string lpFilePath = $@"{installFolder}\installlanguage.resources"; + + if (File.Exists(lpFilePath)) + { + if (!Upgrade.InstallPackage(lpFilePath, "Language", false)) + { + culture = Localization.SystemLocale; + } + } + else + { + culture = Localization.SystemLocale; + } + } + + var template = Upgrade.FindBestTemplate(portal.TemplateFileName, culture); + UserInfo userInfo; + + if (!string.IsNullOrEmpty(portal.AdminUserName)) + { + userInfo = Upgrade.CreateUserInfo(portal.AdminFirstName, portal.AdminLastName, portal.AdminUserName, portal.AdminPassword, email); + } + else + { + userInfo = Upgrade.CreateUserInfo(installConfig.SuperUser.FirstName, installConfig.SuperUser.LastName, installConfig.SuperUser.UserName, installConfig.SuperUser.Password, installConfig.SuperUser.Email); + } + + var childPath = string.Empty; + if (portal.IsChild) + { + childPath = portalAlias.Substring(portalAlias.LastIndexOf("/", StringComparison.Ordinal) + 1); + } + + // Create Folder Mappings config + if (!string.IsNullOrEmpty(installConfig.FolderMappingsSettings)) + { + FolderMappingsConfigController.Instance.SaveConfig(installConfig.FolderMappingsSettings); + } + + // add item to identity install from install wizard. + if (HttpContext.Current != null) + { + HttpContext.Current.Items.Add("InstallFromWizard", true); + } + + // Create Portal + var portalId = PortalController.Instance.CreatePortal( + portal.PortalName, + userInfo, + portal.Description, + portal.Keywords, + template, + portal.HomeDirectory, + portalAlias, + serverPath, + serverPath + childPath, + portal.IsChild); + + if (portalId > -1) + { + foreach (var alias in portal.PortAliases) + { + PortalController.Instance.AddPortalAlias(portalId, alias); + } + } + + // remove en-US from portal if installing in a different language + if (!culture.Equals("en-us", StringComparison.OrdinalIgnoreCase)) + { + var locale = LocaleController.Instance.GetLocale("en-US"); + Localization.RemoveLanguageFromPortal(portalId, locale.LanguageId, true); + } + + // Log user in to site + var loginStatus = UserLoginStatus.LOGIN_FAILURE; + UserController.UserLogin(portalId, userInfo.Username, installConfig.SuperUser.Password, string.Empty, string.Empty, string.Empty, ref loginStatus, false); + + InstallController.Instance.RemoveFromInstallConfig("//dotnetnuke/superuser/password"); + } + + // private void CreateFolderMappingConfig(string folderMappinsSettings) + // { + // string folderMappingsConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); + // if (!File.Exists(folderMappingsConfigPath)) + // { + // File.AppendAllText(folderMappingsConfigPath, "" + folderMappinsSettings + ""); + // } + // } + } +} diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSslStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSslStep.cs index 15585bb19eb..49182c179ba 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSslStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSslStep.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.Internals.Steps { + using System.Globalization; using System.Linq; using DotNetNuke.Abstractions.Portals; @@ -31,9 +32,9 @@ public override void Execute() foreach (var portalConfig in installConfig.Portals) { - var portal = (IPortalInfo)portals.FirstOrDefault(p => p.PortalName == portalConfig.PortalName); + IPortalInfo portal = portals.FirstOrDefault(p => p.PortalName == portalConfig.PortalName); var description = Localization.GetString("InstallingSslStep", this.LocalInstallResourceFile); - this.Details = string.Format(description, portalConfig.PortalName); + this.Details = string.Format(CultureInfo.CurrentCulture, description, portalConfig.PortalName); if (portal != null) { PortalController.UpdatePortalSetting(portal.PortalId, "SSLSetup", portalConfig.IsSsl ? "1" : "0", false); @@ -41,7 +42,7 @@ public override void Execute() } else { - this.Errors.Add(string.Format(Localization.GetString("InstallingSslStepSiteNotFound", this.LocalInstallResourceFile), portalConfig.PortalName)); + this.Errors.Add(string.Format(CultureInfo.CurrentCulture, Localization.GetString("InstallingSslStepSiteNotFound", this.LocalInstallResourceFile), portalConfig.PortalName)); } counter++; diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallVersionStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallVersionStep.cs index fc8d464c2cf..6305bc80a8c 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallVersionStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallVersionStep.cs @@ -2,36 +2,38 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Upgrade.Internals.Steps -{ - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Instrumentation; +namespace DotNetNuke.Services.Upgrade.Internals.Steps +{ + using System.Globalization; - using Localization = DotNetNuke.Services.Localization.Localization; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Instrumentation; - /// DatabaseVerificationStep - Step that performs database verification checks prior to installation. - public class InstallVersionStep : BaseInstallationStep - { + using Localization = DotNetNuke.Services.Localization.Localization; + + /// DatabaseVerificationStep - Step that performs database verification checks prior to installation. + public class InstallVersionStep : BaseInstallationStep + { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InstallVersionStep)); /// - public override void Execute() - { - this.Percentage = 0; - this.Status = StepStatus.Running; - - var databaseVersion = DataProvider.Instance().GetInstallVersion(); - - string strError = Config.UpdateInstallVersion(databaseVersion); - - if (!string.IsNullOrEmpty(strError)) - { - this.Errors.Add(Localization.GetString("InstallVersion", this.LocalInstallResourceFile) + ": " + strError); - Logger.TraceFormat("Adding InstallVersion : {0}", strError); - } - - this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; - } - } -} + public override void Execute() + { + this.Percentage = 0; + this.Status = StepStatus.Running; + + var databaseVersion = DataProvider.Instance().GetInstallVersion(); + + string strError = Config.UpdateInstallVersion(databaseVersion); + + if (!string.IsNullOrEmpty(strError)) + { + this.Errors.Add(Localization.GetString("InstallVersion", this.LocalInstallResourceFile) + ": " + strError); + Logger.TraceFormat(CultureInfo.InvariantCulture, "Adding InstallVersion : {0}", strError); + } + + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; + } + } +} diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs index a50951b84eb..8b25b7a46e3 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs @@ -3,6 +3,8 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { + using System; + using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Services.Upgrade.Internals; @@ -126,18 +128,18 @@ private static string GetUpgradeConnectionStringUserId() string connection = Config.GetUpgradeConnectionString(); // If connection string does not use integrated security, then get user id. - if (connection.ToLowerInvariant().Contains("user id") || connection.ToLowerInvariant().Contains("uid") || connection.ToLowerInvariant().Contains("user")) + if (connection.Contains("user id", StringComparison.OrdinalIgnoreCase) || connection.Contains("uid", StringComparison.OrdinalIgnoreCase) || connection.Contains("user", StringComparison.OrdinalIgnoreCase)) { string[] connectionParams = connection.Split(';'); foreach (string connectionParam in connectionParams) { - int index = connectionParam.IndexOf("="); + int index = connectionParam.IndexOf("=", StringComparison.Ordinal); if (index > 0) { string key = connectionParam.Substring(0, index); string value = connectionParam.Substring(index + 1); - if ("user id|uuid|user".Contains(key.Trim().ToLowerInvariant())) + if ("user id|uuid|user".Contains(key.Trim(), StringComparison.OrdinalIgnoreCase)) { dbUser = value.Trim(); } diff --git a/DNN Platform/Library/Services/Upgrade/Upgrade.cs b/DNN Platform/Library/Services/Upgrade/Upgrade.cs index 22abb9eb26c..47978ab5d93 100644 --- a/DNN Platform/Library/Services/Upgrade/Upgrade.cs +++ b/DNN Platform/Library/Services/Upgrade/Upgrade.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Services.Upgrade using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -395,7 +396,7 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe string description = XmlUtils.GetNodeValue(node.CreateNavigator(), "description"); string keyWords = XmlUtils.GetNodeValue(node.CreateNavigator(), "keywords"); string templateFileName = XmlUtils.GetNodeValue(node.CreateNavigator(), "templatefile"); - string serverPath = Globals.ApplicationMapPath + "\\"; + string serverPath = Globals.ApplicationMapPath + @"\"; bool isChild = bool.Parse(XmlUtils.GetNodeValue(node.CreateNavigator(), "ischild")); string homeDirectory = XmlUtils.GetNodeValue(node.CreateNavigator(), "homedirectory"); @@ -419,9 +420,9 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe email = "admin@" + domain.Replace("www.", string.Empty); // Remove any domain subfolder information ( if it exists ) - if (email.IndexOf("/") != -1) + if (email.IndexOf("/", StringComparison.Ordinal) != -1) { - email = email.Substring(0, email.IndexOf("/")); + email = email.Substring(0, email.IndexOf("/", StringComparison.Ordinal)); } } @@ -554,7 +555,7 @@ public static string DeleteFiles(string providerPath, Version version, bool writ HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Cleaning Up Files: " + stringVersion); } - string listFile = Globals.InstallMapPath + "Cleanup\\" + stringVersion + ".txt"; + string listFile = $@"{Globals.InstallMapPath}Cleanup\{stringVersion}.txt"; try { if (File.Exists(listFile)) @@ -597,14 +598,14 @@ public static string DeleteFiles(string providerPath, Version version, bool writ public static void ExecuteScripts(string strProviderPath) { DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ExecuteScripts:" + strProviderPath); - string scriptPath = Globals.ApplicationMapPath + "\\Install\\Scripts\\"; + string scriptPath = $@"{Globals.ApplicationMapPath}\Install\Scripts\"; if (Directory.Exists(scriptPath)) { string[] files = Directory.GetFiles(scriptPath); foreach (string file in files) { // Execute if script is a provider script - if (file.IndexOf("." + DefaultProvider) != -1) + if (file.Contains("." + DefaultProvider, StringComparison.OrdinalIgnoreCase)) { ExecuteScript(file, true); @@ -628,7 +629,7 @@ public static void ExecuteScripts(string strProviderPath) public static void ExecuteScript(string file) { // Execute if script is a provider script - if (file.IndexOf("." + DefaultProvider) != -1) + if (file.Contains("." + DefaultProvider, StringComparison.OrdinalIgnoreCase)) { ExecuteScript(file, true); } @@ -643,7 +644,7 @@ public static string GetInstallTemplate(XmlDocument xmlDoc) string installTemplate = Config.GetSetting("InstallTemplate"); try { - xmlDoc.Load(Globals.ApplicationMapPath + "\\Install\\" + installTemplate); + xmlDoc.Load($@"{Globals.ApplicationMapPath}\Install\{installTemplate}"); } catch { @@ -656,12 +657,12 @@ public static string GetInstallTemplate(XmlDocument xmlDoc) /// SetInstallTemplate saves the XmlDocument back to Installation Template specified in web.config. /// The Xml Document to save. - /// A string which contains the error massage - if appropriate. + /// A string which contains the error message - if appropriate. public static string SetInstallTemplate(XmlDocument xmlDoc) { string errorMessage = Null.NullString; string installTemplate = Config.GetSetting("InstallTemplate"); - string filePath = Globals.ApplicationMapPath + "\\Install\\" + installTemplate; + string filePath = $@"{Globals.ApplicationMapPath}\Install\{installTemplate}"; try { // ensure the file is not read-only @@ -741,7 +742,7 @@ public static string GetStringVersion(Version version) } else { - stringVersion += versionArray[i].ToString(); + stringVersion += versionArray[i].ToString(CultureInfo.InvariantCulture); } if (i < 2) @@ -815,7 +816,7 @@ public static ArrayList GetUpgradeScripts(string providerPath, Version databaseV string[] files = Directory.GetFiles(providerPath, "*." + DefaultProvider); Array.Sort(files); // The order of the returned file names is not guaranteed on certain NAS systems; use the Sort method if a specific sort order is required. - Logger.TraceFormat("GetUpgradedScripts databaseVersion:{0} applicationVersion:{1}", databaseVersion, ApplicationVersion); + Logger.TraceFormat(CultureInfo.InvariantCulture, "GetUpgradedScripts databaseVersion:{0} applicationVersion:{1}", databaseVersion, ApplicationVersion); foreach (string file in files) { @@ -832,24 +833,24 @@ public static ArrayList GetUpgradeScripts(string providerPath, Version databaseV scriptFiles.Add(file); // check if any incrementals exist - var incrementalfiles = AddAvailableIncrementalFiles(providerPath, version); - if (incrementalfiles != null) + var incrementalFiles = AddAvailableIncrementalFiles(providerPath, version); + if (incrementalFiles != null) { - scriptFiles.AddRange(incrementalfiles); + scriptFiles.AddRange(incrementalFiles); } - Logger.TraceFormat("GetUpgradedScripts including {0}", file); + Logger.TraceFormat(CultureInfo.InvariantCulture, "GetUpgradedScripts including {0}", file); } if (version == databaseVersion && version <= ApplicationVersion && GetFileName(file).Length == 9 + DefaultProvider.Length) { - var incrementalfiles = AddAvailableIncrementalFiles(providerPath, version); - if (incrementalfiles != null) + var incrementalFiles = AddAvailableIncrementalFiles(providerPath, version); + if (incrementalFiles != null) { - scriptFiles.AddRange(incrementalfiles); + scriptFiles.AddRange(incrementalFiles); } - Logger.TraceFormat("GetUpgradedScripts including {0}", file); + Logger.TraceFormat(CultureInfo.InvariantCulture, "GetUpgradedScripts including {0}", file); } // else @@ -914,12 +915,12 @@ public static void InitialiseHostSettings(XmlDocument xmlTemplate, bool writeFee settingValue = "support@" + domainName; // Remove any folders - settingValue = settingValue.Substring(0, settingValue.IndexOf("/")); + settingValue = settingValue.Substring(0, settingValue.IndexOf("/", StringComparison.Ordinal)); // Remove port number - if (settingValue.IndexOf(":") != -1) + if (settingValue.Contains(":", StringComparison.Ordinal)) { - settingValue = settingValue.Substring(0, settingValue.IndexOf(":")); + settingValue = settingValue.Substring(0, settingValue.IndexOf(":", StringComparison.Ordinal)); } } @@ -1151,13 +1152,13 @@ public static bool InstallPackage(string file, string packageType, bool writeFee } else if (Globals.Status != Globals.UpgradeStatus.None) { - var message = string.Format(Localization.GetString("InstallPackageError", Localization.ExceptionsResourceFile), file, "Manifest file missing"); + var message = string.Format(CultureInfo.InvariantCulture, Localization.GetString("InstallPackageError", Localization.ExceptionsResourceFile), file, "Manifest file missing"); DnnInstallLogger.InstallLogError(message); } } else { - // log the failure log when installer is invalid and not caught by mainfest file missing. + // log the failure log when installer is invalid and not caught by manifest file missing. foreach (var log in installer.InstallerInfo.Log.Logs .Where(l => l.Type == LogType.Failure)) { @@ -1418,7 +1419,7 @@ public static string UpgradeApplication(string providerPath, Version version, bo catch (Exception ex) { Logger.Error(ex); - exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + exceptions += $"Error: {ex.Message + ex.StackTrace}{Environment.NewLine}"; // log the results if (string.IsNullOrEmpty(exceptions)) @@ -1483,11 +1484,11 @@ public static string UpdateConfig(string providerPath, Version version, bool wri public static string UpdateConfig(string configFile, Version version, string reason) { DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); - string exceptions = string.Empty; + var exceptions = string.Empty; if (File.Exists(configFile)) { // Create XmlMerge instance from config file source - StreamReader stream = File.OpenText(configFile); + var stream = File.OpenText(configFile); try { var merge = new XmlMerge(stream, version.ToString(3), reason); @@ -1497,7 +1498,7 @@ public static string UpdateConfig(string configFile, Version version, string rea } catch (Exception ex) { - exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + exceptions += $"Error: {ex.Message + ex.StackTrace}{Environment.NewLine}"; Exceptions.Exceptions.LogException(ex); } finally @@ -1526,7 +1527,7 @@ public static string UpdateConfig(string providerPath, string configFile, Versio if (File.Exists(configFile)) { // Create XmlMerge instance from config file source - StreamReader stream = File.OpenText(configFile); + var stream = File.OpenText(configFile); try { var merge = new XmlMerge(stream, version.ToString(3), reason); @@ -1537,16 +1538,14 @@ public static string UpdateConfig(string providerPath, string configFile, Versio catch (Exception ex) { Logger.Error(ex); - exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + exceptions += $"Error: {ex.Message + ex.StackTrace}{Environment.NewLine}"; // log the results try { - using (StreamWriter streamWriter = File.CreateText(providerPath + Globals.FormatVersion(version) + "_Config.log")) - { - streamWriter.WriteLine(exceptions); - streamWriter.Close(); - } + using var streamWriter = File.CreateText(providerPath + Globals.FormatVersion(version) + "_Config.log"); + streamWriter.WriteLine(exceptions); + streamWriter.Close(); } catch (Exception exc) { @@ -2400,7 +2399,7 @@ private static void ParseFiles(XmlNode node, int portalId) { var fileName = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "filename"); var extension = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "extension"); - var size = long.Parse(XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "size")); + var size = long.Parse(XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "size"), CultureInfo.InvariantCulture); var width = XmlUtils.GetNodeValueInt(fileNode, "width"); var height = XmlUtils.GetNodeValueInt(fileNode, "height"); var contentType = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "contentType"); @@ -2477,7 +2476,7 @@ private static string GetStringVersionWithRevision(Version version) var stringVersion = GetStringVersion(version); if (version.Revision > 0) { - stringVersion += "." + version.Revision.ToString("D2"); + stringVersion += "." + version.Revision.ToString("D2", CultureInfo.InvariantCulture); } return stringVersion; diff --git a/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs b/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs index 3f0d009e879..094d22b06b1 100644 --- a/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs +++ b/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs @@ -1,118 +1,119 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.UserProfile -{ - using System; - using System.Web; +namespace DotNetNuke.Services.UserProfile +{ + using System; + using System.Globalization; + using System.Web; - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Users; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; using DotNetNuke.Instrumentation; - public class UserProfilePageHandler : IHttpHandler - { + public class UserProfilePageHandler : IHttpHandler + { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UserProfilePageHandler)); /// - public bool IsReusable - { - get - { - return true; - } + public bool IsReusable + { + get + { + return true; + } } - /// - /// This handler handles requests for LinkClick.aspx, but only those specifc - /// to file serving. - /// - /// System.Web.HttpContext). - public void ProcessRequest(HttpContext context) - { - PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - int userId = Null.NullInteger; - int portalId = portalSettings.PortalId; - - try - { - // try UserId - if (!string.IsNullOrEmpty(context.Request.QueryString["UserId"])) - { - userId = int.Parse(context.Request.QueryString["UserId"]); - if (UserController.GetUserById(portalId, userId) == null) - { - // The user cannot be found (potential DOS) - Exceptions.Exceptions.ProcessHttpException(context.Request); - } - } - - if (userId == Null.NullInteger) - { - // try userName - if (!string.IsNullOrEmpty(context.Request.QueryString["UserName"])) - { - userId = GetUserId(context.Request.QueryString["UserName"], portalId); - } - } - - if (userId == Null.NullInteger) - { - // try user - string user = context.Request.QueryString["User"]; - if (!string.IsNullOrEmpty(user)) - { - if (!int.TryParse(user, out userId)) - { - // User is not an integer, so try it as a name - userId = GetUserId(user, portalId); - } - else - { - if (UserController.GetUserById(portalId, userId) == null) - { - // The user cannot be found (potential DOS) - Exceptions.Exceptions.ProcessHttpException(context.Request); - } - } - } - } - - if (userId == Null.NullInteger) - { - // The user cannot be found (potential DOS) - Exceptions.Exceptions.ProcessHttpException(context.Request); - } - } - catch (Exception exc) - { - Logger.Debug(exc); - - // The user cannot be found (potential DOS) - Exceptions.Exceptions.ProcessHttpException(context.Request); - } - - // Redirect to Userprofile Page - context.Response.Redirect(Globals.UserProfileURL(userId), true); - } + /// + /// This handler handles requests for LinkClick.aspx, but only those specific + /// to file serving. + /// + /// System.Web.HttpContext). + public void ProcessRequest(HttpContext context) + { + PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + int userId = Null.NullInteger; + int portalId = portalSettings.PortalId; - private static int GetUserId(string username, int portalId) - { - int userId = Null.NullInteger; - UserInfo userInfo = UserController.GetUserByName(portalId, username); - if (userInfo != null) - { - userId = userInfo.UserID; - } - else - { - // The user cannot be found (potential DOS) - Exceptions.Exceptions.ProcessHttpException(); - } - - return userId; - } - } -} + try + { + // try UserId + if (!string.IsNullOrEmpty(context.Request.QueryString["UserId"])) + { + userId = int.Parse(context.Request.QueryString["UserId"], CultureInfo.InvariantCulture); + if (UserController.GetUserById(portalId, userId) == null) + { + // The user cannot be found (potential DOS) + Exceptions.Exceptions.ProcessHttpException(context.Request); + } + } + + if (userId == Null.NullInteger) + { + // try userName + if (!string.IsNullOrEmpty(context.Request.QueryString["UserName"])) + { + userId = GetUserId(context.Request.QueryString["UserName"], portalId); + } + } + + if (userId == Null.NullInteger) + { + // try user + string user = context.Request.QueryString["User"]; + if (!string.IsNullOrEmpty(user)) + { + if (!int.TryParse(user, out userId)) + { + // User is not an integer, so try it as a name + userId = GetUserId(user, portalId); + } + else + { + if (UserController.GetUserById(portalId, userId) == null) + { + // The user cannot be found (potential DOS) + Exceptions.Exceptions.ProcessHttpException(context.Request); + } + } + } + } + + if (userId == Null.NullInteger) + { + // The user cannot be found (potential DOS) + Exceptions.Exceptions.ProcessHttpException(context.Request); + } + } + catch (Exception exc) + { + Logger.Debug(exc); + + // The user cannot be found (potential DOS) + Exceptions.Exceptions.ProcessHttpException(context.Request); + } + + // Redirect to Userprofile Page + context.Response.Redirect(Globals.UserProfileURL(userId), true); + } + + private static int GetUserId(string username, int portalId) + { + int userId = Null.NullInteger; + UserInfo userInfo = UserController.GetUserByName(portalId, username); + if (userInfo != null) + { + userId = userInfo.UserID; + } + else + { + // The user cannot be found (potential DOS) + Exceptions.Exceptions.ProcessHttpException(); + } + + return userId; + } + } +} diff --git a/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs b/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs index 89a0dd12589..322583ff991 100644 --- a/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs +++ b/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs @@ -51,12 +51,12 @@ public void ProcessRequest(HttpContext context) { if (!string.IsNullOrEmpty(context.Request.QueryString["userid"])) { - userId = Convert.ToInt32(context.Request.QueryString["userid"]); + userId = Convert.ToInt32(context.Request.QueryString["userid"], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(context.Request.QueryString["h"])) { - height = Convert.ToInt32(context.Request.QueryString["h"]); + height = Convert.ToInt32(context.Request.QueryString["h"], CultureInfo.InvariantCulture); } } catch (Exception) @@ -155,7 +155,7 @@ private static bool TryGetPhotoFile(UserInfo targetUser, out IFileInfo photoFile var isVisible = ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, user, targetUser); if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) { - photoFile = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); + photoFile = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue, CultureInfo.InvariantCulture)); if (photoFile == null) { isVisible = false; @@ -203,7 +203,7 @@ private static void CalculateSize(ref int height, out int width, out string size private static bool IsImageExtension(string extension) { - if (!extension.StartsWith(".")) + if (!extension.StartsWith(".", StringComparison.Ordinal)) { extension = $".{extension}"; } diff --git a/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs b/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs index daa2b367f42..06000eb4c18 100644 --- a/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs +++ b/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs @@ -61,7 +61,7 @@ public string GetUserRequestIPAddress(HttpRequestBase request, IPAddressFamily i userIPAddress = userIPAddress.Split(':')[0]; } else if (ipFamily == IPAddressFamily.IPv6 - && userIPAddress.StartsWith("[") && userIPAddress.Contains(']')) + && userIPAddress.StartsWith("[", StringComparison.Ordinal) && userIPAddress.Contains(']')) { userIPAddress = userIPAddress.Split(']')[0].Substring(1); } diff --git a/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs b/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs index aa7e2e2724e..5144760e52f 100644 --- a/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs +++ b/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Services.Users { using System; + using DotNetNuke.Abstractions.Portals; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Services.Scheduling; @@ -23,9 +24,9 @@ public override void DoWork() { try { - foreach (PortalInfo portal in new PortalController().GetPortals()) + foreach (IPortalInfo portal in new PortalController().GetPortals()) { - var settings = new PortalSettings(portal.PortalID); + var settings = new PortalSettings(portal.PortalId); if (settings.DataConsentActive) { if (settings.DataConsentUserDeleteAction == PortalSettings.UserDeleteAction.DelayedHardDelete) @@ -44,13 +45,13 @@ public override void DoWork() break; } - var deletedUsers = UserController.GetDeletedUsers(portal.PortalID); + var deletedUsers = UserController.GetDeletedUsers(portal.PortalId); foreach (UserInfo user in deletedUsers) { if (user.LastModifiedOnDate < thresholdDate && user.RequestsRemoval) { UserController.RemoveUser(user); - this.ScheduleHistoryItem.AddLogNote(string.Format("Removed user {0}{1}", user.Username, Environment.NewLine)); + this.ScheduleHistoryItem.AddLogNote($"Removed user {user.Username}{Environment.NewLine}"); } } } @@ -64,7 +65,7 @@ public override void DoWork() { this.ScheduleHistoryItem.Succeeded = false; // REQUIRED - this.ScheduleHistoryItem.AddLogNote(string.Format("Purging deleted users task failed: {0}.", exc.ToString())); + this.ScheduleHistoryItem.AddLogNote($"Purging deleted users task failed: {exc}."); // notification that we have errored this.Errored(ref exc); // REQUIRED diff --git a/DNN Platform/Library/UI/Containers/ActionBase.cs b/DNN Platform/Library/UI/Containers/ActionBase.cs index 60ffa412c8b..50948cb88b6 100644 --- a/DNN Platform/Library/UI/Containers/ActionBase.cs +++ b/DNN Platform/Library/UI/Containers/ActionBase.cs @@ -23,14 +23,9 @@ public abstract class ActionBase : UserControl, IActionControl { /// Defines if the action supports icons. [Obsolete("Deprecated in DotNetNuke 9.8.1. Use SupportsIcons property. Scheduled for removal in v11.0.0.")] - [System.Diagnostics.CodeAnalysis.SuppressMessage( - "StyleCop.CSharp.NamingRules", - "SA1308:Variable names should not be prefixed", - Justification = "Keeping the name to prevent a breaking change, will be removed in v11.")] - [System.Diagnostics.CodeAnalysis.SuppressMessage( - "StyleCop.CSharp.MaintainabilityRules", - "SA1401:Fields should be private", - Justification = "In v11, we will make this private and rename.")] + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1308:Variable names should not be prefixed", Justification = "Keeping the name to prevent a breaking change, will be removed in v11.")] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "In v11, we will make this private and rename.")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected bool m_supportsIcons = true; private ActionManager actionManager; diff --git a/DNN Platform/Library/UI/Containers/ActionButton.cs b/DNN Platform/Library/UI/Containers/ActionButton.cs index 2c4e9695cd0..f65b26542bd 100644 --- a/DNN Platform/Library/UI/Containers/ActionButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionButton.cs @@ -3,6 +3,8 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { + using System.Globalization; + using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.Internal.SourceGenerators; @@ -149,7 +151,7 @@ protected override void CreateChildControls() /// Action_Click responds to an Action Event in the contained actionButtonList. private void Action_Click(object sender, ActionEventArgs e) { - this.ProcessAction(e.Action.ID.ToString()); + this.ProcessAction(e.Action.ID.ToString(CultureInfo.InvariantCulture)); } } } diff --git a/DNN Platform/Library/UI/Containers/ActionCommandButton.cs b/DNN Platform/Library/UI/Containers/ActionCommandButton.cs index a396bcef8a2..d21c27af92c 100644 --- a/DNN Platform/Library/UI/Containers/ActionCommandButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionCommandButton.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.Containers { using System; + using System.Globalization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules.Actions; @@ -102,17 +103,17 @@ protected override void OnPreRender(EventArgs e) if (this.ModuleAction != null && this.ActionManager.IsVisible(this.ModuleAction)) { this.Text = this.ModuleAction.Title; - this.CommandArgument = this.ModuleAction.ID.ToString(); + this.CommandArgument = this.ModuleAction.ID.ToString(CultureInfo.InvariantCulture); if (this.DisplayIcon && (!string.IsNullOrEmpty(this.ModuleAction.Icon) || !string.IsNullOrEmpty(this.ImageUrl))) { if (!string.IsNullOrEmpty(this.ImageUrl)) { - this.ImageUrl = this.ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1) + this.ImageUrl; + this.ImageUrl = this.ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/", StringComparison.Ordinal) + 1) + this.ImageUrl; } else { - if (this.ModuleAction.Icon.IndexOf("/") > Null.NullInteger) + if (this.ModuleAction.Icon.IndexOf("/", StringComparison.Ordinal) > Null.NullInteger) { this.ImageUrl = this.ModuleAction.Icon; } diff --git a/DNN Platform/Library/UI/Containers/ActionManager.cs b/DNN Platform/Library/UI/Containers/ActionManager.cs index 9989cd91cb2..006e0362409 100644 --- a/DNN Platform/Library/UI/Containers/ActionManager.cs +++ b/DNN Platform/Library/UI/Containers/ActionManager.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.Containers { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web; using System.Web.UI.WebControls; @@ -109,8 +110,7 @@ public void GetClientScriptURL(ModuleAction action, WebControl control) script = script.Substring(jSPos + 11); } - string formatScript = "javascript: return {0};"; - control.Attributes.Add("onClick", string.Format(formatScript, script)); + control.Attributes.Add("onClick", $"javascript: return {script};"); } } @@ -119,7 +119,7 @@ public void GetClientScriptURL(ModuleAction action, WebControl control) /// if the action is visible, otherwise . public bool IsVisible(ModuleAction action) { - bool isVisible = false; + bool isVisible; if (action.Visible && ModulePermissionController.HasModuleAccess(action.Secure, Null.NullString, this.ModuleContext.Configuration)) { if ((Personalization.GetUserMode() == PortalSettings.Mode.Edit) || (action.Secure == SecurityAccessLevel.Anonymous || action.Secure == SecurityAccessLevel.View)) @@ -140,15 +140,15 @@ public bool IsVisible(ModuleAction action) } /// ProcessAction processes the action. - /// The Id of the Action. + /// The ID of the Action. /// if the action was processed, otherwise (if it's a custom action that can't be found). public bool ProcessAction(string id) { bool bProcessed = true; - int nid = 0; - if (int.TryParse(id, out nid)) + int actionId; + if (int.TryParse(id, out actionId)) { - bProcessed = this.ProcessAction(this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByID(nid)); + bProcessed = this.ProcessAction(this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByID(actionId)); } return bProcessed; @@ -229,7 +229,7 @@ private void ClearCache(ModuleAction command) private void Delete(ModuleAction command) { - var module = ModuleController.Instance.GetModule(int.Parse(command.CommandArgument), this.ModuleContext.TabId, true); + var module = ModuleController.Instance.GetModule(int.Parse(command.CommandArgument, CultureInfo.InvariantCulture), this.ModuleContext.TabId, true); // Check if this is the owner instance of a shared module. var user = UserController.Instance.GetCurrentUserInfo(); @@ -246,7 +246,7 @@ private void Delete(ModuleAction command) } } - ModuleController.Instance.DeleteTabModule(this.ModuleContext.TabId, int.Parse(command.CommandArgument), true); + ModuleController.Instance.DeleteTabModule(this.ModuleContext.TabId, int.Parse(command.CommandArgument, CultureInfo.InvariantCulture), true); EventLogController.Instance.AddLog(module, this.portalSettings, user.UserID, string.Empty, EventLogController.EventLogType.MODULE_SENT_TO_RECYCLE_BIN); // Redirect to the same page to pick up changes diff --git a/DNN Platform/Library/UI/Containers/ActionsMenu.cs b/DNN Platform/Library/UI/Containers/ActionsMenu.cs index 62001fd4790..212bcd4d99e 100644 --- a/DNN Platform/Library/UI/Containers/ActionsMenu.cs +++ b/DNN Platform/Library/UI/Containers/ActionsMenu.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.Containers { using System; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common; @@ -198,13 +199,14 @@ private void BindMenu(DNNNodeCollection objNodes) } } - /// ProcessNodes proceses a single node and its children. + /// ProcessNodes processes a single node and its children. /// The Node to process. private void ProcessNodes(DNNNode objParent) { if (!string.IsNullOrEmpty(objParent.JSFunction)) { - objParent.JSFunction = string.Format("if({0}){{{1}}};", objParent.JSFunction, this.Page.ClientScript.GetPostBackEventReference(this.ProviderControl.NavigationControl, objParent.ID)); + var postBackEventReference = this.Page.ClientScript.GetPostBackEventReference(this.ProviderControl.NavigationControl, objParent.ID); + objParent.JSFunction = $"if({objParent.JSFunction}){{{postBackEventReference}}};"; } foreach (DNNNode objNode in objParent.DNNNodes) @@ -253,7 +255,7 @@ private void MenuItem_Click(NavigationEventArgs args) { if (Globals.NumberMatchRegex.IsMatch(args.ID)) { - ModuleAction action = this.ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID)); + var action = this.ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID, CultureInfo.InvariantCulture)); if (!this.ActionManager.ProcessAction(action)) { this.OnAction(new ActionEventArgs(action, this.ModuleControl.ModuleContext.Configuration)); @@ -267,10 +269,10 @@ private void ProviderControl_PopulateOnDemand(NavigationEventArgs args) this.SetMenuDefaults(); this.ActionRoot.Actions.AddRange(this.ModuleControl.ModuleContext.Actions); // Modules how add custom actions in control lifecycle will not have those actions populated... - ModuleAction objAction = this.ActionRoot; - if (this.ActionRoot.ID != Convert.ToInt32(args.ID)) + var objAction = this.ActionRoot; + if (this.ActionRoot.ID != Convert.ToInt32(args.ID, CultureInfo.InvariantCulture)) { - objAction = this.ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID)); + objAction = this.ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID, CultureInfo.InvariantCulture)); } if (args.Node == null) diff --git a/DNN Platform/Library/UI/Containers/Container.cs b/DNN Platform/Library/UI/Containers/Container.cs index 8ecbb75370a..56731540f03 100644 --- a/DNN Platform/Library/UI/Containers/Container.cs +++ b/DNN Platform/Library/UI/Containers/Container.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.Containers { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Web.UI; using System.Web.UI.HtmlControls; @@ -146,7 +147,7 @@ protected override void OnUnload(EventArgs e) private void AddAdministratorOnlyHighlighting(string message) { - this.ContentPane.Controls.Add(new LiteralControl(string.Format("
    {0}
    ", message))); + this.ContentPane.Controls.Add(new LiteralControl($"
    {message}
    ")); } /// @@ -157,28 +158,23 @@ private void AddAdministratorOnlyHighlighting(string message) /// private void ProcessChildControls(Control control) { - IActionControl actions; - ISkinControl skinControl; foreach (Control childControl in control.Controls) { // check if control is an action control - actions = childControl as IActionControl; - if (actions != null) + if (childControl is IActionControl actions) { actions.ModuleControl = this.ModuleControl; actions.Action += this.ModuleActionClick; } // check if control is an actionLink control - var actionLink = childControl as ActionLink; - if (actionLink != null) + if (childControl is ActionLink actionLink) { actionLink.ModuleControl = this.ModuleControl; } // check if control is a skin control - skinControl = childControl as ISkinControl; - if (skinControl != null) + if (childControl is ISkinControl skinControl) { skinControl.ModuleControl = this.ModuleControl; } @@ -191,10 +187,7 @@ private void ProcessChildControls(Control control) } } - /// - /// ProcessContentPane processes the ContentPane, setting its style and other - /// attributes. - /// + /// ProcessContentPane processes the ContentPane, setting its style and other attributes. private void ProcessContentPane() { this.SetAlignment(); @@ -228,13 +221,13 @@ private void ProcessContentPane() if (this.ModuleConfiguration.StartDate >= DateTime.Now) { - adminMessage = string.Format(Localization.GetString("ModuleEffective.Text"), this.ModuleConfiguration.StartDate); + adminMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString("ModuleEffective.Text"), this.ModuleConfiguration.StartDate); showMessage = !Globals.IsAdminControl(); } if (this.ModuleConfiguration.EndDate <= DateTime.Now) { - adminMessage = string.Format(Localization.GetString("ModuleExpired.Text"), this.ModuleConfiguration.EndDate); + adminMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString("ModuleExpired.Text"), this.ModuleConfiguration.EndDate); showMessage = !Globals.IsAdminControl(); } @@ -348,15 +341,15 @@ private void ProcessStylesheets(bool includeModuleCss) string folderName = this.ModuleConfiguration.DesktopModule.FolderName; string stylesheet = string.Empty; - if (string.IsNullOrEmpty(folderName) == false) + if (!string.IsNullOrEmpty(folderName)) { - if (controlSrc.EndsWith(".mvc")) + if (controlSrc.EndsWith(".mvc", StringComparison.OrdinalIgnoreCase)) { - stylesheet = Globals.ApplicationPath + "/DesktopModules/MVC/" + folderName.Replace("\\", "/") + "/module.css"; + stylesheet = $"{Globals.ApplicationPath}/DesktopModules/MVC/{folderName.Replace(@"\", "/")}/module.css"; } else { - stylesheet = Globals.ApplicationPath + "/DesktopModules/" + folderName.Replace("\\", "/") + "/module.css"; + stylesheet = $"{Globals.ApplicationPath}/DesktopModules/{folderName.Replace(@"\", "/")}/module.css"; } this.clientResourceController.RegisterStylesheet(stylesheet, FileOrder.Css.ModuleCss, true); @@ -365,7 +358,7 @@ private void ProcessStylesheets(bool includeModuleCss) var ix = controlSrc.LastIndexOf("/", StringComparison.Ordinal); if (ix >= 0) { - stylesheet = Globals.ApplicationPath + "/" + controlSrc.Substring(0, ix + 1) + "module.css"; + stylesheet = $"{Globals.ApplicationPath}/{controlSrc.Substring(0, ix + 1)}module.css"; this.clientResourceController.RegisterStylesheet(stylesheet, FileOrder.Css.ModuleCss, true); } } @@ -398,10 +391,10 @@ private void SetBorder() { if (!string.IsNullOrEmpty(this.ModuleConfiguration.Border)) { - this.ContentPane.Style["border-top"] = string.Format("{0}px #000000 solid", this.ModuleConfiguration.Border); - this.ContentPane.Style["border-bottom"] = string.Format("{0}px #000000 solid", this.ModuleConfiguration.Border); - this.ContentPane.Style["border-right"] = string.Format("{0}px #000000 solid", this.ModuleConfiguration.Border); - this.ContentPane.Style["border-left"] = string.Format("{0}px #000000 solid", this.ModuleConfiguration.Border); + this.ContentPane.Style["border-top"] = string.Format(CultureInfo.InvariantCulture, "{0}px #000000 solid", this.ModuleConfiguration.Border); + this.ContentPane.Style["border-bottom"] = string.Format(CultureInfo.InvariantCulture, "{0}px #000000 solid", this.ModuleConfiguration.Border); + this.ContentPane.Style["border-right"] = string.Format(CultureInfo.InvariantCulture, "{0}px #000000 solid", this.ModuleConfiguration.Border); + this.ContentPane.Style["border-left"] = string.Format(CultureInfo.InvariantCulture, "{0}px #000000 solid", this.ModuleConfiguration.Border); } } diff --git a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventHandler.cs b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventHandler.cs index 53f83af8525..8404324ae84 100644 --- a/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventHandler.cs +++ b/DNN Platform/Library/UI/Containers/EventListeners/ContainerEventHandler.cs @@ -2,10 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.Containers.EventListeners -{ - /// The ContainerEventHandler delegate defines a custom event handler for a Container Event. - /// The event sender. - /// The event arguments. - public delegate void ContainerEventHandler(object sender, ContainerEventArgs e); -} +namespace DotNetNuke.UI.Containers.EventListeners; + +using System.Diagnostics.CodeAnalysis; + +/// The ContainerEventHandler delegate defines a custom event handler for a Container Event. +/// The event sender. +/// The event arguments. +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] +public delegate void ContainerEventHandler(object sender, ContainerEventArgs e); diff --git a/DNN Platform/Library/UI/FavIcon.cs b/DNN Platform/Library/UI/FavIcon.cs index 70327d0df4a..b01f859940e 100644 --- a/DNN Platform/Library/UI/FavIcon.cs +++ b/DNN Platform/Library/UI/FavIcon.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.Internals { + using System.Globalization; using System.Net; using DotNetNuke.Abstractions.Application; @@ -75,7 +76,8 @@ public string GetSettingPath() /// The file id or Null.NullInteger for none. public void Update(int fileId) { - PortalController.UpdatePortalSetting(this.portalId, SettingName, fileId != Null.NullInteger ? string.Format("FileID={0}", fileId) : string.Empty, /*clearCache*/ true); + var settingValue = fileId != Null.NullInteger ? string.Format(CultureInfo.InvariantCulture, "FileID={0}", fileId) : string.Empty; + PortalController.UpdatePortalSetting(this.portalId, SettingName, settingValue, clearCache: true); DataCache.ClearCache(GetCacheKey(this.portalId)); } diff --git a/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs b/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs index ec02283e343..0f28f46d9ce 100644 --- a/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs +++ b/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.Modules.Html5 { using System; + using System.Globalization; using System.IO; using System.Web; using System.Web.UI; @@ -92,15 +93,13 @@ protected override void OnPreRender(EventArgs e) private static string GetFileContentInternal(string filepath) { - using (var reader = new StreamReader(filepath)) - { - return reader.ReadToEnd(); - } + using var reader = new StreamReader(filepath); + return reader.ReadToEnd(); } private string GetFileContent(string filepath) { - var cacheKey = string.Format(DataCache.SpaModulesContentHtmlFileCacheKey, filepath); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.SpaModulesContentHtmlFileCacheKey, filepath); var absoluteFilePath = this.Page.Server.MapPath(filepath); var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.SpaModulesHtmlFileTimeOut, DataCache.SpaModulesHtmlFileCachePriority) { @@ -111,7 +110,7 @@ private string GetFileContent(string filepath) private bool FileExists(string filepath) { - var cacheKey = string.Format(DataCache.SpaModulesFileExistsCacheKey, filepath); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.SpaModulesFileExistsCacheKey, filepath); return CBO.GetCachedObject( new CacheItemArgs( cacheKey, diff --git a/DNN Platform/Library/UI/Modules/Html5/ModuleActionsPropertyAccess.cs b/DNN Platform/Library/UI/Modules/Html5/ModuleActionsPropertyAccess.cs index 0dd593044f8..a6afebf473f 100644 --- a/DNN Platform/Library/UI/Modules/Html5/ModuleActionsPropertyAccess.cs +++ b/DNN Platform/Library/UI/Modules/Html5/ModuleActionsPropertyAccess.cs @@ -66,9 +66,10 @@ protected override string ProcessToken(ModuleActionDto model, UserInfo accessing } else { - moduleAction.Url = model.Script.StartsWith("javascript:", StringComparison.InvariantCultureIgnoreCase) ? - model.Script : - string.Format("javascript:{0}", model.Script); + moduleAction.Url = + model.Script.StartsWith("javascript:", StringComparison.OrdinalIgnoreCase) + ? model.Script + : $"javascript:{model.Script}"; } this.moduleActions.Add(moduleAction); diff --git a/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs b/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs index 8ea07281d92..6b3f14a6c75 100644 --- a/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs +++ b/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs @@ -33,17 +33,17 @@ public string GetProperty(string propertyName, string format, CultureInfo format switch (propertyName.ToLowerInvariant()) { case "moduleid": - return this.moduleContext.ModuleId.ToString(); + return this.moduleContext.ModuleId.ToString(formatProvider); case "tabmoduleid": - return this.moduleContext.TabModuleId.ToString(); + return this.moduleContext.TabModuleId.ToString(formatProvider); case "tabid": - return this.moduleContext.TabId.ToString(); + return this.moduleContext.TabId.ToString(formatProvider); case "portalid": - return this.moduleContext.Configuration.OwnerPortalID.ToString(); + return this.moduleContext.Configuration.OwnerPortalID.ToString(formatProvider); case "issuperuser": - return this.moduleContext.PortalSettings.UserInfo.IsSuperUser.ToString(); + return this.moduleContext.PortalSettings.UserInfo.IsSuperUser.ToString(formatProvider); case "editmode": - return this.moduleContext.EditMode.ToString(); + return this.moduleContext.EditMode.ToString(formatProvider); default: if (this.moduleContext.Settings.ContainsKey(propertyName)) { diff --git a/DNN Platform/Library/UI/Modules/Html5/RequestPropertyAccess.cs b/DNN Platform/Library/UI/Modules/Html5/RequestPropertyAccess.cs index bb136ac8bb5..27ecbe3f5b2 100644 --- a/DNN Platform/Library/UI/Modules/Html5/RequestPropertyAccess.cs +++ b/DNN Platform/Library/UI/Modules/Html5/RequestPropertyAccess.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.Modules.Html5 { + using System; using System.Globalization; using System.Web; @@ -39,7 +40,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format return this.request.ApplicationPath; case "relativeapppath": // RelativeAppPath is like ApplicationPath, but will always end with a forward slash (/) - return this.request.ApplicationPath.EndsWith("/") + return this.request.ApplicationPath.EndsWith("/", StringComparison.Ordinal) ? this.request.ApplicationPath : $"{this.request.ApplicationPath}/"; } diff --git a/DNN Platform/Library/UI/Modules/IModuleInjectionFilter.cs b/DNN Platform/Library/UI/Modules/IModuleInjectionFilter.cs index f1aee9de5b8..9d1079ae83a 100644 --- a/DNN Platform/Library/UI/Modules/IModuleInjectionFilter.cs +++ b/DNN Platform/Library/UI/Modules/IModuleInjectionFilter.cs @@ -3,6 +3,8 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Modules { + using System.Diagnostics.CodeAnalysis; + using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; @@ -13,6 +15,7 @@ public interface IModuleInjectionFilter /// The module to be injected. /// The portal settings. /// if the module can be injected, otherwise . + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Breaking change")] bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings); } } diff --git a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs index 231afccacee..e6f8c12cb0e 100644 --- a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs @@ -164,11 +164,7 @@ public static partial Control CreateModuleControl(ModuleInfo moduleConfiguration case ".mvc": var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); - moduleControl.LocalResourceFile = string.Format( - "~/DesktopModules/MVC/{0}/{1}/{2}.resx", - moduleConfiguration.DesktopModule.FolderName, - Localization.LocalResourceDirectory, - segments[0]); + moduleControl.LocalResourceFile = $"~/DesktopModules/MVC/{moduleConfiguration.DesktopModule.FolderName}/{Localization.LocalResourceDirectory}/{segments[0]}.resx"; break; default: moduleControl.LocalResourceFile = moduleConfiguration.ModuleControl.ControlSrc.Replace(Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc), string.Empty) + diff --git a/DNN Platform/Library/UI/Modules/ModuleHost.cs b/DNN Platform/Library/UI/Modules/ModuleHost.cs index 28fbfeccebd..25151a3b36e 100644 --- a/DNN Platform/Library/UI/Modules/ModuleHost.cs +++ b/DNN Platform/Library/UI/Modules/ModuleHost.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.Modules using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; @@ -149,7 +150,7 @@ protected override void OnPreRender(EventArgs e) moduleName = Globals.CleanName(moduleName); } - this.Attributes.Add("class", string.Format("DNNModuleContent Mod{0}C", moduleName)); + this.Attributes.Add("class", $"DNNModuleContent Mod{moduleName}C"); } } @@ -430,7 +431,7 @@ private void RestoreCachedClientResourceRegistrations(string cachedContent) if (match.Groups["priority"].Success) { - priority = Convert.ToInt32(match.Groups["priority"].Value); + priority = Convert.ToInt32(match.Groups["priority"].Value, CultureInfo.InvariantCulture); } switch (dependencyType) diff --git a/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs b/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs index 60324cec365..8ba102d095e 100644 --- a/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs +++ b/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.Modules using System; using System.Collections; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web; using System.Web.UI; @@ -244,7 +245,7 @@ public string EditUrl(string keyName, string keyValue, string controlKey, params string moduleIdParam = string.Empty; if (this.Configuration != null) { - moduleIdParam = string.Format("mid={0}", this.Configuration.ModuleID); + moduleIdParam = $"mid={this.Configuration.ModuleID}"; } string[] parameters; @@ -252,7 +253,7 @@ public string EditUrl(string keyName, string keyValue, string controlKey, params { parameters = new string[2 + additionalParameters.Length]; parameters[0] = moduleIdParam; - parameters[1] = string.Format("{0}={1}", keyName, keyValue); + parameters[1] = $"{keyName}={keyValue}"; Array.Copy(additionalParameters, 0, parameters, 2, additionalParameters.Length); } else @@ -685,7 +686,7 @@ private void LoadActions(HttpRequest request) this.GetNextActionID(), Localization.GetString(ModuleActionType.DeleteModule, Localization.GlobalResourceFile), ModuleActionType.DeleteModule, - this.Configuration.ModuleID.ToString(), + this.Configuration.ModuleID.ToString(CultureInfo.InvariantCulture), "action_delete.gif", string.Empty, confirmText, @@ -701,7 +702,7 @@ private void LoadActions(HttpRequest request) this.GetNextActionID(), Localization.GetString(ModuleActionType.ClearCache, Localization.GlobalResourceFile), ModuleActionType.ClearCache, - this.Configuration.ModuleID.ToString(), + this.Configuration.ModuleID.ToString(CultureInfo.InvariantCulture), "action_refresh.gif", string.Empty, false, diff --git a/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs b/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs index 3276e417116..630bd6376ed 100644 --- a/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs @@ -33,7 +33,7 @@ public int ProfileUserId { if (!string.IsNullOrEmpty(this.Request.Params["UserId"])) { - return int.Parse(this.Request.Params["UserId"]); + return int.Parse(this.Request.Params["UserId"], CultureInfo.InvariantCulture); } return UserController.Instance.GetCurrentUserInfo().UserID; diff --git a/DNN Platform/Library/UI/Navigation.cs b/DNN Platform/Library/UI/Navigation.cs index 29881b10fc8..c1778da2ac0 100644 --- a/DNN Platform/Library/UI/Navigation.cs +++ b/DNN Platform/Library/UI/Navigation.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common.Utilities; @@ -110,15 +111,14 @@ public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, Contr { var objCol = new DNNNodeCollection(objControl.ClientID); - var objActionControl = objControl as IActionControl; - if (objActionControl != null) + if (objControl is IActionControl objActionControl) { if (objActionRoot.Visible) { objCol.Add(); DNNNode objRoot = objCol[0]; - objRoot.ID = objActionRoot.ID.ToString(); - objRoot.Key = objActionRoot.ID.ToString(); + objRoot.ID = objActionRoot.ID.ToString(CultureInfo.InvariantCulture); + objRoot.Key = objActionRoot.ID.ToString(CultureInfo.InvariantCulture); objRoot.Text = objActionRoot.Title; objRoot.NavigateURL = objActionRoot.Url; objRoot.Image = objActionRoot.Icon; @@ -289,8 +289,8 @@ private static void AddChildActions(ModuleAction parentAction, DNNNode parentNod { int i = parentNode.DNNNodes.Add(); DNNNode node = parentNode.DNNNodes[i]; - node.ID = action.ID.ToString(); - node.Key = action.ID.ToString(); + node.ID = action.ID.ToString(CultureInfo.InvariantCulture); + node.Key = action.ID.ToString(CultureInfo.InvariantCulture); node.Text = action.Title; // no longer including SPACE in generic node collection, each control must handle how they want to display if (string.IsNullOrEmpty(action.ClientScript) && string.IsNullOrEmpty(action.Url) && string.IsNullOrEmpty(action.CommandArgument)) { @@ -364,7 +364,7 @@ private static void AddNode(TabInfo objTab, DNNNodeCollection objNodes, Hashtabl objNode.Enabled = false; } - objNode.ID = objTab.TabID.ToString(); + objNode.ID = objTab.TabID.ToString(CultureInfo.InvariantCulture); objNode.Key = objNode.ID; objNode.Text = objTab.LocalizedTabName; objNode.NavigateURL = objTab.FullUrl; @@ -505,15 +505,13 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob // based off of tab properties, is it shown if (CanShowTab(objTab, TabPermissionController.CanAdminPage(), true, showHidden)) { - DNNNodeCollection objParentNodes; - DNNNode objParentNode; - bool blnParentFound = nodesLookup.TryGetValue(objTab.ParentId.ToString(), out objParentNode); + bool blnParentFound = nodesLookup.TryGetValue(objTab.ParentId.ToString(CultureInfo.InvariantCulture), out var objParentNode); if (!blnParentFound) { objParentNode = objRootNode; } - objParentNodes = objParentNode.DNNNodes; + var objParentNodes = objParentNode.DNNNodes; if (objTab.TabID == intStartTabId) { // is this the starting tab @@ -523,7 +521,7 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob if (objTabLookup[objTab.ParentId] != null) { AddNode((TabInfo)objTabLookup[objTab.ParentId], objParentNodes, objBreadCrumbs, objPortalSettings, eToolTips, nodesLookup); - if (nodesLookup.TryGetValue(objTab.ParentId.ToString(), out objParentNode)) + if (nodesLookup.TryGetValue(objTab.ParentId.ToString(CultureInfo.InvariantCulture), out objParentNode)) { objParentNodes = objParentNode.DNNNodes; } diff --git a/DNN Platform/Library/UI/Skins/Controls/LanguagePropertyAccess.cs b/DNN Platform/Library/UI/Skins/Controls/LanguagePropertyAccess.cs index c6472de1b41..d60195549d6 100644 --- a/DNN Platform/Library/UI/Skins/Controls/LanguagePropertyAccess.cs +++ b/DNN Platform/Library/UI/Skins/Controls/LanguagePropertyAccess.cs @@ -26,6 +26,7 @@ public class LanguagePropertyAccess : IPropertyAccess { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming public LanguageTokenReplace objParent; @@ -53,6 +54,7 @@ public CacheLevel Cacheability } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { switch (propertyName.ToLowerInvariant()) @@ -249,7 +251,7 @@ private string NewUrl(string newLanguage) break; case TabType.Tab: // alternate tab url - fullurl = TestableGlobals.Instance.NavigateURL(Convert.ToInt32(localizedTab.Url)); + fullurl = TestableGlobals.Instance.NavigateURL(Convert.ToInt32(localizedTab.Url, CultureInfo.InvariantCulture)); break; case TabType.File: // file url diff --git a/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs b/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs index 97d2e03a47c..fc5987d9dc3 100644 --- a/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs +++ b/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs @@ -14,12 +14,16 @@ namespace DotNetNuke.UI.Skins.Controls public class ModuleMessage : SkinObjectBase { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel dnnSkinMessage; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblHeading; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblMessage; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Control scrollScript; public enum ModuleMessageType diff --git a/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs b/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs index b08296083b8..0a5732c8462 100644 --- a/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs +++ b/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.Skins.Controls using System; using System.Collections.Generic; using System.Collections.Specialized; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common.Utilities; @@ -137,7 +138,7 @@ public void RaisePostBackEvent(string eventArgument) args = new PropertyEditorEventArgs(this.Name); args.Value = this.DictionaryValue; args.OldValue = this.OldDictionaryValue; - args.Key = int.Parse(eventArgument.Substring(7)); + args.Key = int.Parse(eventArgument.Substring(7), CultureInfo.InvariantCulture); args.Changed = true; this.OnItemDeleted(args); break; @@ -247,7 +248,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.AddAttribute(HtmlTextWriterAttribute.Value, kvp.Value); if (length > Null.NullInteger) { - writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString(CultureInfo.InvariantCulture)); } writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + "_skin" + kvp.Key); @@ -281,7 +282,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); if (length > Null.NullInteger) { - writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString(CultureInfo.InvariantCulture)); } writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + "_skinnew"); diff --git a/DNN Platform/Library/UI/Skins/CustomAttribute.cs b/DNN Platform/Library/UI/Skins/CustomAttribute.cs index a8083e36598..950f780e047 100644 --- a/DNN Platform/Library/UI/Skins/CustomAttribute.cs +++ b/DNN Platform/Library/UI/Skins/CustomAttribute.cs @@ -1,15 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.Skins -{ - using System.Diagnostics.CodeAnalysis; +namespace DotNetNuke.UI.Skins; + +using System.Diagnostics.CodeAnalysis; - public class CustomAttribute - { - [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] - public string Name; - [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] - public string Value; - } +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] +public class CustomAttribute +{ + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] + public string Name; + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] + public string Value; } diff --git a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventHandler.cs b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventHandler.cs index 907148fb8e7..7b8db5a16e4 100644 --- a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventHandler.cs +++ b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventHandler.cs @@ -2,10 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.Skins.EventListeners -{ - /// The SkinEventHandler delegate defines a custom event handler for a Skin Event. - /// The event sender. - /// The event arguments. - public delegate void SkinEventHandler(object sender, SkinEventArgs e); -} +namespace DotNetNuke.UI.Skins.EventListeners; + +using System.Diagnostics.CodeAnalysis; + +/// The SkinEventHandler delegate defines a custom event handler for a Skin Event. +/// The event sender. +/// The event arguments. +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] +public delegate void SkinEventHandler(object sender, SkinEventArgs e); diff --git a/DNN Platform/Library/UI/Skins/NavObjectBase.cs b/DNN Platform/Library/UI/Skins/NavObjectBase.cs index e9d5befdd43..ba70a865cf0 100644 --- a/DNN Platform/Library/UI/Skins/NavObjectBase.cs +++ b/DNN Platform/Library/UI/Skins/NavObjectBase.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.UI.Skins using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common; @@ -483,7 +484,7 @@ public string MouseOutHideDelay } else { - return this.Control.MouseOutHideDelay.ToString(); + return this.Control.MouseOutHideDelay.ToString(CultureInfo.InvariantCulture); } } @@ -495,7 +496,7 @@ public string MouseOutHideDelay } else { - this.Control.MouseOutHideDelay = Convert.ToDecimal(value); + this.Control.MouseOutHideDelay = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } } } @@ -1976,7 +1977,7 @@ public string StyleControlHeight } else { - return this.Control.StyleControlHeight.ToString(); + return this.Control.StyleControlHeight.ToString(CultureInfo.InvariantCulture); } } @@ -1988,7 +1989,7 @@ public string StyleControlHeight } else { - this.Control.StyleControlHeight = Convert.ToDecimal(value); + this.Control.StyleControlHeight = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } } } @@ -2003,7 +2004,7 @@ public string StyleBorderWidth } else { - return this.Control.StyleBorderWidth.ToString(); + return this.Control.StyleBorderWidth.ToString(CultureInfo.InvariantCulture); } } @@ -2015,7 +2016,7 @@ public string StyleBorderWidth } else { - this.Control.StyleBorderWidth = Convert.ToDecimal(value); + this.Control.StyleBorderWidth = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } } } @@ -2030,7 +2031,7 @@ public string StyleNodeHeight } else { - return this.Control.StyleNodeHeight.ToString(); + return this.Control.StyleNodeHeight.ToString(CultureInfo.InvariantCulture); } } @@ -2042,7 +2043,7 @@ public string StyleNodeHeight } else { - this.Control.StyleNodeHeight = Convert.ToDecimal(value); + this.Control.StyleNodeHeight = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } } } @@ -2057,7 +2058,7 @@ public string StyleIconWidth } else { - return this.Control.StyleIconWidth.ToString(); + return this.Control.StyleIconWidth.ToString(CultureInfo.InvariantCulture); } } @@ -2069,7 +2070,7 @@ public string StyleIconWidth } else { - this.Control.StyleIconWidth = Convert.ToDecimal(value); + this.Control.StyleIconWidth = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } } } @@ -2111,7 +2112,7 @@ public string StyleFontSize } else { - return this.Control.StyleFontSize.ToString(); + return this.Control.StyleFontSize.ToString(CultureInfo.InvariantCulture); } } @@ -2123,7 +2124,7 @@ public string StyleFontSize } else { - this.Control.StyleFontSize = Convert.ToDecimal(value); + this.Control.StyleFontSize = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } } } @@ -2219,7 +2220,7 @@ public string EffectsShadowStrength } else { - return this.Control.EffectsShadowStrength.ToString(); + return this.Control.EffectsShadowStrength.ToString(CultureInfo.InvariantCulture); } } @@ -2231,7 +2232,7 @@ public string EffectsShadowStrength } else { - this.Control.EffectsShadowStrength = Convert.ToInt32(value); + this.Control.EffectsShadowStrength = Convert.ToInt32(value, CultureInfo.InvariantCulture); } } } @@ -2273,7 +2274,7 @@ public string EffectsDuration } else { - return this.Control.EffectsDuration.ToString(); + return this.Control.EffectsDuration.ToString(CultureInfo.InvariantCulture); } } @@ -2285,7 +2286,7 @@ public string EffectsDuration } else { - this.Control.EffectsDuration = Convert.ToDouble(value); + this.Control.EffectsDuration = Convert.ToDouble(value, CultureInfo.InvariantCulture); } } } @@ -2386,7 +2387,7 @@ public DNNNodeCollection GetNavigationNodes(DNNNode objNode) if (objNode != null) { - intRootParent = Convert.ToInt32(objNode.ID); + intRootParent = Convert.ToInt32(objNode.ID, CultureInfo.InvariantCulture); intNavNodeOptions = (int)Navigation.NavNodeOptions.MarkPendingNodes; objNodes = Navigation.GetNavigationNodes(objNode, eToolTips, intRootParent, intDepth, intNavNodeOptions); } @@ -2488,7 +2489,7 @@ private void AssignControlProperties() this.Control.ForceDownLevel = this.GetValue(this.strForceDownLevel, "False"); if (!string.IsNullOrEmpty(this.strMouseOutHideDelay)) { - this.Control.MouseOutHideDelay = Convert.ToDecimal(this.strMouseOutHideDelay); + this.Control.MouseOutHideDelay = Convert.ToDecimal(this.strMouseOutHideDelay, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(this.strMouseOverDisplay)) @@ -2764,22 +2765,22 @@ private void AssignControlProperties() if (!string.IsNullOrEmpty(this.strStyleControlHeight)) { - this.Control.StyleControlHeight = Convert.ToDecimal(this.strStyleControlHeight); + this.Control.StyleControlHeight = Convert.ToDecimal(this.strStyleControlHeight, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(this.strStyleBorderWidth)) { - this.Control.StyleBorderWidth = Convert.ToDecimal(this.strStyleBorderWidth); + this.Control.StyleBorderWidth = Convert.ToDecimal(this.strStyleBorderWidth, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(this.strStyleNodeHeight)) { - this.Control.StyleNodeHeight = Convert.ToDecimal(this.strStyleNodeHeight); + this.Control.StyleNodeHeight = Convert.ToDecimal(this.strStyleNodeHeight, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(this.strStyleIconWidth)) { - this.Control.StyleIconWidth = Convert.ToDecimal(this.strStyleIconWidth); + this.Control.StyleIconWidth = Convert.ToDecimal(this.strStyleIconWidth, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(this.strStyleFontNames)) @@ -2789,7 +2790,7 @@ private void AssignControlProperties() if (!string.IsNullOrEmpty(this.strStyleFontSize)) { - this.Control.StyleFontSize = Convert.ToDecimal(this.strStyleFontSize); + this.Control.StyleFontSize = Convert.ToDecimal(this.strStyleFontSize, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(this.strStyleFontBold)) @@ -2809,7 +2810,7 @@ private void AssignControlProperties() if (!string.IsNullOrEmpty(this.strEffectsShadowStrength)) { - this.Control.EffectsShadowStrength = Convert.ToInt32(this.strEffectsShadowStrength); + this.Control.EffectsShadowStrength = Convert.ToInt32(this.strEffectsShadowStrength, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(this.strEffectsTransition)) @@ -2819,7 +2820,7 @@ private void AssignControlProperties() if (!string.IsNullOrEmpty(this.strEffectsDuration)) { - this.Control.EffectsDuration = Convert.ToDouble(this.strEffectsDuration); + this.Control.EffectsDuration = Convert.ToDouble(this.strEffectsDuration, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(this.strEffectsShadowDirection)) @@ -2832,24 +2833,24 @@ private void AssignControlProperties() private string GetPath(string strPath) { - if (strPath.IndexOf("[SKINPATH]") > -1) + if (strPath.Contains("[SKINPATH]", StringComparison.OrdinalIgnoreCase)) { return strPath.Replace("[SKINPATH]", this.PortalSettings.ActiveTab.SkinPath); } - else if (strPath.IndexOf("[APPIMAGEPATH]") > -1) + + if (strPath.Contains("[APPIMAGEPATH]", StringComparison.OrdinalIgnoreCase)) { return strPath.Replace("[APPIMAGEPATH]", Globals.ApplicationPath + "/images/"); } - else if (strPath.IndexOf("[HOMEDIRECTORY]") > -1) + + if (strPath.Contains("[HOMEDIRECTORY]", StringComparison.OrdinalIgnoreCase)) { return strPath.Replace("[HOMEDIRECTORY]", this.PortalSettings.HomeDirectory); } - else + + if (strPath.StartsWith("~", StringComparison.Ordinal)) { - if (strPath.StartsWith("~")) - { - return this.ResolveUrl(strPath); - } + return this.ResolveUrl(strPath); } return strPath; diff --git a/DNN Platform/Library/UI/Skins/Pane.cs b/DNN Platform/Library/UI/Skins/Pane.cs index 594966bc9f1..b7174c926aa 100644 --- a/DNN Platform/Library/UI/Skins/Pane.cs +++ b/DNN Platform/Library/UI/Skins/Pane.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.Skins using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Linq; using System.Threading; @@ -26,7 +27,7 @@ namespace DotNetNuke.UI.Skins using Globals = DotNetNuke.Common.Globals; /// The Pane class represents a Pane within the Skin. - public class Pane + public class Pane : IDisposable { private const string CPaneOutline = "paneOutline"; private HtmlGenericControl containerWrapperControl; @@ -92,13 +93,13 @@ public void InjectModule(ModuleInfo module) classFormatString += " DnnVersionableControl"; } - this.containerWrapperControl.Attributes["class"] = string.Format(classFormatString, sanitizedModuleName, module.ModuleID); + this.containerWrapperControl.Attributes["class"] = string.Format(CultureInfo.InvariantCulture, classFormatString, sanitizedModuleName, module.ModuleID); try { if (!Globals.IsAdminControl() && (this.PortalSettings.InjectModuleHyperLink || Personalization.GetUserMode() != PortalSettings.Mode.View)) { - this.containerWrapperControl.Controls.Add(new LiteralControl("")); + this.containerWrapperControl.Controls.Add(new LiteralControl($"")); } // Load container control @@ -163,18 +164,18 @@ public void InjectModule(ModuleInfo module) container.SetModuleConfiguration(module); // display collapsible page panes - if (this.PaneControl.Visible == false) + if (!this.PaneControl.Visible) { this.PaneControl.Visible = true; } } catch (ThreadAbortException) { - // Response.Redirect may called in module control's OnInit method, so it will cause ThreadAbortException, no need any action here. + // Response.Redirect may be called in module control's OnInit method, so it will cause ThreadAbortException, no need any action here. } catch (Exception exc) { - var lex = new ModuleLoadException(string.Format(Skin.MODULEADD_ERROR, this.PaneControl.ID), exc); + var lex = new ModuleLoadException(string.Format(CultureInfo.InvariantCulture, Skin.MODULEADD_ERROR, this.PaneControl.ID), exc); if (TabPermissionController.CanAdminPage()) { // only display the error to administrators @@ -257,6 +258,22 @@ public void ProcessPane() } } + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.containerWrapperControl?.Dispose(); + this.PaneControl?.Dispose(); + } + } + private static bool IsVersionableModule(ModuleInfo moduleInfo) { if (string.IsNullOrEmpty(moduleInfo.DesktopModule.BusinessControllerClass)) @@ -338,7 +355,7 @@ private Containers.Container LoadContainerByPath(string containerPath) if (TabPermissionController.CanAdminPage()) { // only display the error to administrators - this.containerWrapperControl.Controls.Add(new ErrorContainer(this.PortalSettings, string.Format(Skin.CONTAINERLOAD_ERROR, containerPath), lex).Container); + this.containerWrapperControl.Controls.Add(new ErrorContainer(this.PortalSettings, string.Format(CultureInfo.InvariantCulture, Skin.CONTAINERLOAD_ERROR, containerPath), lex).Container); } Exceptions.LogException(lex); @@ -382,7 +399,7 @@ private Containers.Container LoadContainerFromPane() containerSrc = this.PaneControl.Attributes["ContainerSrc"]; if (containerSrc.Contains("/") && !(containerSrc.StartsWith("[g]", StringComparison.InvariantCultureIgnoreCase) || containerSrc.StartsWith("[l]", StringComparison.InvariantCultureIgnoreCase))) { - containerSrc = string.Format(SkinController.IsGlobalSkin(this.PortalSettings.ActiveTab.SkinSrc) ? "[G]containers/{0}" : "[L]containers/{0}", containerSrc.TrimStart('/')); + containerSrc = string.Format(CultureInfo.InvariantCulture, SkinController.IsGlobalSkin(this.PortalSettings.ActiveTab.SkinSrc) ? "[G]containers/{0}" : "[L]containers/{0}", containerSrc.TrimStart('/')); validSrc = true; } } @@ -526,7 +543,7 @@ private Containers.Container LoadModuleContainer(ModuleInfo module) // make the container id unique for the page if (module.ModuleID > -1) { - container.ID += module.ModuleID.ToString(); + container.ID += module.ModuleID.ToString(CultureInfo.InvariantCulture); } return container; @@ -539,9 +556,9 @@ private void ModuleMoveToPanePostBack(ClientAPIPostBackEventArgs args) var portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; if (TabPermissionController.CanAdminPage()) { - var moduleId = Convert.ToInt32(args.EventArguments["moduleid"]); - var paneName = Convert.ToString(args.EventArguments["pane"]); - var moduleOrder = Convert.ToInt32(args.EventArguments["order"]); + var moduleId = Convert.ToInt32(args.EventArguments["moduleid"], CultureInfo.InvariantCulture); + var paneName = Convert.ToString(args.EventArguments["pane"], CultureInfo.InvariantCulture); + var moduleOrder = Convert.ToInt32(args.EventArguments["order"], CultureInfo.InvariantCulture); ModuleController.Instance.UpdateModuleOrder(portalSettings.ActiveTab.TabID, moduleId, moduleOrder, paneName); ModuleController.Instance.UpdateTabModuleOrder(portalSettings.ActiveTab.TabID); diff --git a/DNN Platform/Library/UI/Skins/Skin.cs b/DNN Platform/Library/UI/Skins/Skin.cs index 02a10cb850a..de491d37482 100644 --- a/DNN Platform/Library/UI/Skins/Skin.cs +++ b/DNN Platform/Library/UI/Skins/Skin.cs @@ -57,18 +57,23 @@ public partial class Skin : UserControlBase public const string OnInitMessage = "Skin_InitMessage"; public const string OnInitMessageType = "Skin_InitMessageType"; +#pragma warning disable CA1707 // Identifiers should not contain underscores // ReSharper disable InconsistentNaming [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULELOAD_ERROR = Localization.GetString("ModuleLoad.Error"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string CONTAINERLOAD_ERROR = Localization.GetString("ContainerLoad.Error"); [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public static readonly string MODULEADD_ERROR = Localization.GetString("ModuleAdd.Error"); +#pragma warning restore CA1707 // ReSharper restore InconsistentNaming private readonly ModuleInjectionManager moduleInjectionManager; @@ -421,10 +426,10 @@ public static List GetInstalledSkins() var list = new List(); foreach (string folder in Directory.GetDirectories(Path.Combine(Globals.HostMapPath, "Skins"))) { - if (!folder.EndsWith(Globals.glbHostSkinFolder)) + if (!folder.EndsWith(Globals.glbHostSkinFolder, StringComparison.OrdinalIgnoreCase)) { var skin = new InstalledSkinInfo(); - skin.SkinName = folder.Substring(folder.LastIndexOf("\\") + 1); + skin.SkinName = folder.Substring(folder.LastIndexOf(@"\", StringComparison.Ordinal) + 1); skin.InUse = IsFallbackSkin(folder) || !SkinController.CanDeleteSkin(folder, string.Empty); list.Add(skin); } @@ -531,7 +536,7 @@ protected override void OnInit(EventArgs e) if (!TabPermissionController.CanAdminPage() && !success) { // only display the warning to non-administrators (administrators will see the errors) - AddPageMessage(this, Localization.GetString("ModuleLoadWarning.Error"), string.Format(Localization.GetString("ModuleLoadWarning.Text"), this.PortalSettings.Email), ModuleMessage.ModuleMessageType.YellowWarning, string.Empty); + AddPageMessage(this, Localization.GetString("ModuleLoadWarning.Error"), string.Format(CultureInfo.CurrentCulture, Localization.GetString("ModuleLoadWarning.Text"), this.PortalSettings.Email), ModuleMessage.ModuleMessageType.YellowWarning, string.Empty); } this.InvokeSkinEvents(SkinEventType.OnSkinInit); @@ -672,7 +677,7 @@ private static Skin LoadSkin(PageBase page, string skinPath) { // only display the error to administrators var skinError = (Label)page.FindControl("SkinError"); - skinError.Text = string.Format(Localization.GetString("SkinLoadError", Localization.GlobalResourceFile), skinPath, page.Server.HtmlEncode(exc.Message)); + skinError.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("SkinLoadError", Localization.GlobalResourceFile), skinPath, page.Server.HtmlEncode(exc.Message)); skinError.Visible = true; } @@ -685,8 +690,8 @@ private static Skin LoadSkin(PageBase page, string skinPath) private static bool IsFallbackSkin(string skinPath) { SkinDefaults defaultSkin = SkinDefaults.GetSkinDefaults(SkinDefaultType.SkinInfo); - string defaultSkinPath = (Globals.HostMapPath + SkinController.RootSkin + defaultSkin.Folder).Replace("/", "\\"); - if (defaultSkinPath.EndsWith("\\")) + string defaultSkinPath = (Globals.HostMapPath + SkinController.RootSkin + defaultSkin.Folder).Replace("/", @"\"); + if (defaultSkinPath.EndsWith(@"\", StringComparison.Ordinal)) { defaultSkinPath = defaultSkinPath.Substring(0, defaultSkinPath.Length - 1); } @@ -920,7 +925,7 @@ private bool ProcessMasterModules() AddPageMessage( this, string.Empty, - string.Format(Localization.GetString("ContractExpired.Error"), this.PortalSettings.PortalName, Globals.GetMediumDate(this.PortalSettings.ExpiryDate.ToString(CultureInfo.InvariantCulture)), this.PortalSettings.Email), + string.Format(CultureInfo.CurrentCulture, Localization.GetString("ContractExpired.Error"), this.PortalSettings.PortalName, Globals.GetMediumDate(this.PortalSettings.ExpiryDate.ToString(CultureInfo.InvariantCulture)), this.PortalSettings.Email), ModuleMessage.ModuleMessageType.RedError, string.Empty); } diff --git a/DNN Platform/Library/UI/Skins/SkinControl.cs b/DNN Platform/Library/UI/Skins/SkinControl.cs index 6d2fb2094ce..317e2b00e6d 100644 --- a/DNN Platform/Library/UI/Skins/SkinControl.cs +++ b/DNN Platform/Library/UI/Skins/SkinControl.cs @@ -22,13 +22,18 @@ namespace DotNetNuke.UI.Skins public class SkinControl : UserControlBase { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DropDownList cboSkin; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CommandButton cmdPreview; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RadioButton optHost; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RadioButton optSite; + private string defaultKey = "System"; private string skinRoot; private string skinSrc; @@ -38,41 +43,20 @@ public class SkinControl : UserControlBase public string DefaultKey { - get - { - return this.defaultKey; - } - - set - { - this.defaultKey = value; - } + get => this.defaultKey; + set => this.defaultKey = value; } public string Width { - get - { - return Convert.ToString(this.ViewState["SkinControlWidth"]); - } - - set - { - this.width = value; - } + get => Convert.ToString(this.ViewState["SkinControlWidth"], CultureInfo.InvariantCulture); + set => this.width = value; } public string SkinRoot { - get - { - return Convert.ToString(this.ViewState["SkinRoot"]); - } - - set - { - this.skinRoot = value; - } + get => Convert.ToString(this.ViewState["SkinRoot"], CultureInfo.InvariantCulture); + set => this.skinRoot = value; } public string SkinSrc @@ -130,7 +114,7 @@ protected override void OnLoad(EventArgs e) { if (this.Request.QueryString["pid"] != null && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) { - this.objPortal = PortalController.Instance.GetPortal(int.Parse(this.Request.QueryString["pid"])); + this.objPortal = PortalController.Instance.GetPortal(int.Parse(this.Request.QueryString["pid"], CultureInfo.InvariantCulture)); } else { @@ -187,6 +171,7 @@ protected override void OnLoad(EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void optHost_CheckedChanged(object sender, EventArgs e) @@ -195,6 +180,7 @@ protected void optHost_CheckedChanged(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void optSite_CheckedChanged(object sender, EventArgs e) @@ -203,6 +189,7 @@ protected void optSite_CheckedChanged(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdPreview_Click(object sender, EventArgs e) @@ -252,7 +239,7 @@ private void LoadSkins() // select current skin for (int intIndex = 0; intIndex < this.cboSkin.Items.Count; intIndex++) { - if (this.cboSkin.Items[intIndex].Value.Equals(Convert.ToString(this.ViewState["SkinSrc"]), StringComparison.OrdinalIgnoreCase)) + if (this.cboSkin.Items[intIndex].Value.Equals(Convert.ToString(this.ViewState["SkinSrc"], CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase)) { this.cboSkin.Items[intIndex].Selected = true; break; diff --git a/DNN Platform/Library/UI/Skins/SkinController.cs b/DNN Platform/Library/UI/Skins/SkinController.cs index faad524fc8d..b3288d94563 100644 --- a/DNN Platform/Library/UI/Skins/SkinController.cs +++ b/DNN Platform/Library/UI/Skins/SkinController.cs @@ -6,11 +6,13 @@ namespace DotNetNuke.UI.Skins using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.IO.Compression; using System.Text.RegularExpressions; using DotNetNuke.Abstractions.Application; + using DotNetNuke.Abstractions.Logging; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; @@ -36,6 +38,7 @@ public partial class SkinController private static readonly Regex SdirRegex = new Regex("\\[s]", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex LdirRegex = new Regex("\\[l]", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly string[] MessageSeparator = ["
    ",]; + private static readonly List LegacySkinExtensions = [".ASCX", ".HTM", ".HTML", ".CSS", ".SWF", ".RESX", ".XAML", ".JS",]; public static string RootSkin => "Skins"; @@ -75,18 +78,18 @@ public static bool CanDeleteSkin(IHostSettings hostSettings, string folderPath, if (folderPath.IndexOf(Globals.HostMapPath, StringComparison.InvariantCultureIgnoreCase) != -1) { skinType = "G"; - skinFolder = folderPath.ToLowerInvariant().Replace(Globals.HostMapPath.ToLowerInvariant(), string.Empty).Replace("\\", "/"); + skinFolder = folderPath.ToLowerInvariant().Replace(Globals.HostMapPath.ToLowerInvariant(), string.Empty).Replace(@"\", "/"); } else if (folderPath.IndexOf(PortalSettings.Current.HomeSystemDirectoryMapPath, StringComparison.InvariantCultureIgnoreCase) != -1) { skinType = "S"; - skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), string.Empty).Replace("\\", "/"); + skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), string.Empty).Replace(@"\", "/"); } else { // to be compliant with all versions skinType = "L"; - skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), string.Empty).Replace("\\", "/"); + skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), string.Empty).Replace(@"\", "/"); } var portalSettings = PortalController.Instance.GetCurrentSettings(); @@ -161,7 +164,7 @@ public static string FormatSkinPath(string skinSrc) string strSkinSrc = skinSrc; if (!string.IsNullOrEmpty(strSkinSrc)) { - strSkinSrc = strSkinSrc.Substring(0, strSkinSrc.LastIndexOf("/") + 1); + strSkinSrc = strSkinSrc.Substring(0, strSkinSrc.LastIndexOf("/", StringComparison.Ordinal) + 1); } return strSkinSrc; @@ -340,56 +343,51 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s string strExtension; string strFileName; - FileStream objFileStream; + FileStream fileStream; var arrData = new byte[2048]; string strMessage = string.Empty; var arrSkinFiles = new ArrayList(); // Localized Strings PortalSettings resourcePortalSettings = Globals.GetPortalSettings(); - string bEGIN_MESSAGE = Localization.GetString("BeginZip", resourcePortalSettings); - string cREATE_DIR = Localization.GetString("CreateDir", resourcePortalSettings); - string wRITE_FILE = Localization.GetString("WriteFile", resourcePortalSettings); - string fILE_ERROR = Localization.GetString("FileError", resourcePortalSettings); - string eND_MESSAGE = Localization.GetString("EndZip", resourcePortalSettings); - string fILE_RESTICTED = Localization.GetString("FileRestricted", resourcePortalSettings); + string beginMessage = Localization.GetString("BeginZip", resourcePortalSettings); + string createDir = Localization.GetString("CreateDir", resourcePortalSettings); + string writeFile = Localization.GetString("WriteFile", resourcePortalSettings); + string fileError = Localization.GetString("FileError", resourcePortalSettings); + string endMessage = Localization.GetString("EndZip", resourcePortalSettings); + string fileRestricted = Localization.GetString("FileRestricted", resourcePortalSettings); - strMessage += FormatMessage(bEGIN_MESSAGE, skinName, -1, false); + strMessage += FormatMessage(beginMessage, skinName, -1, false); foreach (var objZipEntry in objZipInputStream.FileEntries()) { // validate file extension - strExtension = objZipEntry.FullName.Substring(objZipEntry.FullName.LastIndexOf(".") + 1); - var extraExtensions = new List { ".ASCX", ".HTM", ".HTML", ".CSS", ".SWF", ".RESX", ".XAML", ".JS" }; - if (Host.AllowedExtensionWhitelist.IsAllowedExtension(strExtension, extraExtensions)) + strExtension = objZipEntry.FullName.Substring(objZipEntry.FullName.LastIndexOf(".", StringComparison.Ordinal) + 1); + if (Host.AllowedExtensionWhitelist.IsAllowedExtension(strExtension, LegacySkinExtensions)) { // process embedded zip files if (objZipEntry.FullName.Equals(RootSkin.ToLowerInvariant() + ".zip", StringComparison.OrdinalIgnoreCase)) { - using (var objMemoryStream = new MemoryStream()) - { - objZipEntry.Open().CopyToStream(objMemoryStream, 25000); - objMemoryStream.Seek(0, SeekOrigin.Begin); - strMessage += UploadLegacySkin(rootPath, RootSkin, skinName, objMemoryStream); - } + using var objMemoryStream = new MemoryStream(); + objZipEntry.Open().CopyToStream(objMemoryStream, 25000); + objMemoryStream.Seek(0, SeekOrigin.Begin); + strMessage += UploadLegacySkin(rootPath, RootSkin, skinName, objMemoryStream); } else if (objZipEntry.FullName.Equals(RootContainer.ToLowerInvariant() + ".zip", StringComparison.OrdinalIgnoreCase)) { - using (var objMemoryStream = new MemoryStream()) - { - objZipEntry.Open().CopyToStream(objMemoryStream, 25000); - objMemoryStream.Seek(0, SeekOrigin.Begin); - strMessage += UploadLegacySkin(rootPath, RootContainer, skinName, objMemoryStream); - } + using var objMemoryStream = new MemoryStream(); + objZipEntry.Open().CopyToStream(objMemoryStream, 25000); + objMemoryStream.Seek(0, SeekOrigin.Begin); + strMessage += UploadLegacySkin(rootPath, RootContainer, skinName, objMemoryStream); } else { - strFileName = rootPath + skinRoot + "\\" + skinName + "\\" + objZipEntry.FullName; + strFileName = $@"{rootPath}{skinRoot}\{skinName}\{objZipEntry.FullName}"; // create the directory if it does not exist if (!Directory.Exists(Path.GetDirectoryName(strFileName))) { - strMessage += FormatMessage(cREATE_DIR, Path.GetDirectoryName(strFileName), 2, false); + strMessage += FormatMessage(createDir, Path.GetDirectoryName(strFileName), 2, false); Directory.CreateDirectory(Path.GetDirectoryName(strFileName)); } @@ -401,12 +399,12 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s } // create the new file - objFileStream = File.Create(strFileName); + fileStream = File.Create(strFileName); // unzip the file - strMessage += FormatMessage(wRITE_FILE, Path.GetFileName(strFileName), 2, false); - objZipEntry.Open().CopyToStream(objFileStream, 25000); - objFileStream.Close(); + strMessage += FormatMessage(writeFile, Path.GetFileName(strFileName), 2, false); + objZipEntry.Open().CopyToStream(fileStream, 25000); + fileStream.Close(); // save the skin file switch (Path.GetExtension(strFileName)) @@ -428,11 +426,11 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s } else { - strMessage += string.Format(fILE_RESTICTED, objZipEntry.FullName, Host.AllowedExtensionWhitelist.ToStorageString(), ",", ", *.").Replace("2", "true"); + strMessage += string.Format(CultureInfo.CurrentCulture, fileRestricted, objZipEntry.FullName, Host.AllowedExtensionWhitelist.ToStorageString(), ",", ", *.").Replace("2", "true"); } } - strMessage += FormatMessage(eND_MESSAGE, skinName + ".zip", 1, false); + strMessage += FormatMessage(endMessage, skinName + ".zip", 1, false); objZipInputStream.Dispose(); // process the list of skin files @@ -442,7 +440,7 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s // log installation event try { - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; + var log = new LogInfo { LogTypeKey = nameof(EventLogType.HOST_ALERT), }; log.LogProperties.Add(new LogDetailInfo("Install Skin:", skinName)); Array arrMessage = strMessage.Split(MessageSeparator, StringSplitOptions.None); foreach (string strRow in arrMessage) @@ -464,11 +462,11 @@ private static void AddSkinFiles(List> skins, strin { foreach (string skinFile in Directory.GetFiles(skinFolder, "*.ascx")) { - string folder = skinFolder.Substring(skinFolder.LastIndexOf("\\") + 1); + string folder = skinFolder.Substring(skinFolder.LastIndexOf(@"\", StringComparison.Ordinal) + 1); - string key = (skinPrefix == PortalSystemSkinPrefix || skinPrefix == PortalSkinPrefix ? "Site: " : "Host: ") + string key = (skinPrefix is PortalSystemSkinPrefix or PortalSkinPrefix ? "Site: " : "Host: ") + FormatSkinName(folder, Path.GetFileNameWithoutExtension(skinFile)); - string value = skinPrefix + skinRoot + "/" + folder + "/" + Path.GetFileName(skinFile); + string value = $"{skinPrefix}{skinRoot}/{folder}/{Path.GetFileName(skinFile)}"; skins.Add(new KeyValuePair(key, value)); } } @@ -482,7 +480,7 @@ private static List> GetHostSkins(string skinRoot) { foreach (string skinFolder in Directory.GetDirectories(root)) { - if (!skinFolder.EndsWith(Globals.glbHostSkinFolder)) + if (!skinFolder.EndsWith(Globals.glbHostSkinFolder, StringComparison.OrdinalIgnoreCase)) { AddSkinFiles(skins, skinRoot, skinFolder, GlobalSkinPrefix); } diff --git a/DNN Platform/Library/UI/Skins/SkinDefaults.cs b/DNN Platform/Library/UI/Skins/SkinDefaults.cs index b725ca639dc..f5212c2a6b8 100644 --- a/DNN Platform/Library/UI/Skins/SkinDefaults.cs +++ b/DNN Platform/Library/UI/Skins/SkinDefaults.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.Skins { using System; + using System.Globalization; using System.Xml; using DotNetNuke.Common.Utilities; @@ -79,7 +80,7 @@ public static SkinDefaults GetSkinDefaults(SkinDefaultType defaultType) { return CBO.GetCachedObject( - new CacheItemArgs(string.Format(DataCache.SkinDefaultsCacheKey, defaultType), DataCache.SkinDefaultsCacheTimeOut, DataCache.SkinDefaultsCachePriority, defaultType), + new CacheItemArgs(string.Format(CultureInfo.InvariantCulture, DataCache.SkinDefaultsCacheKey, defaultType), DataCache.SkinDefaultsCacheTimeOut, DataCache.SkinDefaultsCachePriority, defaultType), GetSkinDefaultsCallback); } diff --git a/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs b/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs index ded67fdc529..77db875f3a6 100644 --- a/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs +++ b/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.Skins { using System; using System.Collections; + using System.Globalization; using System.IO; using System.Text.RegularExpressions; using System.Web; @@ -64,7 +65,7 @@ public SkinFileProcessor(string controlKey, string controlSrc) /// /// The constructor primes the file processor with path information and /// control data that should only be retrieved once. It checks for the - /// existentce of a skin level attribute file and read it in, if found. + /// existence of a skin level attribute file and read it in, if found. /// It also sorts through the complete list of controls and creates /// a hashtable which contains only the skin objects and their source paths. /// These are recognized by their ControlKey's which are formatted like @@ -73,7 +74,7 @@ public SkinFileProcessor(string controlKey, string controlSrc) /// public SkinFileProcessor(string skinPath, string skinRoot, string skinName) { - this.Message += SkinController.FormatMessage(this.iNITIALIZEPROCESSOR, skinRoot + " :: " + skinName, 0, false); + this.Message += SkinController.FormatMessage(this.iNITIALIZEPROCESSOR, $"{skinRoot} :: {skinName}", 0, false); // Save path information for future use this.SkinRoot = skinRoot; @@ -81,7 +82,8 @@ public SkinFileProcessor(string skinPath, string skinRoot, string skinName) this.SkinName = skinName; // Check for and read skin package level attribute information file - string fileName = this.SkinPath + this.SkinRoot + "\\" + this.SkinName + "\\" + skinRoot.Substring(0, skinRoot.Length - 1) + ".xml"; + string fileName = + $@"{this.SkinPath}{this.SkinRoot}\{this.SkinName}\{skinRoot.Substring(0, skinRoot.Length - 1)}.xml"; if (File.Exists(fileName)) { try @@ -93,7 +95,7 @@ public SkinFileProcessor(string skinPath, string skinRoot, string skinName) { // could not load XML file Logger.Error(ex); - this.Message += SkinController.FormatMessage(string.Format(this.pACKAGELOADERROR, ex.Message), Path.GetFileName(fileName), 2, true); + this.Message += SkinController.FormatMessage(string.Format(CultureInfo.CurrentCulture, this.pACKAGELOADERROR, ex.Message), Path.GetFileName(fileName), 2, true); } } @@ -106,15 +108,15 @@ public SkinFileProcessor(string skinPath, string skinRoot, string skinName) if (this.controlList.ContainsKey(token)) { this.Message += SkinController.FormatMessage( - string.Format(this.dUPLICATEERROR, token), - string.Format(this.dUPLICATEDETAIL, this.controlList[token], objSkinControl.ControlSrc), + string.Format(CultureInfo.CurrentCulture, this.dUPLICATEERROR, token), + string.Format(CultureInfo.CurrentCulture, this.dUPLICATEDETAIL, this.controlList[token], objSkinControl.ControlSrc), 2, true); } else { // Add it - this.Message += SkinController.FormatMessage(string.Format(this.lOADSKINTOKEN, token), objSkinControl.ControlSrc, 2, false); + this.Message += SkinController.FormatMessage(string.Format(CultureInfo.CurrentCulture, this.lOADSKINTOKEN, token), objSkinControl.ControlSrc, 2, false); this.controlList.Add(token, objSkinControl.ControlSrc); } } @@ -478,17 +480,17 @@ public string Parse(ref string source) /// private string ObjectMatchHandler(Match m) { - string oBJECT_PROC = Util.GetLocalizedString("ProcessObject"); - string oBJECT_SKIN = Util.GetLocalizedString("SkinObject"); - string oBJECT_PANE = Util.GetLocalizedString("PaneObject"); - string cONTROL_FORMAT = Util.GetLocalizedString("ControlFormat"); - string oBJECT_NOTFOUND = Util.GetLocalizedString("ObjectNotFound"); + string processObject = Util.GetLocalizedString("ProcessObject"); + string skinObject = Util.GetLocalizedString("SkinObject"); + string pangeObject = Util.GetLocalizedString("PaneObject"); + string controlFormat = Util.GetLocalizedString("ControlFormat"); + string objectNotFound = Util.GetLocalizedString("ObjectNotFound"); // "token" string matches will be in the form of (" id=".." codetype=".." codebase=".." etc...>") // we need to assume properly formatted HTML - attributes will be enclosed in double quotes and there will no spaces between assignments ( ie. attribute="value" ) // extract the embedded object attributes (" id=".." codetype=".." codebase=".." etc...") - string embeddedObjectAttributes = m.Groups["token"].Value.Substring(0, m.Groups["token"].Value.IndexOf(">")); + string embeddedObjectAttributes = m.Groups["token"].Value.Substring(0, m.Groups["token"].Value.IndexOf(">", StringComparison.Ordinal)); // split into array string[] attributes = embeddedObjectAttributes.Split(' '); @@ -499,16 +501,13 @@ private string ObjectMatchHandler(Match m) string controlName = string.Empty; // iterate and process valid attributes - string[] attribute; - string attributeName; - string attributeValue; foreach (string strAttribute in attributes) { if (strAttribute != string.Empty) { - attribute = strAttribute.Split('='); - attributeName = attribute[0].Trim(); - attributeValue = attribute[1].Trim().Replace("\"", string.Empty); + var attribute = strAttribute.Split('='); + var attributeName = attribute[0].Trim(); + var attributeValue = attribute[1].Trim().Replace("\"", string.Empty); switch (attributeName.ToLowerInvariant()) { case "id": @@ -528,7 +527,7 @@ private string ObjectMatchHandler(Match m) if (attributeNode.Equals("dotnetnuke/server", StringComparison.OrdinalIgnoreCase)) { // we have a valid skin object specification - this.Messages += SkinController.FormatMessage(oBJECT_PROC, token, 2, false); + this.Messages += SkinController.FormatMessage(processObject, token, 2, false); // if the embedded object is a recognized skin object if (this.ControlList.ContainsKey(token) || token == "CONTENTPANE") @@ -537,15 +536,15 @@ private string ObjectMatchHandler(Match m) if (this.ControlList.ContainsKey(token)) { - this.Messages += SkinController.FormatMessage(oBJECT_SKIN, (string)this.ControlList[token], 2, false); + this.Messages += SkinController.FormatMessage(skinObject, (string)this.ControlList[token], 2, false); } else { - this.Messages += SkinController.FormatMessage(oBJECT_PANE, token, 2, false); + this.Messages += SkinController.FormatMessage(pangeObject, token, 2, false); } // process embedded object params - string parameters = m.Groups["token"].Value.Substring(m.Groups["token"].Value.IndexOf(">") + 1); + string parameters = m.Groups["token"].Value.Substring(m.Groups["token"].Value.IndexOf(">", StringComparison.Ordinal) + 1); parameters = parameters.Replace("", string.Empty); @@ -572,7 +571,7 @@ private string ObjectMatchHandler(Match m) } // return the control statement - this.Messages += SkinController.FormatMessage(cONTROL_FORMAT, "<" + skinControl + " />", 2, false); + this.Messages += SkinController.FormatMessage(controlFormat, "<" + skinControl + " />", 2, false); skinControl = "<" + skinControl + "/>"; } else @@ -590,7 +589,7 @@ private string ObjectMatchHandler(Match m) skinControl += parameters + ">"; } @@ -599,7 +598,7 @@ private string ObjectMatchHandler(Match m) else { // return the unmodified embedded object - this.Messages += SkinController.FormatMessage(oBJECT_NOTFOUND, token, 2, false); + this.Messages += SkinController.FormatMessage(objectNotFound, token, 2, false); return ""; } } @@ -750,13 +749,13 @@ private string MatchHandler(Match m) string strNewTag = strOldTag; // we do not want to process object tags to DotNetNuke widgets - if (!m.Groups[0].Value.ToLowerInvariant().Contains("codetype=\"dotnetnuke/client\"")) + if (!m.Groups[0].Value.Contains("codetype=\"dotnetnuke/client\"", StringComparison.OrdinalIgnoreCase)) { switch (this.ParseOption) { case SkinParser.Localized: // if the tag does not contain the localized path - if (strNewTag.IndexOf(this.SkinPath) == -1) + if (!strNewTag.Contains(this.SkinPath, StringComparison.OrdinalIgnoreCase)) { // insert the localized path strNewTag = m.Groups["tag"].Value + this.SkinPath + m.Groups["content"].Value + m.Groups["endtag"].Value; @@ -765,14 +764,14 @@ private string MatchHandler(Match m) break; case SkinParser.Portable: // if the tag does not contain a reference to the skinpath - if (strNewTag.IndexOf("<%= skinpath %>", StringComparison.InvariantCultureIgnoreCase) == -1) + if (!strNewTag.Contains("<%= skinpath %>", StringComparison.OrdinalIgnoreCase)) { // insert the skinpath strNewTag = m.Groups["tag"].Value + "<%= SkinPath %>" + m.Groups["content"].Value + m.Groups["endtag"].Value; } // if the tag contains the localized path - if (strNewTag.IndexOf(this.SkinPath) != -1) + if (strNewTag.Contains(this.SkinPath, StringComparison.OrdinalIgnoreCase)) { // remove the localized path strNewTag = strNewTag.Replace(this.SkinPath, string.Empty); @@ -782,7 +781,7 @@ private string MatchHandler(Match m) } } - this.messages += SkinController.FormatMessage(this.subst, string.Format(this.substDetail, HttpUtility.HtmlEncode(strOldTag), HttpUtility.HtmlEncode(strNewTag)), 2, false); + this.messages += SkinController.FormatMessage(this.subst, string.Format(CultureInfo.InvariantCulture, this.substDetail, HttpUtility.HtmlEncode(strOldTag), HttpUtility.HtmlEncode(strNewTag)), 2, false); return strNewTag; } } @@ -790,25 +789,25 @@ private string MatchHandler(Match m) /// Utility class for processing of skin files. private class SkinFile { - private const string StrPattern = "<\\s*body[^>]*>(?.*)<\\s*/\\s*body\\s*>"; + private const string StrPattern = @"<\s*body[^>]*>(?.*)<\s*/\s*body\s*>"; private static readonly Regex PaneCheck1Regex = new Regex("\\s*id\\s*=\\s*\"" + Globals.glbDefaultPane + "\"", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex PaneCheck2Regex = new Regex("\\s*[" + Globals.glbDefaultPane + "]", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex BodyExtractionRegex = new Regex(StrPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); - private readonly string cONTROLDIR = Util.GetLocalizedString("ControlDirective"); - private readonly string cONTROLREG = Util.GetLocalizedString("ControlRegister"); - private readonly string fILEFORMATERROR = Util.GetLocalizedString("FileFormat.Error"); - private readonly string fILELOAD = Util.GetLocalizedString("SkinFileLoad"); - private readonly string fILELOADERROR = Util.GetLocalizedString("SkinFileLoad.Error"); - private readonly string fILEWRITE = Util.GetLocalizedString("FileWrite"); + private readonly string controlDirective = Util.GetLocalizedString("ControlDirective"); + private readonly string controlRegister = Util.GetLocalizedString("ControlRegister"); + private readonly string fileFormatError = Util.GetLocalizedString("FileFormat.Error"); + private readonly string fileLoad = Util.GetLocalizedString("SkinFileLoad"); + private readonly string fileLoadError = Util.GetLocalizedString("SkinFileLoad.Error"); + private readonly string fileWrite = Util.GetLocalizedString("FileWrite"); + private readonly string fileFormatDetail = Util.GetLocalizedString("FileFormat.Detail"); private readonly XmlDocument fileAttributes; private readonly string fileExtension; private readonly string fileName; private readonly string skinRoot; private readonly string skinRootPath; private readonly string writeFileName; - private string fILEFORMATDETAIL = Util.GetLocalizedString("FileFormat.Detail"); private string messages = string.Empty; /// Initializes a new instance of the class. @@ -861,7 +860,7 @@ public SkinFile(string skinRoot, string fileName, XmlDocument skinAttributes) // capture warning if file does not contain a id="ContentPane" or [CONTENTPANE] if (!PaneCheck1Regex.IsMatch(this.Contents) && !PaneCheck2Regex.IsMatch(this.Contents)) { - this.messages += SkinController.FormatMessage(this.fILEFORMATERROR, string.Format(this.fILEFORMATERROR, fileName), 2, true); + this.messages += SkinController.FormatMessage(this.fileFormatError, string.Format(CultureInfo.InvariantCulture, this.fileFormatError, fileName), 2, true); } // Check for existence of and load skin file level attribute information @@ -870,14 +869,14 @@ public SkinFile(string skinRoot, string fileName, XmlDocument skinAttributes) try { this.fileAttributes.Load(fileName.Replace(this.FileExtension, ".xml")); - this.messages += SkinController.FormatMessage(this.fILELOAD, fileName, 2, false); + this.messages += SkinController.FormatMessage(this.fileLoad, fileName, 2, false); } catch (Exception exc) { // could not load XML file Logger.Error(exc); this.fileAttributes = skinAttributes; - this.messages += SkinController.FormatMessage(this.fILELOADERROR, fileName, 2, true); + this.messages += SkinController.FormatMessage(this.fileLoadError, fileName, 2, true); } } @@ -955,7 +954,7 @@ public void Write() File.Delete(this.WriteFileName); } - this.messages += SkinController.FormatMessage(this.fILEWRITE, Path.GetFileName(this.WriteFileName), 2, false); + this.messages += SkinController.FormatMessage(this.fileWrite, Path.GetFileName(this.WriteFileName), 2, false); using (var objStreamWriter = new StreamWriter(this.WriteFileName)) { objStreamWriter.WriteLine(this.Contents); @@ -992,12 +991,12 @@ public string PrependASCXDirectives(ArrayList registrations) prefix += "<%@ Control language=\"vb\" AutoEventWireup=\"false\" Explicit=\"True\" Inherits=\"DotNetNuke.UI.Containers.Container\" %>" + Environment.NewLine; } - messages += SkinController.FormatMessage(this.cONTROLDIR, HttpUtility.HtmlEncode(prefix), 2, false); + messages += SkinController.FormatMessage(this.controlDirective, HttpUtility.HtmlEncode(prefix), 2, false); // add preformatted Control Registrations foreach (string item in registrations) { - messages += SkinController.FormatMessage(this.cONTROLREG, HttpUtility.HtmlEncode(item), 2, false); + messages += SkinController.FormatMessage(this.controlRegister, HttpUtility.HtmlEncode(item), 2, false); prefix += item; } diff --git a/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs b/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs index 708faa04e02..a9ae9790c0c 100644 --- a/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs +++ b/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.Skins { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; @@ -25,12 +26,14 @@ public abstract class SkinThumbNailControl : UserControlBase { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected HtmlGenericControl ControlContainer; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected RadioButtonList OptSkin; @@ -41,7 +44,7 @@ public string Border { get { - return Convert.ToString(this.ViewState["SkinControlBorder"]); + return Convert.ToString(this.ViewState["SkinControlBorder"], CultureInfo.InvariantCulture); } set @@ -61,7 +64,7 @@ public int Columns { get { - return Convert.ToInt32(this.ViewState["SkinControlColumns"]); + return Convert.ToInt32(this.ViewState["SkinControlColumns"], CultureInfo.InvariantCulture); } set @@ -78,7 +81,7 @@ public string Height { get { - return Convert.ToString(this.ViewState["SkinControlHeight"]); + return Convert.ToString(this.ViewState["SkinControlHeight"], CultureInfo.InvariantCulture); } set @@ -95,7 +98,7 @@ public string SkinRoot { get { - return Convert.ToString(this.ViewState["SkinRoot"]); + return Convert.ToString(this.ViewState["SkinRoot"], CultureInfo.InvariantCulture); } set @@ -130,7 +133,7 @@ public string Width { get { - return Convert.ToString(this.ViewState["SkinControlWidth"]); + return Convert.ToString(this.ViewState["SkinControlWidth"], CultureInfo.InvariantCulture); } set @@ -183,7 +186,7 @@ public void LoadHostSkins(bool includeNotSpecified) var arrFolders = Directory.GetDirectories(strRoot); foreach (var strFolder in arrFolders) { - if (!strFolder.EndsWith(Globals.glbHostSkinFolder)) + if (!strFolder.EndsWith(Globals.glbHostSkinFolder, StringComparison.OrdinalIgnoreCase)) { this.LoadSkins(strFolder, "[G]", false); } @@ -228,7 +231,7 @@ public void LoadSkins(string strFolder, string skinType, bool includeNotSpecifie if (Directory.Exists(strFolder)) { var arrFiles = Directory.GetFiles(strFolder, "*.ascx"); - strFolder = strFolder.Substring(strFolder.LastIndexOf("\\") + 1); + strFolder = strFolder.Substring(strFolder.LastIndexOf(@"\", StringComparison.Ordinal) + 1); foreach (var strFile in arrFiles) { @@ -256,7 +259,7 @@ private static string FormatSkinName(string strSkinFolder, string strSkinFile) case "default": return strSkinFolder; default: - return string.Format("{0} - {1}", strSkinFolder, strSkinFile); + return $"{strSkinFolder} - {strSkinFile}"; } } @@ -332,7 +335,7 @@ private static string CreateThumbnail(string strImage) } } - strThumbnail = Globals.ApplicationPath + "\\" + strThumbnail.Substring(strThumbnail.IndexOf("portals\\", StringComparison.InvariantCultureIgnoreCase)); + strThumbnail = Globals.ApplicationPath + @"\" + strThumbnail.Substring(strThumbnail.IndexOf("portals\\", StringComparison.InvariantCultureIgnoreCase)); return strThumbnail; } @@ -340,7 +343,7 @@ private static string CreateThumbnail(string strImage) private void AddDefaultSkin() { var strDefault = Localization.GetString("Not_Specified") + "
    "; - strDefault += ""; + strDefault += ""; this.OptSkin.Items.Insert(0, new ListItem(strDefault, string.Empty)); } @@ -354,11 +357,11 @@ private void AddSkin(string root, string strFolder, string strFile) if (File.Exists(strFile.Replace(".ascx", ".jpg"))) { strImage += ""; + CreateThumbnail(strFile.Replace(".ascx", ".jpg")).Replace(@"\", "/") + "\" border=\"1\">"; } else { - strImage += ""; + strImage += ""; } this.OptSkin.Items.Add(new ListItem(FormatSkinName(strFolder, Path.GetFileNameWithoutExtension(strFile)) + "
    " + strImage, root + "/" + strFolder + "/" + Path.GetFileName(strFile))); diff --git a/DNN Platform/Library/UI/UIUtilities.cs b/DNN Platform/Library/UI/UIUtilities.cs index 7e2a46ff486..ac5e7363db1 100644 --- a/DNN Platform/Library/UI/UIUtilities.cs +++ b/DNN Platform/Library/UI/UIUtilities.cs @@ -173,28 +173,28 @@ internal static string GetLocalResourceFile(Control ctrl) { if (ctrl is UserControl) { - resourceFileName = string.Format("{0}/{1}/{2}.ascx.resx", ctrl.TemplateSourceDirectory, Localization.LocalResourceDirectory, ctrl.GetType().BaseType.Name); + resourceFileName = $"{ctrl.TemplateSourceDirectory}/{Localization.LocalResourceDirectory}/{ctrl.GetType().BaseType.Name}.ascx.resx"; if (File.Exists(ctrl.Page.Server.MapPath(resourceFileName))) { break; } } - if (ctrl is IModuleControl) + if (ctrl is IModuleControl moduleControl) { - resourceFileName = ((IModuleControl)ctrl).LocalResourceFile; + resourceFileName = moduleControl.LocalResourceFile; break; } - if (ctrl is ControlPanelBase) + if (ctrl is ControlPanelBase controlPanel) { - resourceFileName = ((ControlPanelBase)ctrl).LocalResourceFile; + resourceFileName = controlPanel.LocalResourceFile; break; } if (ctrl is Page) { - resourceFileName = string.Format("{0}/{1}/{2}.aspx.resx", ctrl.TemplateSourceDirectory, Localization.LocalResourceDirectory, ctrl.GetType().BaseType.Name); + resourceFileName = $"{ctrl.TemplateSourceDirectory}/{Localization.LocalResourceDirectory}/{ctrl.GetType().BaseType.Name}.aspx.resx"; } ctrl = ctrl.Parent; diff --git a/DNN Platform/Library/UI/UserControls/Address.cs b/DNN Platform/Library/UI/UserControls/Address.cs index 5f06f2de564..e1dc10b8641 100644 --- a/DNN Platform/Library/UI/UserControls/Address.cs +++ b/DNN Platform/Library/UI/UserControls/Address.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.UserControls { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; @@ -21,94 +22,139 @@ namespace DotNetNuke.UI.UserControls public abstract class Address : UserControlBase { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CountryListBox cboCountry; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DropDownList cboRegion; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkCell; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkCity; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkCountry; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkFax; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkPostal; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkRegion; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkStreet; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkTelephone; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plCell; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plCity; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plCountry; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plFax; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plPostal; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plRegion; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plStreet; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plTelephone; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plUnit; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divCell; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divCity; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divCountry; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divFax; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divPostal; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divRegion; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divStreet; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divTelephone; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl divUnit; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtCell; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtCity; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtFax; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtPostal; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtRegion; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtStreet; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtTelephone; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtUnit; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valCell; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valCity; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valCountry; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valFax; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valPostal; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valRegion1; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valRegion2; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valStreet; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valTelephone; private const string MyFileName = "Address.ascx"; private string cell; @@ -153,7 +199,7 @@ public int ModuleId { get { - return Convert.ToInt32(this.ViewState["ModuleId"]); + return Convert.ToInt32(this.ViewState["ModuleId"], CultureInfo.InvariantCulture); } set @@ -166,7 +212,7 @@ public string LabelColumnWidth { get { - return Convert.ToString(this.ViewState["LabelColumnWidth"]); + return Convert.ToString(this.ViewState["LabelColumnWidth"], CultureInfo.InvariantCulture); } set @@ -179,7 +225,7 @@ public string ControlColumnWidth { get { - return Convert.ToString(this.ViewState["ControlColumnWidth"]); + return Convert.ToString(this.ViewState["ControlColumnWidth"], CultureInfo.InvariantCulture); } set @@ -575,7 +621,7 @@ protected override void OnLoad(EventArgs e) this.chkFax.Visible = true; } - this.ViewState["ModuleId"] = Convert.ToString(this.moduleId); + this.ViewState["ModuleId"] = Convert.ToString(this.moduleId, CultureInfo.InvariantCulture); this.ViewState["LabelColumnWidth"] = this.labelColumnWidth; this.ViewState["ControlColumnWidth"] = this.controlColumnWidth; diff --git a/DNN Platform/Library/UI/UserControls/DualListControl.cs b/DNN Platform/Library/UI/UserControls/DualListControl.cs index aaf24264e0a..9cfcd82077c 100644 --- a/DNN Platform/Library/UI/UserControls/DualListControl.cs +++ b/DNN Platform/Library/UI/UserControls/DualListControl.cs @@ -18,28 +18,37 @@ public abstract class DualListControl : UserControlBase { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected Label Label1; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected Label Label2; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdAdd; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdAddAll; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdRemove; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdRemoveAll; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected ListBox lstAssigned; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected ListBox lstAvailable; + private string myFileName = "DualListControl.ascx"; private ArrayList assigned; private ArrayList available; @@ -53,7 +62,7 @@ public string ListBoxWidth { get { - return Convert.ToString(this.ViewState[this.ClientID + "_ListBoxWidth"]); + return Convert.ToString(this.ViewState[this.ClientID + "_ListBoxWidth"], CultureInfo.InvariantCulture); } set @@ -66,7 +75,7 @@ public string ListBoxHeight { get { - return Convert.ToString(this.ViewState[this.ClientID + "_ListBoxHeight"]); + return Convert.ToString(this.ViewState[this.ClientID + "_ListBoxHeight"], CultureInfo.InvariantCulture); } set diff --git a/DNN Platform/Library/UI/UserControls/Help.cs b/DNN Platform/Library/UI/UserControls/Help.cs index 7dab50454a1..4c598dec65f 100644 --- a/DNN Platform/Library/UI/UserControls/Help.cs +++ b/DNN Platform/Library/UI/UserControls/Help.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.UserControls { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Web.UI.WebControls; @@ -21,15 +22,21 @@ namespace DotNetNuke.UI.UserControls public abstract class Help : PortalModuleBase { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdCancel; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HyperLink cmdHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Literal helpFrame; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblInfo; + private string myFileName = "Help.ascx"; private string key; @@ -43,11 +50,11 @@ protected override void OnLoad(EventArgs e) if (this.Request.QueryString["ctlid"] != null) { - moduleControlId = int.Parse(this.Request.QueryString["ctlid"]); + moduleControlId = int.Parse(this.Request.QueryString["ctlid"], CultureInfo.InvariantCulture); } else if (Host.EnableModuleOnLineHelp) { - this.helpFrame.Text = string.Format("", Host.HelpURL); + this.helpFrame.Text = $""; } ModuleControlInfo objModuleControl = ModuleControlController.GetModuleControl(moduleControlId); @@ -55,7 +62,7 @@ protected override void OnLoad(EventArgs e) { if (!string.IsNullOrEmpty(objModuleControl.HelpURL) && Host.EnableModuleOnLineHelp) { - this.helpFrame.Text = string.Format("", objModuleControl.HelpURL); + this.helpFrame.Text = $""; } else { @@ -105,11 +112,11 @@ protected override void OnLoad(EventArgs e) this.cmdHelp.Visible = !string.IsNullOrEmpty(objModuleControl.HelpURL); } - if (this.Page.IsPostBack == false) + if (!this.Page.IsPostBack) { if (this.Request.UrlReferrer != null) { - this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); + this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer, CultureInfo.InvariantCulture); } else { @@ -122,13 +129,14 @@ protected override void OnLoad(EventArgs e) /// The event sender. /// The event arguments. [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdCancel_Click(object sender, EventArgs e) { try { - this.Response.Redirect(Convert.ToString(this.ViewState["UrlReferrer"]), true); + this.Response.Redirect(Convert.ToString(this.ViewState["UrlReferrer"], CultureInfo.InvariantCulture), true); } catch (Exception exc) { diff --git a/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs b/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs index b113fcbd19a..2ba60054e51 100644 --- a/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs +++ b/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs @@ -25,12 +25,16 @@ namespace DotNetNuke.UI.UserControls public abstract class HelpButtonControl : UserControl { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Image imgHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel pnlHelp; /// Gets or sets controlName is the Id of the control that is associated with the label. @@ -97,6 +101,7 @@ protected override void OnLoad(EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdHelp_Click(object sender, EventArgs e) diff --git a/DNN Platform/Library/UI/UserControls/LabelControl.cs b/DNN Platform/Library/UI/UserControls/LabelControl.cs index 5731d814067..2f065ce2d1d 100644 --- a/DNN Platform/Library/UI/UserControls/LabelControl.cs +++ b/DNN Platform/Library/UI/UserControls/LabelControl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.UserControls { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; @@ -25,24 +26,30 @@ namespace DotNetNuke.UI.UserControls public abstract class LabelControl : UserControl { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl label; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblLabel; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel pnlHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblNoHelpLabel; - /// Gets or sets controlName is the Id of the control that is associated with the label. + /// Gets or sets controlName is the ID of the control that is associated with the label. /// A string representing the id of the associated control. public string ControlName { get; set; } /// - /// Gets or sets set the associate control id format, combined used with ControlName for controls + /// Gets or sets the associate control ID format, combined used with ControlName for controls /// which have child edit control and want that child control focus when click label. /// public string AssociateFormat { get; set; } @@ -202,7 +209,7 @@ protected override void OnPreRender(EventArgs e) if (!string.IsNullOrEmpty(this.AssociateFormat)) { - clientId = string.Format(this.AssociateFormat, clientId); + clientId = string.Format(CultureInfo.InvariantCulture, this.AssociateFormat, clientId); } this.label.Attributes["for"] = clientId; diff --git a/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs b/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs index 50ba2689fc3..f4a284333d9 100644 --- a/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs +++ b/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.UserControls { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web.UI.WebControls; using DotNetNuke.Framework; @@ -18,10 +19,13 @@ namespace DotNetNuke.UI.UserControls public abstract class LocaleSelectorControl : UserControlBase { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DropDownList ddlPortalDefaultLanguage; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Literal litStatus; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RadioButtonList rbViewType; private string myFileName = "LocaleSelectorControl.ascx"; private string viewType = string.Empty; @@ -56,7 +60,7 @@ private string ViewType { if (string.IsNullOrEmpty(this.viewType)) { - this.viewType = Convert.ToString(Personalization.GetProfile("LanguageEnabler", string.Format("ViewType{0}", this.PortalSettings.PortalId))); + this.viewType = Convert.ToString(Personalization.GetProfile("LanguageEnabler", string.Format(CultureInfo.InvariantCulture, "ViewType{0}", this.PortalSettings.PortalId)), CultureInfo.InvariantCulture); } if (string.IsNullOrEmpty(this.viewType)) diff --git a/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs b/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs index d5aa8498796..aae1db4277a 100644 --- a/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs +++ b/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.UserControls { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Text.RegularExpressions; using System.Web.UI; using System.Web.UI.WebControls; @@ -20,8 +21,10 @@ namespace DotNetNuke.UI.UserControls public abstract class ModuleAuditControl : UserControl { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblCreatedBy; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblUpdatedBy; private const string MyFileName = "ModuleAuditControl.ascx"; @@ -82,10 +85,10 @@ protected override void OnLoad(EventArgs e) { if (this.Model != null) { - this.CreatedByUser = this.Model.CreatedByUserID.ToString(); - this.CreatedDate = this.Model.CreatedOnDate.ToString(); - this.LastModifiedByUser = this.Model.LastModifiedByUserID.ToString(); - this.LastModifiedDate = this.Model.LastModifiedOnDate.ToString(); + this.CreatedByUser = this.Model.CreatedByUserID.ToString(CultureInfo.CurrentCulture); + this.CreatedDate = this.Model.CreatedOnDate.ToString(CultureInfo.CurrentCulture); + this.LastModifiedByUser = this.Model.LastModifiedByUserID.ToString(CultureInfo.CurrentCulture); + this.LastModifiedDate = this.Model.LastModifiedOnDate.ToString(CultureInfo.CurrentCulture); } // check to see if updated check is redundant @@ -110,14 +113,14 @@ private void ShowCreatedString() { if (CheckDateColumnRegex.IsMatch(this.CreatedByUser)) { - if (int.Parse(this.CreatedByUser) == Null.NullInteger) + if (int.Parse(this.CreatedByUser, CultureInfo.CurrentCulture) == Null.NullInteger) { this.CreatedByUser = this.systemUser; } else { // contains a UserID - UserInfo userInfo = UserController.GetUserById(PortalController.Instance.GetCurrentPortalSettings().PortalId, int.Parse(this.CreatedByUser)); + UserInfo userInfo = UserController.GetUserById(PortalController.Instance.GetCurrentPortalSettings().PortalId, int.Parse(this.CreatedByUser, CultureInfo.CurrentCulture)); if (userInfo != null) { this.CreatedByUser = userInfo.DisplayName; @@ -126,7 +129,7 @@ private void ShowCreatedString() } string createdString = Localization.GetString("CreatedBy", Localization.GetResourceFile(this, MyFileName)); - this.lblCreatedBy.Text = string.Format(createdString, this.CreatedByUser, this.CreatedDate); + this.lblCreatedBy.Text = string.Format(CultureInfo.CurrentCulture, createdString, this.CreatedByUser, this.CreatedDate); } private void ShowUpdatedString(bool isCreatorAndUpdater) @@ -143,14 +146,14 @@ private void ShowUpdatedString(bool isCreatorAndUpdater) { this.LastModifiedByUser = this.CreatedByUser; } - else if (int.Parse(this.LastModifiedByUser) == Null.NullInteger) + else if (int.Parse(this.LastModifiedByUser, CultureInfo.CurrentCulture) == Null.NullInteger) { this.LastModifiedByUser = this.systemUser; } else { // contains a UserID - UserInfo userInfo = UserController.GetUserById(PortalController.Instance.GetCurrentPortalSettings().PortalId, int.Parse(this.LastModifiedByUser)); + UserInfo userInfo = UserController.GetUserById(PortalController.Instance.GetCurrentPortalSettings().PortalId, int.Parse(this.LastModifiedByUser, CultureInfo.CurrentCulture)); if (userInfo != null) { this.LastModifiedByUser = userInfo.DisplayName; @@ -159,7 +162,7 @@ private void ShowUpdatedString(bool isCreatorAndUpdater) } string updatedByString = Localization.GetString("UpdatedBy", Localization.GetResourceFile(this, MyFileName)); - this.lblUpdatedBy.Text = string.Format(updatedByString, this.LastModifiedByUser, this.LastModifiedDate); + this.lblUpdatedBy.Text = string.Format(CultureInfo.CurrentCulture, updatedByString, this.LastModifiedByUser, this.LastModifiedDate); } [Serializable] diff --git a/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs b/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs index 6994a486133..7438cf4056b 100644 --- a/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs +++ b/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs @@ -24,10 +24,13 @@ namespace DotNetNuke.UI.UserControls public class SectionHeadControl : UserControl { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected ImageButton imgIcon; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblTitle; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel pnlRule; private bool isExpanded = true; @@ -163,6 +166,7 @@ protected override void OnPreRender(EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void imgIcon_Click(object sender, ImageClickEventArgs e) diff --git a/DNN Platform/Library/UI/UserControls/TextEditor.cs b/DNN Platform/Library/UI/UserControls/TextEditor.cs index f64d258828e..8ddbb45db85 100644 --- a/DNN Platform/Library/UI/UserControls/TextEditor.cs +++ b/DNN Platform/Library/UI/UserControls/TextEditor.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.UserControls { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; @@ -25,30 +26,39 @@ public class TextEditor : UserControl // ReSharper disable InconsistentNaming [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel PanelTextEditor; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RadioButtonList OptRender; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RadioButtonList OptView; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected PlaceHolder PlcEditor; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl DivBasicTextBox; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl DivBasicRender; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl DivRichTextBox; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel PanelView; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox TxtDesktopHTML; // ReSharper restore InconsistentNaming @@ -151,7 +161,7 @@ public string Mode { if (Personalization.GetProfile("DotNetNuke.TextEditor", "PreferredTextEditor") != null) { - strMode = Convert.ToString(Personalization.GetProfile("DotNetNuke.TextEditor", "PreferredTextEditor")); + strMode = Convert.ToString(Personalization.GetProfile("DotNetNuke.TextEditor", "PreferredTextEditor"), CultureInfo.InvariantCulture); } } @@ -160,7 +170,7 @@ public string Mode { if (this.ViewState["DesktopMode"] != null && !string.IsNullOrEmpty(this.ViewState["DesktopMode"].ToString())) { - strMode = Convert.ToString(this.ViewState["DesktopMode"]); + strMode = Convert.ToString(this.ViewState["DesktopMode"], CultureInfo.InvariantCulture); } } @@ -247,7 +257,7 @@ public string TextRenderMode { get { - return Convert.ToString(this.ViewState["textrender"]); + return Convert.ToString(this.ViewState["textrender"], CultureInfo.InvariantCulture); } set diff --git a/DNN Platform/Library/UI/UserControls/URLControl.cs b/DNN Platform/Library/UI/UserControls/URLControl.cs index 5bfd27e7795..d25222551ee 100644 --- a/DNN Platform/Library/UI/UserControls/URLControl.cs +++ b/DNN Platform/Library/UI/UserControls/URLControl.cs @@ -31,81 +31,115 @@ public abstract class UrlControl : UserControlBase // ReSharper disable InconsistentNaming [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel ErrorRow; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel FileRow; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel ImagesRow; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel TabRow; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel TypeRow; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel URLRow; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel UserRow; // ReSharper restore InconsistentNaming [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DropDownList cboFiles; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DropDownList cboFolders; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DropDownList cboImages; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DropDownList cboTabs; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DropDownList cboUrls; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkLog; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkNewWindow; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CheckBox chkTrack; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdAdd; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdCancel; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdDelete; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdSave; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdSelect; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdUpload; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Image imgStorageLocationType; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblFile; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblFolder; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblImages; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblMessage; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblTab; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblURL; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblURLType; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblUser; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RadioButtonList optType; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlInputFile txtFile; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtUrl; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtUser; private bool doChangeURL; private bool doReloadFiles; @@ -151,7 +185,7 @@ public string FileFilter { if (this.ViewState["FileFilter"] != null) { - return Convert.ToString(this.ViewState["FileFilter"]); + return Convert.ToString(this.ViewState["FileFilter"], CultureInfo.InvariantCulture); } else { @@ -175,7 +209,7 @@ public bool IncludeActiveTab { if (this.ViewState["IncludeActiveTab"] != null) { - return Convert.ToBoolean(this.ViewState["IncludeActiveTab"]); + return Convert.ToBoolean(this.ViewState["IncludeActiveTab"], CultureInfo.InvariantCulture); } else { @@ -223,7 +257,7 @@ public int ModuleID int myMid = -2; if (this.ViewState["ModuleId"] != null) { - myMid = Convert.ToInt32(this.ViewState["ModuleId"]); + myMid = Convert.ToInt32(this.ViewState["ModuleId"], CultureInfo.InvariantCulture); } else if (this.Request.QueryString["mid"] != null) { @@ -261,7 +295,7 @@ public bool Required { if (this.ViewState["Required"] != null) { - return Convert.ToBoolean(this.ViewState["Required"]); + return Convert.ToBoolean(this.ViewState["Required"], CultureInfo.InvariantCulture); } else { @@ -285,7 +319,7 @@ public bool ShowFiles { if (this.ViewState["ShowFiles"] != null) { - return Convert.ToBoolean(this.ViewState["ShowFiles"]); + return Convert.ToBoolean(this.ViewState["ShowFiles"], CultureInfo.InvariantCulture); } else { @@ -309,7 +343,7 @@ public bool ShowImages { if (this.ViewState["ShowImages"] != null) { - return Convert.ToBoolean(this.ViewState["ShowImages"]); + return Convert.ToBoolean(this.ViewState["ShowImages"], CultureInfo.InvariantCulture); } else { @@ -359,7 +393,7 @@ public bool ShowNone { if (this.ViewState["ShowNone"] != null) { - return Convert.ToBoolean(this.ViewState["ShowNone"]); + return Convert.ToBoolean(this.ViewState["ShowNone"], CultureInfo.InvariantCulture); } else { @@ -383,7 +417,7 @@ public bool ShowTabs { if (this.ViewState["ShowTabs"] != null) { - return Convert.ToBoolean(this.ViewState["ShowTabs"]); + return Convert.ToBoolean(this.ViewState["ShowTabs"], CultureInfo.InvariantCulture); } else { @@ -420,7 +454,7 @@ public bool ShowUpLoad { if (this.ViewState["ShowUpLoad"] != null) { - return Convert.ToBoolean(this.ViewState["ShowUpLoad"]); + return Convert.ToBoolean(this.ViewState["ShowUpLoad"], CultureInfo.InvariantCulture); } else { @@ -444,7 +478,7 @@ public bool ShowUrls { if (this.ViewState["ShowUrls"] != null) { - return Convert.ToBoolean(this.ViewState["ShowUrls"]); + return Convert.ToBoolean(this.ViewState["ShowUrls"], CultureInfo.InvariantCulture); } else { @@ -468,7 +502,7 @@ public bool ShowUsers { if (this.ViewState["ShowUsers"] != null) { - return Convert.ToBoolean(this.ViewState["ShowUsers"]); + return Convert.ToBoolean(this.ViewState["ShowUsers"], CultureInfo.InvariantCulture); } else { @@ -534,7 +568,7 @@ public string Url if (this.cboTabs.SelectedItem != null) { strTab = this.cboTabs.SelectedItem.Value; - if (Globals.NumberMatchRegex.IsMatch(strTab) && (Convert.ToInt32(strTab) >= 0)) + if (Globals.NumberMatchRegex.IsMatch(strTab) && (Convert.ToInt32(strTab, CultureInfo.InvariantCulture) >= 0)) { r = strTab; } @@ -594,7 +628,7 @@ public string UrlType { get { - return Convert.ToString(this.ViewState["UrlType"]); + return Convert.ToString(this.ViewState["UrlType"], CultureInfo.InvariantCulture); } set @@ -614,7 +648,7 @@ public string Width { get { - return Convert.ToString(this.ViewState["SkinControlWidth"]); + return Convert.ToString(this.ViewState["SkinControlWidth"], CultureInfo.InvariantCulture); } set @@ -667,7 +701,7 @@ protected override void OnLoad(EventArgs e) { if ((this.Request.QueryString["pid"] != null) && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) { - this.objPortal = PortalController.Instance.GetPortal(int.Parse(this.Request.QueryString["pid"])); + this.objPortal = PortalController.Instance.GetPortal(int.Parse(this.Request.QueryString["pid"], CultureInfo.InvariantCulture)); } else { @@ -738,6 +772,7 @@ protected override void OnPreRender(EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cboFolders_SelectedIndexChanged(object sender, EventArgs e) @@ -800,6 +835,7 @@ protected void cboFolders_SelectedIndexChanged(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdAdd_Click(object sender, EventArgs e) @@ -817,6 +853,7 @@ protected void cmdAdd_Click(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdCancel_Click(object sender, EventArgs e) @@ -834,6 +871,7 @@ protected void cmdCancel_Click(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdDelete_Click(object sender, EventArgs e) @@ -853,6 +891,7 @@ protected void cmdDelete_Click(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdSave_Click(object sender, EventArgs e) @@ -878,10 +917,10 @@ protected void cmdSave_Click(object sender, EventArgs e) parentFolderName += this.cboFolders.SelectedItem.Value; string strExtension = Path.GetExtension(this.txtFile.PostedFile.FileName).Replace(".", string.Empty); - if (!string.IsNullOrEmpty(this.FileFilter) && ("," + this.FileFilter.ToLowerInvariant()).IndexOf("," + strExtension.ToLowerInvariant()) == -1) + if (!string.IsNullOrEmpty(this.FileFilter) && !("," + this.FileFilter).Contains("," + strExtension, StringComparison.OrdinalIgnoreCase)) { // trying to upload a file not allowed for current filter - this.lblMessage.Text = string.Format(Localization.GetString("UploadError", this.LocalResourceFile), this.FileFilter, strExtension); + this.lblMessage.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("UploadError", this.LocalResourceFile), this.FileFilter, strExtension); this.ErrorRow.Visible = true; } else @@ -890,12 +929,12 @@ protected void cmdSave_Click(object sender, EventArgs e) var folderManager = FolderManager.Instance; var settings = PortalController.Instance.GetCurrentPortalSettings(); - var portalID = (settings.ActiveTab.ParentId == settings.SuperTabId) ? Null.NullInteger : settings.PortalId; + var portalId = (settings.ActiveTab.ParentId == settings.SuperTabId) ? Null.NullInteger : settings.PortalId; var fileName = Path.GetFileName(this.txtFile.PostedFile.FileName); - var folderPath = Globals.GetSubFolderPath(parentFolderName.Replace("/", "\\") + fileName, portalID); + var folderPath = Globals.GetSubFolderPath(parentFolderName.Replace("/", @"\") + fileName, portalId); - var folder = folderManager.GetFolder(portalID, folderPath); + var folder = folderManager.GetFolder(portalId, folderPath); this.ErrorRow.Visible = false; try @@ -904,22 +943,22 @@ protected void cmdSave_Click(object sender, EventArgs e) } catch (Services.FileSystem.PermissionsNotMetException) { - this.lblMessage.Text += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); + this.lblMessage.Text += "
    " + string.Format(CultureInfo.CurrentCulture, Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); this.ErrorRow.Visible = true; } catch (NoSpaceAvailableException) { - this.lblMessage.Text += "
    " + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); + this.lblMessage.Text += "
    " + string.Format(CultureInfo.CurrentCulture, Localization.GetString("DiskSpaceExceeded"), fileName); this.ErrorRow.Visible = true; } catch (InvalidFileExtensionException) { - this.lblMessage.Text += "
    " + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); + this.lblMessage.Text += "
    " + string.Format(CultureInfo.CurrentCulture, Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); this.ErrorRow.Visible = true; } catch (Exception) { - this.lblMessage.Text += "
    " + string.Format(Localization.GetString("SaveFileError"), fileName); + this.lblMessage.Text += "
    " + string.Format(CultureInfo.CurrentCulture, Localization.GetString("SaveFileError"), fileName); this.ErrorRow.Visible = true; } } @@ -938,7 +977,7 @@ protected void cmdSave_Click(object sender, EventArgs e) this.cboFiles.DataSource = this.GetFileList(false); this.cboFiles.DataBind(); - string fileName1 = this.txtFile.PostedFile.FileName.Substring(this.txtFile.PostedFile.FileName.LastIndexOf("\\") + 1); + string fileName1 = this.txtFile.PostedFile.FileName.Substring(this.txtFile.PostedFile.FileName.LastIndexOf(@"\", StringComparison.Ordinal) + 1); if (this.cboFiles.Items.FindByText(fileName1) != null) { this.cboFiles.Items.FindByText(fileName1).Selected = true; @@ -962,6 +1001,7 @@ protected void cmdSave_Click(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdSelect_Click(object sender, EventArgs e) @@ -986,6 +1026,7 @@ protected void cmdSelect_Click(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void cmdUpload_Click(object sender, EventArgs e) @@ -1035,6 +1076,7 @@ protected void cmdUpload_Click(object sender, EventArgs e) } [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected void optType_SelectedIndexChanged(object sender, EventArgs e) @@ -1120,8 +1162,8 @@ private void SetStorageLocationType() private void DoChangeURL() { - string url = Convert.ToString(this.ViewState["Url"]); - string urltype = Convert.ToString(this.ViewState["UrlType"]); + string url = Convert.ToString(this.ViewState["Url"], CultureInfo.InvariantCulture); + string urltype = Convert.ToString(this.ViewState["UrlType"], CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(url)) { var objUrls = new UrlController(); @@ -1139,7 +1181,7 @@ private void DoChangeURL() if (url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) { trackingUrl = url; - var objFile = FileManager.Instance.GetFile(int.Parse(url.Substring(7))); + var objFile = FileManager.Instance.GetFile(int.Parse(url.Substring(7), CultureInfo.InvariantCulture)); if (objFile != null) { url = objFile.Folder + objFile.FileName; @@ -1149,7 +1191,7 @@ private void DoChangeURL() { // to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(url); - var folderPath = url.Substring(0, url.LastIndexOf(fileName)); + var folderPath = url.Substring(0, url.LastIndexOf(fileName, StringComparison.OrdinalIgnoreCase)); var folder = FolderManager.Instance.GetFolder(this.objPortal.PortalID, folderPath); var fileId = -1; if (folder != null) @@ -1161,7 +1203,7 @@ private void DoChangeURL() } } - trackingUrl = "FileID=" + fileId.ToString(); + trackingUrl = "FileID=" + fileId.ToString(CultureInfo.InvariantCulture); } } @@ -1169,7 +1211,7 @@ private void DoChangeURL() { if (url.StartsWith("userid=", StringComparison.InvariantCultureIgnoreCase)) { - UserInfo objUser = UserController.GetUserById(this.objPortal.PortalID, int.Parse(url.Substring(7))); + UserInfo objUser = UserController.GetUserById(this.objPortal.PortalID, int.Parse(url.Substring(7), CultureInfo.InvariantCulture)); if (objUser != null) { url = objUser.Username; @@ -1355,7 +1397,7 @@ private void DoRenderTypes() private void DoCorrectRadioButtonList() { - string urltype = Convert.ToString(this.ViewState["UrlType"]); + string urltype = Convert.ToString(this.ViewState["UrlType"], CultureInfo.InvariantCulture); if (this.optType.Items.Count > 0) { @@ -1384,8 +1426,8 @@ private void DoCorrectRadioButtonList() private void DoRenderTypeControls() { - string url = Convert.ToString(this.ViewState["Url"]); - string urltype = Convert.ToString(this.ViewState["UrlType"]); + string url = Convert.ToString(this.ViewState["Url"], CultureInfo.InvariantCulture); + string urltype = Convert.ToString(this.ViewState["UrlType"], CultureInfo.InvariantCulture); var objUrls = new UrlController(); if (!string.IsNullOrEmpty(urltype)) { @@ -1412,14 +1454,11 @@ private void DoRenderTypeControls() foreach (string strImage in Directory.GetFiles(strImagesFolder)) { string img = strImage.Replace(strImagesFolder, string.Empty).Trim('/').Trim('\\'); - this.cboImages.Items.Add(new ListItem(img, string.Format("~/{0}/{1}", this.PortalSettings.DefaultIconLocation, img).ToLowerInvariant())); + this.cboImages.Items.Add(new ListItem(img, $"~/{this.PortalSettings.DefaultIconLocation}/{img}".ToLowerInvariant())); } - ListItem selecteItem = this.cboImages.Items.FindByValue(url.ToLowerInvariant()); - if (selecteItem != null) - { - selecteItem.Selected = true; - } + var selectedItem = this.cboImages.Items.FindByValue(url.ToLowerInvariant()); + selectedItem?.Selected = true; break; @@ -1464,9 +1503,9 @@ private void DoRenderTypeControls() this.cboTabs.Items.FindByValue(url).Selected = true; } - if (!this.IncludeActiveTab && this.cboTabs.Items.FindByValue(settings.ActiveTab.TabID.ToString()) != null) + if (!this.IncludeActiveTab && this.cboTabs.Items.FindByValue(settings.ActiveTab.TabID.ToString(CultureInfo.InvariantCulture)) != null) { - this.cboTabs.Items.FindByValue(settings.ActiveTab.TabID.ToString()).Attributes.Add("disabled", "disabled"); + this.cboTabs.Items.FindByValue(settings.ActiveTab.TabID.ToString(CultureInfo.InvariantCulture)).Attributes.Add("disabled", "disabled"); } break; @@ -1502,18 +1541,18 @@ private void DoRenderTypeControls() // Let's try to remember last selection if (this.ViewState["LastFolderPath"] != null) { - lastFolderPath = Convert.ToString(this.ViewState["LastFolderPath"]); + lastFolderPath = Convert.ToString(this.ViewState["LastFolderPath"], CultureInfo.InvariantCulture); } if (this.ViewState["LastFileName"] != null) { - lastFileName = Convert.ToString(this.ViewState["LastFileName"]); + lastFileName = Convert.ToString(this.ViewState["LastFileName"], CultureInfo.InvariantCulture); } if (url != string.Empty) { // Let's use the new URL - fileName = url.Substring(url.LastIndexOf("/") + 1); + fileName = url.Substring(url.LastIndexOf("/", StringComparison.Ordinal) + 1); folderPath = url.Replace(fileName, string.Empty); } else diff --git a/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs b/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs index f8c63034294..d8277bb43ea 100644 --- a/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs +++ b/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.UserControls { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Web.UI.WebControls; @@ -23,58 +24,81 @@ public abstract class URLTrackingControl : UserControlBase // ReSharper disable InconsistentNaming [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label Label1; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label Label2; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label Label3; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label Label4; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label Label5; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label Label6; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label Label7; // ReSharper restore InconsistentNaming [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdDisplay; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HyperLink cmdEndCalendar; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HyperLink cmdStartCalendar; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected DataGrid grdLog; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblClicks; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblCreatedDate; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblLastClick; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblLogURL; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblTrackingURL; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblURL; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel pnlLog; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel pnlTrack; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtEndDate; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtStartDate; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CompareValidator valEndDate; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CompareValidator valStartDate; private int moduleID = -2; @@ -143,7 +167,7 @@ protected override void OnLoad(EventArgs e) try { - // this needs to execute always to the client script code is registred in InvokePopupCal + // this needs to execute always to the client script code is registered in InvokePopupCal this.cmdStartCalendar.NavigateUrl = Calendar.InvokePopupCal(this.txtStartDate); this.cmdEndCalendar.NavigateUrl = Calendar.InvokePopupCal(this.txtEndDate); if (!this.Page.IsPostBack) @@ -152,12 +176,12 @@ protected override void OnLoad(EventArgs e) { this.lblLogURL.Text = this.URL; // saved for loading Log grid TabType urlType = Globals.GetURLType(this.URL); - if (urlType == TabType.File && this.URL.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase) == false) + if (urlType == TabType.File && !this.URL.StartsWith("fileid=", StringComparison.OrdinalIgnoreCase)) { // to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(this.URL); - var folderPath = this.URL.Substring(0, this.URL.LastIndexOf(fileName)); + var folderPath = this.URL.Substring(0, this.URL.LastIndexOf(fileName, StringComparison.OrdinalIgnoreCase)); var folder = FolderManager.Instance.GetFolder(this.PortalSettings.PortalId, folderPath); var file = FileManager.Instance.GetFile(folder, fileName); @@ -172,7 +196,7 @@ protected override void OnLoad(EventArgs e) if (string.IsNullOrEmpty(this.FormattedURL)) { this.lblURL.Text = Globals.LinkClick(this.URL, this.PortalSettings.ActiveTab.TabID, this.ModuleID, false); - if (!this.lblURL.Text.StartsWith("http") && !this.lblURL.Text.StartsWith("mailto")) + if (!this.lblURL.Text.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !this.lblURL.Text.StartsWith("mailto", StringComparison.OrdinalIgnoreCase)) { this.lblURL.Text = Globals.AddHTTP(this.Request.Url.Host) + this.lblURL.Text; } @@ -182,14 +206,14 @@ protected override void OnLoad(EventArgs e) this.lblURL.Text = this.FormattedURL; } - this.lblCreatedDate.Text = objUrlTracking.CreatedDate.ToString(); + this.lblCreatedDate.Text = objUrlTracking.CreatedDate.ToString(CultureInfo.CurrentCulture); if (objUrlTracking.TrackClicks) { this.pnlTrack.Visible = true; if (string.IsNullOrEmpty(this.TrackingURL)) { - if (!this.URL.StartsWith("http")) + if (!this.URL.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { this.lblTrackingURL.Text = Globals.AddHTTP(this.Request.Url.Host); } @@ -201,10 +225,10 @@ protected override void OnLoad(EventArgs e) this.lblTrackingURL.Text = this.TrackingURL; } - this.lblClicks.Text = objUrlTracking.Clicks.ToString(); + this.lblClicks.Text = objUrlTracking.Clicks.ToString(CultureInfo.CurrentCulture); if (!Null.IsNull(objUrlTracking.LastClick)) { - this.lblLastClick.Text = objUrlTracking.LastClick.ToString(); + this.lblLastClick.Text = objUrlTracking.LastClick.ToString(CultureInfo.CurrentCulture); } } @@ -249,7 +273,12 @@ private void CmdDisplay_Click(object sender, EventArgs e) // localize datagrid Localization.LocalizeDataGrid(ref this.grdLog, this.LocalResourceFile); - this.grdLog.DataSource = objUrls.GetUrlLog(this.PortalSettings.PortalId, this.lblLogURL.Text, this.ModuleID, Convert.ToDateTime(strStartDate), Convert.ToDateTime(strEndDate)); + this.grdLog.DataSource = objUrls.GetUrlLog( + this.PortalSettings.PortalId, + this.lblLogURL.Text, + this.ModuleID, + Convert.ToDateTime(strStartDate, CultureInfo.CurrentCulture), + Convert.ToDateTime(strEndDate, CultureInfo.CurrentCulture)); this.grdLog.DataBind(); } catch (Exception exc) diff --git a/DNN Platform/Library/UI/UserControls/User.cs b/DNN Platform/Library/UI/UserControls/User.cs index 5f4a4fdec2a..f3ab3d7f684 100644 --- a/DNN Platform/Library/UI/UserControls/User.cs +++ b/DNN Platform/Library/UI/UserControls/User.cs @@ -18,67 +18,95 @@ public abstract class User : UserControlBase { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected HtmlTableRow ConfirmPasswordRow; [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected HtmlTableRow PasswordRow; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblUsername; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblUsernameAsterisk; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plConfirm; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plEmail; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plFirstName; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plIM; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plLastName; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plPassword; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plUserName; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LabelControl plWebsite; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtConfirm; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtEmail; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtFirstName; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtIM; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtLastName; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtPassword; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtUsername; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TextBox txtWebsite; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valConfirm1; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected CompareValidator valConfirm2; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valEmail1; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RegularExpressionValidator valEmail2; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valFirstName; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valLastName; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valPassword; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected RequiredFieldValidator valUsername; private string myFileName = "User.ascx"; private string confirm; @@ -107,7 +135,7 @@ public int ModuleId { get { - return Convert.ToInt32(this.ViewState["ModuleId"]); + return Convert.ToInt32(this.ViewState["ModuleId"], CultureInfo.InvariantCulture); } set @@ -120,7 +148,7 @@ public string LabelColumnWidth { get { - return Convert.ToString(this.ViewState["LabelColumnWidth"]); + return Convert.ToString(this.ViewState["LabelColumnWidth"], CultureInfo.InvariantCulture); } set @@ -133,7 +161,7 @@ public string ControlColumnWidth { get { - return Convert.ToString(this.ViewState["ControlColumnWidth"]); + return Convert.ToString(this.ViewState["ControlColumnWidth"], CultureInfo.InvariantCulture); } set @@ -325,7 +353,7 @@ protected override void OnLoad(EventArgs e) this.ConfirmPasswordRow.Visible = true; } - this.ViewState["ModuleId"] = Convert.ToString(this.ModuleId); + this.ViewState["ModuleId"] = Convert.ToString(this.ModuleId, CultureInfo.InvariantCulture); this.ViewState["LabelColumnWidth"] = this.LabelColumnWidth; this.ViewState["ControlColumnWidth"] = this.ControlColumnWidth; } diff --git a/DNN Platform/Library/UI/Utilities/DNNClientAPI.cs b/DNN Platform/Library/UI/Utilities/DNNClientAPI.cs index 8eec3a614f2..fb173b1a1a7 100644 --- a/DNN Platform/Library/UI/Utilities/DNNClientAPI.cs +++ b/DNN Platform/Library/UI/Utilities/DNNClientAPI.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.Utilities { using System; using System.Collections; + using System.Globalization; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; @@ -185,7 +186,7 @@ public static void EnableMinMax(Control objButton, Control objContent, int intMo if (intModuleId != -1) { AddAttribute(objButton, "onclick", "if (__dnn_ContainerMaxMin_OnClick(this, '" + objContent.ClientID + "')) return false;"); - ClientAPI.RegisterClientVariable(objButton.Page, "containerid_" + objContent.ClientID, intModuleId.ToString(), true); + ClientAPI.RegisterClientVariable(objButton.Page, "containerid_" + objContent.ClientID, intModuleId.ToString(CultureInfo.InvariantCulture), true); ClientAPI.RegisterClientVariable(objButton.Page, "cookieid_" + objContent.ClientID, "_Module" + intModuleId + "_Visible", true); ClientAPI.RegisterClientVariable(objButton.Page, "min_icon_" + intModuleId, strMinIconLoc, true); @@ -255,7 +256,7 @@ public static void EnableMinMax(Control objButton, Control objContent, int intMo if (intAnimationFrames != 5) { - ClientAPI.RegisterClientVariable(objButton.Page, "animf_" + objContent.ClientID, intAnimationFrames.ToString(), true); + ClientAPI.RegisterClientVariable(objButton.Page, "animf_" + objContent.ClientID, intAnimationFrames.ToString(CultureInfo.InvariantCulture), true); } } @@ -305,7 +306,7 @@ public static bool MinMaxContentVisibile(Control objButton, int intModuleId, boo } case MinMaxPersistanceType.Personalization: - string strVisible = Convert.ToString(Personalization.GetProfile(Globals.GetAttribute(objButton, "userctr"), Globals.GetAttribute(objButton, "userkey"))); + string strVisible = Convert.ToString(Personalization.GetProfile(Globals.GetAttribute(objButton, "userctr"), Globals.GetAttribute(objButton, "userkey")), CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(strVisible)) { return blnDefaultMin; @@ -330,7 +331,7 @@ public static void MinMaxContentVisibile(Control objButton, int intModuleId, boo switch (ePersistanceType) { case MinMaxPersistanceType.Page: - ClientAPI.RegisterClientVariable(objButton.Page, objButton.ClientID + ":exp", Convert.ToInt32(value).ToString(), true); + ClientAPI.RegisterClientVariable(objButton.Page, objButton.ClientID + ":exp", Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture), true); break; case MinMaxPersistanceType.Cookie: var objModuleVisible = new HttpCookie("_Module" + intModuleId + "_Visible", value.ToString().ToLowerInvariant()) diff --git a/DNN Platform/Library/UI/WebControls/CaptchaControl.cs b/DNN Platform/Library/UI/WebControls/CaptchaControl.cs index be850aa8064..7c5fb257d4c 100644 --- a/DNN Platform/Library/UI/WebControls/CaptchaControl.cs +++ b/DNN Platform/Library/UI/WebControls/CaptchaControl.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.UI.WebControls using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; + using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Web; @@ -225,7 +226,7 @@ public void RaisePostDataChangedEvent() /// if the data is valid, otherwise . public bool Validate(string userData) { - var cacheKey = string.Format(DataCache.CaptchaCacheKey, userData); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.CaptchaCacheKey, userData); var cacheObj = DataCache.GetCache(cacheKey); if (cacheObj == null) @@ -325,7 +326,7 @@ protected virtual string GetNextCaptcha() // the request might go to another server in the farm. Also, in a system // with a single server or web-farm, the cache might be cleared // which will cause a problem in such case unless sticky sessions are used. - var cacheKey = string.Format(DataCache.CaptchaCacheKey, challenge); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.CaptchaCacheKey, challenge); DataCache.SetCache( cacheKey, challenge, @@ -354,11 +355,11 @@ protected override void LoadViewState(object savedState) // Load the CAPTCHA Text from the ViewState if (myState[1] != null) { - this.captchaText = Convert.ToString(myState[1]); + this.captchaText = Convert.ToString(myState[1], CultureInfo.InvariantCulture); } } - // var cacheKey = string.Format(DataCache.CaptchaCacheKey, masterPortalId); + // var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.CaptchaCacheKey, masterPortalId); // _CaptchaText } @@ -424,7 +425,7 @@ protected override void Render(HtmlTextWriter writer) this.TextBoxStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Style, "width:" + this.Width); - writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.captchaText.Length.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.captchaText.Length.ToString(CultureInfo.InvariantCulture)); writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); if (!string.IsNullOrEmpty(this.AccessKey)) { @@ -438,7 +439,7 @@ protected override void Render(HtmlTextWriter writer) if (this.TabIndex > 0) { - writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, this.TabIndex.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, this.TabIndex.ToString(CultureInfo.InvariantCulture)); } if (this.userText == this.captchaText) @@ -598,7 +599,7 @@ private static GraphicsPath CreateText(string text, int width, int height, Graph charPath.AddString( c.ToString(), f.FontFamily, - Convert.ToInt32(f.Style), + (int)f.Style, f.Size, new PointF(charX, yOffset), new StringFormat()); diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs index c1faf73dc89..3e11abf50ac 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; @@ -107,7 +108,7 @@ private void Item_DataBinding(object sender, EventArgs e) } else { - box.Checked = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.DataField)); + box.Checked = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.DataField), CultureInfo.InvariantCulture); } } else @@ -123,7 +124,7 @@ private void Item_DataBinding(object sender, EventArgs e) } else { - box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.EnabledField)); + box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.EnabledField), CultureInfo.InvariantCulture); } } else diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs index 1b9b59b2def..bdabe2e55cf 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs @@ -3,8 +3,10 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Diagnostics.CodeAnalysis; using System.Web.UI.WebControls; + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public delegate void DNNDataGridCheckedColumnEventHandler(object sender, DNNDataGridCheckChangedEventArgs e); /// diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs index f3106784415..dc0366de51f 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; @@ -210,7 +211,7 @@ private void Item_DataBinding(object sender, EventArgs e) } else { - box.SelectedStateKey = Convert.ToString(DataBinder.Eval(container.DataItem, this.DataField)); + box.SelectedStateKey = Convert.ToString(DataBinder.Eval(container.DataItem, this.DataField), CultureInfo.InvariantCulture); } } else @@ -226,7 +227,7 @@ private void Item_DataBinding(object sender, EventArgs e) } else { - box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.EnabledField)); + box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.EnabledField), CultureInfo.InvariantCulture); } } else diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs index 018a2b9d30c..2aee39ecc7e 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; @@ -175,7 +176,7 @@ private bool GetIsVisible(DataGridItem container) bool isVisible; if (!string.IsNullOrEmpty(this.VisibleField)) { - isVisible = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.VisibleField)); + isVisible = Convert.ToBoolean(DataBinder.Eval(container.DataItem, this.VisibleField), CultureInfo.InvariantCulture); } else { @@ -192,7 +193,7 @@ private int GetValue(DataGridItem container) int keyValue = Null.NullInteger; if (!string.IsNullOrEmpty(this.KeyField)) { - keyValue = Convert.ToInt32(DataBinder.Eval(container.DataItem, this.KeyField)); + keyValue = Convert.ToInt32(DataBinder.Eval(container.DataItem, this.KeyField), CultureInfo.InvariantCulture); } return keyValue; @@ -212,11 +213,11 @@ private void Item_DataBinding(object sender, EventArgs e) keyValue = this.GetValue(container); if (!string.IsNullOrEmpty(this.NavigateURLFormatString)) { - hypLink.NavigateUrl = string.Format(this.NavigateURLFormatString, keyValue); + hypLink.NavigateUrl = string.Format(CultureInfo.InvariantCulture, this.NavigateURLFormatString, keyValue); } else { - hypLink.NavigateUrl = keyValue.ToString(); + hypLink.NavigateUrl = keyValue.ToString(CultureInfo.InvariantCulture); } } else @@ -227,7 +228,7 @@ private void Item_DataBinding(object sender, EventArgs e) var colIcon = (ImageButton)sender; container = (DataGridItem)colIcon.NamingContainer; keyValue = this.GetValue(container); - colIcon.CommandArgument = keyValue.ToString(); + colIcon.CommandArgument = keyValue.ToString(CultureInfo.InvariantCulture); colIcon.Visible = this.GetIsVisible(container); } @@ -237,7 +238,7 @@ private void Item_DataBinding(object sender, EventArgs e) var colLink = (LinkButton)sender; container = (DataGridItem)colLink.NamingContainer; keyValue = this.GetValue(container); - colLink.CommandArgument = keyValue.ToString(); + colLink.CommandArgument = keyValue.ToString(CultureInfo.InvariantCulture); colLink.Visible = this.GetIsVisible(container); } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs index d48e22f1f9e..63b05c9ffb0 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs @@ -68,22 +68,17 @@ public static string GetInitScript(Control ctl) { LookupScriptValues(ctl, out var grantImagePath, out var denyImagePath, out var nullImagePath, out _, out var grantAltText, out var denyAltText, out var nullAltText); - return string.Format( - @"jQuery(document).ready( - function() {{ - var images = {{ 'True': '{0}', 'False': '{1}', 'Null': '{2}' }}; - var toolTips = {{ 'True': '{3}', 'False': '{4}', 'Null': '{5}' }}; - var tsm = dnn.controls.triStateManager(images, toolTips); - jQuery('.tristate').each( function(i, elem) {{ - tsm.initControl( elem ); - }}); - }});", - HttpUtility.JavaScriptStringEncode(grantImagePath), - HttpUtility.JavaScriptStringEncode(denyImagePath), - HttpUtility.JavaScriptStringEncode(nullImagePath), - HttpUtility.JavaScriptStringEncode(grantAltText), - HttpUtility.JavaScriptStringEncode(denyAltText), - HttpUtility.JavaScriptStringEncode(nullAltText)); + return $$""" + jQuery(document).ready( + function() { + var images = { 'True': '{{HttpUtility.JavaScriptStringEncode(grantImagePath)}}', 'False': '{{HttpUtility.JavaScriptStringEncode(denyImagePath)}}', 'Null': '{{HttpUtility.JavaScriptStringEncode(nullImagePath)}}' }; + var toolTips = { 'True': '{{HttpUtility.JavaScriptStringEncode(grantAltText)}}', 'False': '{{HttpUtility.JavaScriptStringEncode(denyAltText)}}', 'Null': '{{HttpUtility.JavaScriptStringEncode(nullAltText)}}' }; + var tsm = dnn.controls.triStateManager(images, toolTips); + jQuery('.tristate').each( function(i, elem) { + tsm.initControl( elem ); + }); + }); + """; } /// diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs b/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs index 23fdc3e8a33..2b440c8b102 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs @@ -145,7 +145,7 @@ public ArrayList SelectedRoleNames /// Gets or sets the ResourceFile to localize permissions. public string ResourceFile { get; set; } - /// Gets or sets a value indicating whether enable ShowAllUsers to display the virtuell "Unauthenticated Users" role. + /// Gets or sets a value indicating whether enable ShowAllUsers to display the virtual "Unauthenticated Users" role. public bool ShowUnauthenticatedUsers { get @@ -155,7 +155,7 @@ public bool ShowUnauthenticatedUsers return false; } - return Convert.ToBoolean(this.ViewState["ShowUnauthenticatedUsers"]); + return Convert.ToBoolean(this.ViewState["ShowUnauthenticatedUsers"], CultureInfo.InvariantCulture); } set @@ -164,7 +164,7 @@ public bool ShowUnauthenticatedUsers } } - /// Gets or sets a value indicating whether enable ShowAllUsers to display the virtuell "All Users" role. + /// Gets or sets a value indicating whether enable ShowAllUsers to display the virtual "All Users" role. public bool ShowAllUsers { get @@ -174,7 +174,7 @@ public bool ShowAllUsers return false; } - return Convert.ToBoolean(this.ViewState["ShowAllUsers"]); + return Convert.ToBoolean(this.ViewState["ShowAllUsers"], CultureInfo.InvariantCulture); } set @@ -222,7 +222,7 @@ protected override void LoadViewState(object savedState) // Load TabPermissions if (myState[1] != null) { - string state = Convert.ToString(myState[1]); + string state = Convert.ToString(myState[1], CultureInfo.InvariantCulture); this.CurrentRoleSelection = state != string.Empty ? new List(state.Split(RoleSeparator, StringSplitOptions.None)) : new List(); @@ -414,25 +414,25 @@ private bool GetSelection(string roleName) private void GetRoles() { int roleGroupId = -2; - if ((this.cboRoleGroups != null) && (this.cboRoleGroups.SelectedValue != null)) + if (this.cboRoleGroups is { SelectedValue: not null, }) { - roleGroupId = int.Parse(this.cboRoleGroups.SelectedValue); + roleGroupId = int.Parse(this.cboRoleGroups.SelectedValue, CultureInfo.InvariantCulture); } this.roles = roleGroupId > -2 - ? RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentPortalSettings().PortalId, r => r.RoleGroupID == roleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved) - : RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentPortalSettings().PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved); + ? RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentSettings().PortalId, r => r.RoleGroupID == roleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved) + : RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentSettings().PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved); if (roleGroupId < 0) { if (this.ShowUnauthenticatedUsers) { - this.roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleUnauthUser), RoleName = Globals.glbRoleUnauthUserName }); + this.roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleUnauthUser, CultureInfo.InvariantCulture), RoleName = Globals.glbRoleUnauthUserName }); } if (this.ShowAllUsers) { - this.roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleAllUsers), RoleName = Globals.glbRoleAllUsersName }); + this.roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture), RoleName = Globals.glbRoleAllUsersName }); } } diff --git a/DNN Platform/Library/UI/WebControls/DualListBox.cs b/DNN Platform/Library/UI/WebControls/DualListBox.cs index de9fbc17ba9..2ea38bd4df3 100644 --- a/DNN Platform/Library/UI/WebControls/DualListBox.cs +++ b/DNN Platform/Library/UI/WebControls/DualListBox.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.UI.WebControls using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; + using System.Globalization; using System.Reflection; using System.Web.UI; using System.Web.UI.WebControls; @@ -321,11 +322,11 @@ private NameValueCollection GetList(string listType, object dataSource) { foreach (object item in dataList) { - BindingFlags bindings = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; + const BindingFlags bindings = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; PropertyInfo objTextProperty = item.GetType().GetProperty(this.DataTextField, bindings); PropertyInfo objValueProperty = item.GetType().GetProperty(this.DataValueField, bindings); - string objValue = Convert.ToString(objValueProperty.GetValue(item, null)); - string objText = Convert.ToString(objTextProperty.GetValue(item, null)); + string objValue = Convert.ToString(objValueProperty.GetValue(item, null), CultureInfo.InvariantCulture); + string objText = Convert.ToString(objTextProperty.GetValue(item, null), CultureInfo.InvariantCulture); list.Add(objText, objValue); } @@ -337,7 +338,7 @@ private NameValueCollection GetList(string listType, object dataSource) private void RenderButton(string buttonType, HtmlTextWriter writer) { string buttonText = Null.NullString; - string imageURL = Null.NullString; + string imageUrl = Null.NullString; // Begin Button Row writer.RenderBeginTag(HtmlTextWriterTag.Tr); @@ -350,25 +351,25 @@ private void RenderButton(string buttonType, HtmlTextWriter writer) buttonText = string.IsNullOrEmpty(this.AddKey) ? this.AddText : Localization.GetString(this.AddKey, this.LocalResourceFile); - imageURL = this.AddImageURL; + imageUrl = this.AddImageURL; break; case "AddAll": buttonText = string.IsNullOrEmpty(this.AddAllKey) ? this.AddAllText : Localization.GetString(this.AddAllKey, this.LocalResourceFile); - imageURL = this.AddAllImageURL; + imageUrl = this.AddAllImageURL; break; case "Remove": buttonText = string.IsNullOrEmpty(this.RemoveKey) ? this.RemoveText : Localization.GetString(this.RemoveKey, this.LocalResourceFile); - imageURL = this.RemoveImageURL; + imageUrl = this.RemoveImageURL; break; case "RemoveAll": buttonText = string.IsNullOrEmpty(this.RemoveAllKey) ? this.RemoveAllText : Localization.GetString(this.RemoveAllKey, this.LocalResourceFile); - imageURL = this.RemoveAllImageURL; + imageUrl = this.RemoveAllImageURL; break; } @@ -378,9 +379,9 @@ private void RenderButton(string buttonType, HtmlTextWriter writer) writer.RenderBeginTag(HtmlTextWriterTag.A); // Render Image - if (!string.IsNullOrEmpty(imageURL)) + if (!string.IsNullOrEmpty(imageUrl)) { - writer.AddAttribute(HtmlTextWriterAttribute.Src, this.ResolveClientUrl(imageURL)); + writer.AddAttribute(HtmlTextWriterAttribute.Src, this.ResolveClientUrl(imageUrl)); writer.AddAttribute(HtmlTextWriterAttribute.Title, buttonText); writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); writer.RenderBeginTag(HtmlTextWriterTag.Img); diff --git a/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventHandler.cs b/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventHandler.cs index 076f2ed7ec1..272bf6dda78 100644 --- a/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventHandler.cs +++ b/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventHandler.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.WebControls -{ - public delegate void DualListBoxEventHandler(object sender, DualListBoxEventArgs e); -} +namespace DotNetNuke.UI.WebControls; + +using System.Diagnostics.CodeAnalysis; + +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] +public delegate void DualListBoxEventHandler(object sender, DualListBoxEventArgs e); diff --git a/DNN Platform/Library/UI/WebControls/LanguageSelector.cs b/DNN Platform/Library/UI/WebControls/LanguageSelector.cs index eb831deb848..a5f7ad0cf09 100644 --- a/DNN Platform/Library/UI/WebControls/LanguageSelector.cs +++ b/DNN Platform/Library/UI/WebControls/LanguageSelector.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.WebControls { using System; using System.Collections; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Web.UI; using System.Web.UI.HtmlControls; @@ -43,9 +44,10 @@ public enum LanguageListDirection public enum LanguageSelectionMode { /// Multiple select. - Multiple = 1, - + Multiple = 1, + /// Single select. + [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Breaking change")] Single = 2, } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs index 730c148841d..34b49841d85 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs @@ -3,12 +3,21 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; using System.Collections; + using System.Collections.Generic; using System.Web.UI; /// A collection of PageHierarchyData objects. - public class NavDataPageHierarchicalEnumerable : ArrayList, IHierarchicalEnumerable + public class NavDataPageHierarchicalEnumerable : ArrayList, IHierarchicalEnumerable, IList { + /// + NavDataPageHierarchyData IList.this[int index] + { + get => (NavDataPageHierarchyData)this[index]; + set => this[index] = value; + } + /// Handles enumeration. /// THe item. /// . @@ -16,5 +25,56 @@ public virtual IHierarchyData GetHierarchyData(object enumeratedItem) { return (IHierarchyData)enumeratedItem; } + + /// + public void Add(NavDataPageHierarchyData item) => base.Add(item); + + /// + public bool Contains(NavDataPageHierarchyData item) => base.Contains(item); + + /// + public void CopyTo(NavDataPageHierarchyData[] array, int arrayIndex) => base.CopyTo(array, arrayIndex); + + /// + public bool Remove(NavDataPageHierarchyData item) + { + if (!this.Contains(item)) + { + return false; + } + + base.Remove(item); + return true; + } + + /// + public int IndexOf(NavDataPageHierarchyData item) => base.IndexOf(item); + + /// + public void Insert(int index, NavDataPageHierarchyData item) => base.Insert(index, item); + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return new NavDataPageHierarchyDataEnumerator(this.GetEnumerator()); + } + + private class NavDataPageHierarchyDataEnumerator(IEnumerator enumerator) : IEnumerator + { + /// + public NavDataPageHierarchyData Current => (NavDataPageHierarchyData)enumerator.Current; + + /// + object IEnumerator.Current => this.Current; + + /// + public void Dispose() => (enumerator as IDisposable)?.Dispose(); + + /// + public bool MoveNext() => enumerator.MoveNext(); + + /// + public void Reset() => enumerator.Reset(); + } } } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs index 6c5e6e4002c..2e8d931c01b 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; using System.Web.UI; using DotNetNuke.Entities.Portals; @@ -24,13 +25,13 @@ public virtual string ImageUrl { get { - if (string.IsNullOrEmpty(this.objNode.Image) || this.objNode.Image.StartsWith("/")) + if (string.IsNullOrEmpty(this.objNode.Image) || this.objNode.Image.StartsWith("/", StringComparison.Ordinal)) { return this.objNode.Image; } else { - return PortalController.Instance.GetCurrentPortalSettings().HomeDirectory + this.objNode.Image; + return PortalController.Instance.GetCurrentSettings().HomeDirectory + this.objNode.Image; } } } @@ -134,7 +135,7 @@ private static string GetValuePath(DNNNode objNode) break; } - strPath = GetSafeValue(objParent.Key, string.Empty) + "\\" + strPath; + strPath = GetSafeValue(objParent.Key, string.Empty) + @"\" + strPath; objParent = objParent.ParentNode; } while (true); diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs index ab68622a473..b96bd49c028 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs @@ -3,13 +3,13 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; using System.Web.UI; /// The NavDataSourceView class encapsulates the capabilities of the NavDataSource data source control. public class NavDataSourceView : HierarchicalDataSourceView { private readonly string sKey; - private string sNamespace = "MyNS"; /// Initializes a new instance of the class. /// The view path by which to filter nav nodes. @@ -19,9 +19,9 @@ public NavDataSourceView(string viewPath) { this.sKey = string.Empty; } - else if (viewPath.IndexOf("\\") > -1) + else if (viewPath.IndexOf(@"\", StringComparison.Ordinal) > -1) { - this.sKey = viewPath.Substring(viewPath.LastIndexOf("\\") + 1); + this.sKey = viewPath.Substring(viewPath.LastIndexOf(@"\", StringComparison.Ordinal) + 1); } else { @@ -29,18 +29,7 @@ public NavDataSourceView(string viewPath) } } - public string Namespace - { - get - { - return this.sNamespace; - } - - set - { - this.sNamespace = value; - } - } + public string Namespace { get; set; } = "MyNS"; /// /// Starting with the rootNode, recursively build a list of @@ -53,7 +42,7 @@ public override IHierarchicalEnumerable Select() { var objPages = new NavDataPageHierarchicalEnumerable(); DNNNodeCollection objNodes; - objNodes = Navigation.GetNavigationNodes(this.sNamespace); + objNodes = Navigation.GetNavigationNodes(this.Namespace); if (!string.IsNullOrEmpty(this.sKey)) { objNodes = objNodes.FindNodeByKey(this.sKey).DNNNodes; diff --git a/DNN Platform/Library/UI/WebControls/PagingControl.cs b/DNN Platform/Library/UI/WebControls/PagingControl.cs index 3091536c205..90fb39115e3 100644 --- a/DNN Platform/Library/UI/WebControls/PagingControl.cs +++ b/DNN Platform/Library/UI/WebControls/PagingControl.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.UI.WebControls using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Text; using System.Web.UI; @@ -20,15 +21,19 @@ public class PagingControl : WebControl, IPostBackEventHandler { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Breaking Change")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] // ReSharper disable once InconsistentNaming protected Repeater PageNumbers; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TableCell cellDisplayLinks; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected TableCell cellDisplayStatus; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Table tablePageNumbers; private int totalPages = -1; private string cssClassLinkActive; @@ -127,8 +132,8 @@ public PagingControlMode Mode /// public void RaisePostBackEvent(string eventArgument) { - this.CurrentPage = int.Parse(eventArgument.Replace("Page_", string.Empty)); - this.OnPageChanged(new EventArgs()); + this.CurrentPage = int.Parse(eventArgument.Replace("Page_", string.Empty), CultureInfo.InvariantCulture); + this.OnPageChanged(EventArgs.Empty); } /// @@ -158,7 +163,7 @@ protected override void CreateChildControls() intTotalPages = 1; } - var str = string.Format(Localization.GetString("Pages"), this.CurrentPage, intTotalPages); + var str = string.Format(CultureInfo.CurrentCulture, Localization.GetString("Pages"), this.CurrentPage, intTotalPages); var lit = new LiteralControl(str); this.cellDisplayStatus.Controls.Add(lit); this.tablePageNumbers.Rows[intRowIndex].Cells.Add(this.cellDisplayStatus); @@ -167,13 +172,11 @@ protected override void CreateChildControls() protected void OnPageChanged(EventArgs e) { - if (this.PageChanged != null) - { - this.PageChanged(this, e); - } + this.PageChanged?.Invoke(this, e); } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override void Render(HtmlTextWriter output) { if (this.PageNumbers == null) @@ -263,7 +266,7 @@ private void BindPageNumbers(int totalRecords, int recordsPerPage) } } - private string CreateURL(string currentPage) + private string CreateUrl(string currentPage) { switch (this.Mode) { @@ -281,68 +284,77 @@ private string GetLink(int pageNum) { if (pageNum == this.CurrentPage) { - return this.CSSClassLinkInactive.Trim().Length > 0 ? "[" + pageNum + "]" : "[" + pageNum + "]"; + return this.CSSClassLinkInactive.Trim().Length > 0 + ? $"[{pageNum}]" + : $"[{pageNum}]"; } + var url = this.CreateUrl(pageNum.ToString(CultureInfo.InvariantCulture)); return this.CSSClassLinkActive.Trim().Length > 0 - ? "" + pageNum + "" - : "" + pageNum + ""; + ? $"{pageNum}" + : $"{pageNum}"; } /// GetPreviousLink returns the link for the Previous page for paging. private string GetPreviousLink() { + var url = this.CreateUrl((this.CurrentPage - 1).ToString(CultureInfo.InvariantCulture)); + var previousText = Localization.GetString("Previous", Localization.SharedResourceFile); return this.CurrentPage > 1 && this.totalPages > 0 ? (this.CSSClassLinkActive.Trim().Length > 0 - ? "" + - Localization.GetString("Previous", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Previous", Localization.SharedResourceFile) + "") + ? $"{previousText}" + : $"{previousText}") : (this.CSSClassLinkInactive.Trim().Length > 0 - ? "" + Localization.GetString("Previous", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Previous", Localization.SharedResourceFile) + ""); + ? $"{previousText}" + : $"{previousText}"); } /// GetNextLink returns the link for the Next Page for paging. private string GetNextLink() { + var url = this.CreateUrl((this.CurrentPage + 1).ToString(CultureInfo.InvariantCulture)); + var nextText = Localization.GetString("Next", Localization.SharedResourceFile); return this.CurrentPage != this.totalPages && this.totalPages > 0 ? (this.CSSClassLinkActive.Trim().Length > 0 - ? "" + Localization.GetString("Next", Localization.SharedResourceFile) + - "" - : "" + Localization.GetString("Next", Localization.SharedResourceFile) + "") + ? $"{nextText}" + : $"{nextText}") : (this.CSSClassLinkInactive.Trim().Length > 0 - ? "" + Localization.GetString("Next", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Next", Localization.SharedResourceFile) + ""); + ? $"{nextText}" + : $"{nextText}"); } /// GetFirstLink returns the First Page link for paging. private string GetFirstLink() { + var firstText = Localization.GetString("First", Localization.SharedResourceFile); if (this.CurrentPage > 1 && this.totalPages > 0) { + var url = this.CreateUrl("1"); return this.CSSClassLinkActive.Trim().Length > 0 - ? "" + Localization.GetString("First", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("First", Localization.SharedResourceFile) + ""; + ? $"{firstText}" + : $"{firstText}"; } return this.CSSClassLinkInactive.Trim().Length > 0 - ? "" + Localization.GetString("First", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("First", Localization.SharedResourceFile) + ""; + ? $"{firstText}" + : $"{firstText}"; } /// GetLastLink returns the Last Page link for paging. private string GetLastLink() { + var lastText = Localization.GetString("Last", Localization.SharedResourceFile); if (this.CurrentPage != this.totalPages && this.totalPages > 0) { + var url = this.CreateUrl(this.totalPages.ToString(CultureInfo.InvariantCulture)); return this.CSSClassLinkActive.Trim().Length > 0 - ? "" + Localization.GetString("Last", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Last", Localization.SharedResourceFile) + ""; + ? $"{lastText}" + : $"{lastText}"; } return this.CSSClassLinkInactive.Trim().Length > 0 - ? "" + Localization.GetString("Last", Localization.SharedResourceFile) + "" - : "" + Localization.GetString("Last", Localization.SharedResourceFile) + ""; + ? $"{lastText}" + : $"{lastText}"; } public class PageNumberLinkTemplate : ITemplate @@ -366,11 +378,9 @@ void ITemplate.InstantiateIn(Control container) private void BindData(object sender, EventArgs e) { - Literal lc; - lc = (Literal)sender; - RepeaterItem container; - container = (RepeaterItem)lc.NamingContainer; - lc.Text = this.pagingControl.GetLink(Convert.ToInt32(DataBinder.Eval(container.DataItem, "PageNum"))) + "  "; + var lc = (Literal)sender; + var container = (RepeaterItem)lc.NamingContainer; + lc.Text = this.pagingControl.GetLink(Convert.ToInt32(DataBinder.Eval(container.DataItem, "PageNum"), CultureInfo.InvariantCulture)) + "  "; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs index 193bd954e4d..b32d0ab3b6e 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.WebControls { using System; using System.Collections; + using System.Globalization; using System.Reflection; using System.Web.UI.WebControls; @@ -40,10 +41,8 @@ public EditorInfo CreateEditControl() /// public bool UpdateValue(PropertyEditorEventArgs e) { - string nameDataField = Convert.ToString(this.fieldNames["Name"]); - string valueDataField = Convert.ToString(this.fieldNames["Value"]); - PropertyInfo objProperty; - string propertyName = string.Empty; + string nameDataField = Convert.ToString(this.fieldNames["Name"], CultureInfo.InvariantCulture); + string valueDataField = Convert.ToString(this.fieldNames["Value"], CultureInfo.InvariantCulture); bool changed = e.Changed; string name = e.Name; object oldValue = e.OldValue; @@ -52,10 +51,10 @@ public bool UpdateValue(PropertyEditorEventArgs e) bool isDirty = Null.NullBoolean; // Get the Name Property - objProperty = this.dataSource.GetType().GetProperty(nameDataField); + var objProperty = this.dataSource.GetType().GetProperty(nameDataField); if (objProperty != null) { - propertyName = Convert.ToString(objProperty.GetValue(this.dataSource, null)); + var propertyName = Convert.ToString(objProperty.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); // Do we have the item in the IEnumerable Collection being changed propertyName = propertyName.Replace(" ", "_"); @@ -87,8 +86,8 @@ public bool UpdateValue(PropertyEditorEventArgs e) /// public bool UpdateVisibility(PropertyEditorEventArgs e) { - string nameDataField = Convert.ToString(this.fieldNames["Name"]); - string dataField = Convert.ToString(this.fieldNames["ProfileVisibility"]); + string nameDataField = Convert.ToString(this.fieldNames["Name"], CultureInfo.InvariantCulture); + string dataField = Convert.ToString(this.fieldNames["ProfileVisibility"], CultureInfo.InvariantCulture); string name = e.Name; object newValue = e.Value; bool dirty = Null.NullBoolean; @@ -97,7 +96,7 @@ public bool UpdateVisibility(PropertyEditorEventArgs e) PropertyInfo property = this.dataSource.GetType().GetProperty(nameDataField); if (property != null) { - string propertyName = Convert.ToString(property.GetValue(this.dataSource, null)); + string propertyName = Convert.ToString(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); // Do we have the item in the IEnumerable Collection being changed propertyName = propertyName.Replace(" ", "_"); @@ -115,18 +114,18 @@ public bool UpdateVisibility(PropertyEditorEventArgs e) return dirty; } - /// GetEditorInfo builds an EditorInfo object for a propoerty. + /// GetEditorInfo builds an EditorInfo object for a property. private EditorInfo GetEditorInfo() { - string categoryDataField = Convert.ToString(this.fieldNames["Category"]); - string editorDataField = Convert.ToString(this.fieldNames["Editor"]); - string nameDataField = Convert.ToString(this.fieldNames["Name"]); - string requiredDataField = Convert.ToString(this.fieldNames["Required"]); - string typeDataField = Convert.ToString(this.fieldNames["Type"]); - string validationExpressionDataField = Convert.ToString(this.fieldNames["ValidationExpression"]); - string valueDataField = Convert.ToString(this.fieldNames["Value"]); - string visibilityDataField = Convert.ToString(this.fieldNames["ProfileVisibility"]); - string maxLengthDataField = Convert.ToString(this.fieldNames["Length"]); + string categoryDataField = Convert.ToString(this.fieldNames["Category"], CultureInfo.InvariantCulture); + string editorDataField = Convert.ToString(this.fieldNames["Editor"], CultureInfo.InvariantCulture); + string nameDataField = Convert.ToString(this.fieldNames["Name"], CultureInfo.InvariantCulture); + string requiredDataField = Convert.ToString(this.fieldNames["Required"], CultureInfo.InvariantCulture); + string typeDataField = Convert.ToString(this.fieldNames["Type"], CultureInfo.InvariantCulture); + string validationExpressionDataField = Convert.ToString(this.fieldNames["ValidationExpression"], CultureInfo.InvariantCulture); + string valueDataField = Convert.ToString(this.fieldNames["Value"], CultureInfo.InvariantCulture); + string visibilityDataField = Convert.ToString(this.fieldNames["ProfileVisibility"], CultureInfo.InvariantCulture); + string maxLengthDataField = Convert.ToString(this.fieldNames["Length"], CultureInfo.InvariantCulture); var editInfo = new EditorInfo(); PropertyInfo property; @@ -138,7 +137,7 @@ private EditorInfo GetEditorInfo() property = this.dataSource.GetType().GetProperty(nameDataField); if (!(property == null || (property.GetValue(this.dataSource, null) == null))) { - editInfo.Name = Convert.ToString(property.GetValue(this.dataSource, null)); + editInfo.Name = Convert.ToString(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); } } @@ -151,7 +150,7 @@ private EditorInfo GetEditorInfo() property = this.dataSource.GetType().GetProperty(categoryDataField); if (!(property == null || (property.GetValue(this.dataSource, null) == null))) { - editInfo.Category = Convert.ToString(property.GetValue(this.dataSource, null)); + editInfo.Category = Convert.ToString(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); } } @@ -162,7 +161,7 @@ private EditorInfo GetEditorInfo() property = this.dataSource.GetType().GetProperty(valueDataField); if (!(property == null || (property.GetValue(this.dataSource, null) == null))) { - editInfo.Value = Convert.ToString(property.GetValue(this.dataSource, null)); + editInfo.Value = Convert.ToString(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); } } @@ -173,7 +172,7 @@ private EditorInfo GetEditorInfo() property = this.dataSource.GetType().GetProperty(typeDataField); if (!(property == null || (property.GetValue(this.dataSource, null) == null))) { - editInfo.Type = Convert.ToString(property.GetValue(this.dataSource, null)); + editInfo.Type = Convert.ToString(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); } } @@ -184,7 +183,7 @@ private EditorInfo GetEditorInfo() property = this.dataSource.GetType().GetProperty(editorDataField); if (!(property == null || (property.GetValue(this.dataSource, null) == null))) { - editInfo.Editor = EditorInfo.GetEditor(Convert.ToInt32(property.GetValue(this.dataSource, null))); + editInfo.Editor = EditorInfo.GetEditor(Convert.ToInt32(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture)); } } @@ -198,13 +197,13 @@ private EditorInfo GetEditorInfo() property = this.dataSource.GetType().GetProperty(requiredDataField); if (!((property == null) || (property.GetValue(this.dataSource, null) == null))) { - editInfo.Required = Convert.ToBoolean(property.GetValue(this.dataSource, null)); + editInfo.Required = Convert.ToBoolean(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); } } // Set ResourceKey Field editInfo.ResourceKey = editInfo.Name; - editInfo.ResourceKey = string.Format("{0}_{1}", this.name, editInfo.Name); + editInfo.ResourceKey = $"{this.name}_{editInfo.Name}"; // Set Style editInfo.ControlStyle = new Style(); @@ -230,7 +229,7 @@ private EditorInfo GetEditorInfo() property = this.dataSource.GetType().GetProperty(validationExpressionDataField); if (!(property == null || (property.GetValue(this.dataSource, null) == null))) { - editInfo.ValidationExpression = Convert.ToString(property.GetValue(this.dataSource, null)); + editInfo.ValidationExpression = Convert.ToString(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); } } @@ -240,7 +239,7 @@ private EditorInfo GetEditorInfo() property = this.dataSource.GetType().GetProperty(maxLengthDataField); if (!(property == null || (property.GetValue(this.dataSource, null) == null))) { - int length = Convert.ToInt32(property.GetValue(this.dataSource, null)); + int length = Convert.ToInt32(property.GetValue(this.dataSource, null), CultureInfo.InvariantCulture); var attributes = new object[1]; attributes[0] = new MaxLengthAttribute(length); editInfo.Attributes = attributes; diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs index 5b0fa5b3ccf..790559752d2 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.WebControls { using System; using System.Collections; + using System.Globalization; using System.Web.UI.WebControls; using DotNetNuke.Common.Utilities; @@ -71,19 +72,17 @@ public EditorInfo CreateEditControl() /// public bool UpdateValue(PropertyEditorEventArgs e) { - string key; string name = e.Name; bool changed = e.Changed; object oldValue = e.OldValue; object newValue = e.Value; - object stringValue = e.StringValue; bool isDirty = Null.NullBoolean; var settings = (Hashtable)this.dataSource; - IDictionaryEnumerator settingsEnumerator = settings.GetEnumerator(); + var settingsEnumerator = settings.GetEnumerator(); while (settingsEnumerator.MoveNext()) { - key = Convert.ToString(settingsEnumerator.Key); + var key = Convert.ToString(settingsEnumerator.Key, CultureInfo.InvariantCulture); // Do we have the item in the Hashtable being changed if (key == name) diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs index 6e1ac683ffd..1e7538b3009 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System; using System.ComponentModel; using System.Reflection; using System.Web.UI.WebControls; @@ -120,7 +121,7 @@ private static EditorInfo GetEditorInfo(object dataSource, PropertyInfo objPrope EditorAttribute editor = null; for (int i = 0; i <= editorAttributes.Length - 1; i++) { - if (((EditorAttribute)editorAttributes[i]).EditorBaseTypeName.IndexOf("DotNetNuke.UI.WebControls.EditControl") >= 0) + if (((EditorAttribute)editorAttributes[i]).EditorBaseTypeName.Contains("DotNetNuke.UI.WebControls.EditControl", StringComparison.Ordinal)) { editor = (EditorAttribute)editorAttributes[i]; break; @@ -167,7 +168,7 @@ private static EditorInfo GetEditorInfo(object dataSource, PropertyInfo objPrope } // Set ResourceKey Field - editInfo.ResourceKey = string.Format("{0}_{1}", dataSource.GetType().Name, objProperty.Name); + editInfo.ResourceKey = $"{dataSource.GetType().Name}_{objProperty.Name}"; // Get Validation Expression Field editInfo.ValidationExpression = string.Empty; diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs index 9ff9d436224..9cfe373676a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.WebControls using System; using System.Collections; using System.ComponentModel; + using System.Globalization; using System.Reflection; using System.Web.UI; using System.Web.UI.WebControls; @@ -148,16 +149,15 @@ protected override void AddEditorRow(object obj) /// The category name or . protected override string GetCategory(object obj) { - PropertyInfo objProperty; string category = Null.NullString; // Get Category Field if (!string.IsNullOrEmpty(this.CategoryDataField)) { - objProperty = obj.GetType().GetProperty(this.CategoryDataField); + var objProperty = obj.GetType().GetProperty(this.CategoryDataField); if (!(objProperty == null || (objProperty.GetValue(obj, null) == null))) { - category = Convert.ToString(objProperty.GetValue(obj, null)); + category = Convert.ToString(objProperty.GetValue(obj, null), CultureInfo.InvariantCulture); } } @@ -170,17 +170,16 @@ protected override string GetCategory(object obj) protected override string[] GetGroups(IEnumerable arrObjects) { var arrGroups = new ArrayList(); - PropertyInfo objProperty; foreach (object obj in arrObjects) { // Get Category Field if (!string.IsNullOrEmpty(this.CategoryDataField)) { - objProperty = obj.GetType().GetProperty(this.CategoryDataField); + var objProperty = obj.GetType().GetProperty(this.CategoryDataField); if (!((objProperty == null) || (objProperty.GetValue(obj, null) == null))) { - string category = Convert.ToString(objProperty.GetValue(obj, null)); + string category = Convert.ToString(objProperty.GetValue(obj, null), CultureInfo.InvariantCulture); if (!arrGroups.Contains(category)) { @@ -193,7 +192,7 @@ protected override string[] GetGroups(IEnumerable arrObjects) var strGroups = new string[arrGroups.Count]; for (int i = 0; i <= arrGroups.Count - 1; i++) { - strGroups[i] = Convert.ToString(arrGroups[i]); + strGroups[i] = Convert.ToString(arrGroups[i], CultureInfo.InvariantCulture); } return strGroups; @@ -205,11 +204,10 @@ protected override string[] GetGroups(IEnumerable arrObjects) protected override bool GetRowVisibility(object obj) { bool isVisible = true; - PropertyInfo objProperty; - objProperty = obj.GetType().GetProperty(this.VisibleDataField); + var objProperty = obj.GetType().GetProperty(this.VisibleDataField); if (!(objProperty == null || (objProperty.GetValue(obj, null) == null))) { - isVisible = Convert.ToBoolean(objProperty.GetValue(obj, null)); + isVisible = Convert.ToBoolean(objProperty.GetValue(obj, null), CultureInfo.InvariantCulture); } if (!isVisible && this.EditMode == PropertyEditorMode.Edit) @@ -218,7 +216,7 @@ protected override bool GetRowVisibility(object obj) objProperty = obj.GetType().GetProperty(this.RequiredDataField); if (!(objProperty == null || (objProperty.GetValue(obj, null) == null))) { - isVisible = Convert.ToBoolean(objProperty.GetValue(obj, null)); + isVisible = Convert.ToBoolean(objProperty.GetValue(obj, null), CultureInfo.InvariantCulture); } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs index 4f5917a1b07..7020269daf6 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs @@ -2,76 +2,77 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.WebControls -{ - using System; - using System.Web.UI; +namespace DotNetNuke.UI.WebControls +{ + using System; + using System.Globalization; + using System.Web.UI; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Framework.JavaScriptLibraries; - using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Web.Client.ClientResourceManagement; - /// - /// The AutoCompleteControl is the same as a TextEditControl but it looks up similar values - /// in the profile of other users in the same portal and offers those in a dropdown under the text - /// box where the user is entering the value. So if you'd use this as the input control - /// for "City" it will find all entered cities and look up values as the user types the city in - /// the textbox. Selection is not enforced and if a user enters a new city it is added to the list. - /// - [ToolboxData("<{0}:TextEditControl runat=server>")] - internal class AutoCompleteControl : TextEditControl + /// + /// The AutoCompleteControl is the same as a TextEditControl but it looks up similar values + /// in the profile of other users in the same portal and offers those in a dropdown under the text + /// box where the user is entering the value. So if you'd use this as the input control + /// for "City" it will find all entered cities and look up values as the user types the city in + /// the textbox. Selection is not enforced and if a user enters a new city it is added to the list. + /// + [ToolboxData("<{0}:TextEditControl runat=server>")] + internal class AutoCompleteControl : TextEditControl { /// Initializes a new instance of the class. - public AutoCompleteControl() - { - this.Init += this.AutoCompleteControl_Init; - this.Load += this.AutoCompleteControl_Load; + public AutoCompleteControl() + { + this.Init += this.AutoCompleteControl_Init; + this.Load += this.AutoCompleteControl_Load; } /// - protected override void RenderEditMode(HtmlTextWriter writer) - { - int length = Null.NullInteger; - if (this.CustomAttributes != null) - { - foreach (Attribute attribute in this.CustomAttributes) - { - if (attribute is MaxLengthAttribute) - { - var lengthAtt = (MaxLengthAttribute)attribute; - length = lengthAtt.Length; - break; - } - } - } - - this.ControlStyle.AddAttributesToRender(writer); - writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); - writer.AddAttribute(HtmlTextWriterAttribute.Value, this.StringValue); - if (length > Null.NullInteger) - { - writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); - } - - writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); - writer.AddAttribute("data-name", this.Name); - writer.AddAttribute("data-pid", Entities.Portals.PortalSettings.Current.PortalId.ToString()); - writer.AddAttribute("data-editor", "AutoCompleteControl"); - writer.RenderBeginTag(HtmlTextWriterTag.Input); - writer.RenderEndTag(); - } + protected override void RenderEditMode(HtmlTextWriter writer) + { + int length = Null.NullInteger; + if (this.CustomAttributes != null) + { + foreach (Attribute attribute in this.CustomAttributes) + { + if (attribute is MaxLengthAttribute) + { + var lengthAtt = (MaxLengthAttribute)attribute; + length = lengthAtt.Length; + break; + } + } + } - private void AutoCompleteControl_Init(object sender, System.EventArgs e) - { - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/ProfileAutoComplete/dnn.ProfileAutoComplete.js"); - ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/ProfileAutoComplete/dnn.AutoComplete.css"); - JavaScript.RequestRegistration(CommonJs.jQuery); - JavaScript.RequestRegistration(CommonJs.jQueryUI); - } - - private void AutoCompleteControl_Load(object sender, System.EventArgs e) - { - } - } -} + this.ControlStyle.AddAttributesToRender(writer); + writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); + writer.AddAttribute(HtmlTextWriterAttribute.Value, this.StringValue); + if (length > Null.NullInteger) + { + writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString(CultureInfo.InvariantCulture)); + } + + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + writer.AddAttribute("data-name", this.Name); + writer.AddAttribute("data-pid", Entities.Portals.PortalSettings.Current.PortalId.ToString(CultureInfo.InvariantCulture)); + writer.AddAttribute("data-editor", "AutoCompleteControl"); + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.RenderEndTag(); + } + + private void AutoCompleteControl_Init(object sender, System.EventArgs e) + { + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/ProfileAutoComplete/dnn.ProfileAutoComplete.js"); + ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/ProfileAutoComplete/dnn.AutoComplete.css"); + JavaScript.RequestRegistration(CommonJs.jQuery); + JavaScript.RequestRegistration(CommonJs.jQueryUI); + } + + private void AutoCompleteControl_Load(object sender, System.EventArgs e) + { + } + } +} diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryAutocompleteControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryAutocompleteControl.cs index b0339774bfd..684d135351a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryAutocompleteControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryAutocompleteControl.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; @@ -44,10 +45,7 @@ public override string EditControlClientId } } - protected string OldStringValue - { - get { return Convert.ToString(this.OldValue); } - } + protected string OldStringValue => Convert.ToString(this.OldValue, CultureInfo.InvariantCulture); /// protected override string StringValue @@ -57,7 +55,7 @@ protected override string StringValue string strValue = Null.NullString; if (this.Value != null) { - strValue = Convert.ToString(this.Value); + strValue = Convert.ToString(this.Value, CultureInfo.InvariantCulture); } return strValue; diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs index cafcfb7d915..577a6d5025f 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.WebControls { + using System.Globalization; using System.Web.UI; using DotNetNuke.Common.Lists; @@ -41,7 +42,7 @@ private void OnItemChanged(object sender, PropertyEditorEventArgs e) var countries = listController.GetListEntryInfoItems("Country"); foreach (var checkCountry in countries) { - if (checkCountry.EntryID.ToString() == e.StringValue) + if (checkCountry.EntryID.ToString(CultureInfo.InvariantCulture) == e.StringValue) { var attributes = new object[1]; attributes[0] = new ListAttribute("Region", "Country." + checkCountry.Value, ListBoundField.Id, ListBoundField.Text); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs index 3d95a85ba2f..9869b81b689 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.UI.WebControls using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Web; using System.Web.UI; @@ -50,7 +51,7 @@ protected int IntegerValue try { - intValue = Convert.ToInt32(this.Value); + intValue = Convert.ToInt32(this.Value, CultureInfo.InvariantCulture); } catch (Exception exc) { @@ -61,7 +62,7 @@ protected int IntegerValue } } - /// Gets the ListEntryInfo objects associated witht the control. + /// Gets the ListEntryInfo objects associated with the control. protected IEnumerable ListEntries { get @@ -98,7 +99,7 @@ protected int OldIntegerValue try { // Try and cast the value to an Integer - intValue = Convert.ToInt32(this.OldValue); + intValue = Convert.ToInt32(this.OldValue, CultureInfo.InvariantCulture); } catch (Exception exc) { @@ -114,7 +115,7 @@ protected int OldIntegerValue /// Gets oldStringValue returns the Boolean representation of the OldValue. /// A String representing the OldValue. - protected string OldStringValue => Convert.ToString(this.OldValue); + protected string OldStringValue => Convert.ToString(this.OldValue, CultureInfo.InvariantCulture); /// Gets or sets a value indicating whether the List Auto Posts Back. protected bool AutoPostBack { get; set; } @@ -156,7 +157,7 @@ protected override string StringValue { get { - return Convert.ToString(this.Value); + return Convert.ToString(this.Value, CultureInfo.InvariantCulture); } set @@ -164,7 +165,7 @@ protected override string StringValue if (this.ValueField == ListBoundField.Id) { // Integer type field - this.Value = int.Parse(value); + this.Value = int.Parse(value, CultureInfo.InvariantCulture); } else { @@ -231,7 +232,7 @@ protected override void RenderViewMode(HtmlTextWriter writer) switch (this.ValueField) { case ListBoundField.Id: - entry = objListController.GetListEntryInfo(this.ListName, Convert.ToInt32(this.Value)); + entry = objListController.GetListEntryInfo(this.ListName, Convert.ToInt32(this.Value, CultureInfo.InvariantCulture)); break; case ListBoundField.Text: entryText = this.StringValue; @@ -248,7 +249,7 @@ protected override void RenderViewMode(HtmlTextWriter writer) switch (this.TextField) { case ListBoundField.Id: - writer.Write(entry.EntryID.ToString()); + writer.Write(entry.EntryID.ToString(CultureInfo.InvariantCulture)); break; case ListBoundField.Text: writer.Write(entry.Text); @@ -315,7 +316,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) switch (this.ValueField) { case ListBoundField.Id: - itemValue = item.EntryID.ToString(); + itemValue = item.EntryID.ToString(CultureInfo.InvariantCulture); break; case ListBoundField.Text: itemValue = item.Text; @@ -337,7 +338,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) switch (this.TextField) { case ListBoundField.Id: - writer.Write(item.EntryID.ToString()); + writer.Write(item.EntryID.ToString(CultureInfo.InvariantCulture)); break; case ListBoundField.Text: writer.Write(item.Text); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs index a3261e933f1..19a1039f604 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System.Collections.Generic; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common; @@ -38,7 +39,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) TabInfo tab = listTabs[tabIndex]; // Add the Value Attribute - writer.AddAttribute(HtmlTextWriterAttribute.Value, tab.TabID.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Value, tab.TabID.ToString(CultureInfo.InvariantCulture)); if (tab.TabID == this.IntegerValue) { diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRegionEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRegionEditControl.cs index e5bd0c58b3c..8a87d7b514b 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRegionEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRegionEditControl.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.WebControls using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Web.UI; using System.Web.UI.HtmlControls; @@ -53,7 +54,7 @@ public DNNRegionEditControl(string type) protected string OldStringValue { - get { return Convert.ToString(this.OldValue); } + get { return Convert.ToString(this.OldValue, CultureInfo.InvariantCulture); } } /// Gets the ListEntryInfo objects associated with the control. @@ -82,7 +83,7 @@ protected override string StringValue string strValue = Null.NullString; if (this.Value != null) { - strValue = Convert.ToString(this.Value); + strValue = Convert.ToString(this.Value, CultureInfo.InvariantCulture); } return strValue; @@ -220,7 +221,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { foreach (ListEntryInfo item in this.ListEntries) { - this.Regions.Items.Add(new ListItem() { Text = item.Text, Value = item.EntryID.ToString() }); + this.Regions.Items.Add(new ListItem() { Text = item.Text, Value = item.EntryID.ToString(CultureInfo.InvariantCulture), }); } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs index 03d7205e225..1f37dba97bd 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.WebControls { using System; using System.Collections.Specialized; + using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; @@ -86,7 +87,7 @@ protected override void CreateChildControls() } else { - pnlEditor.CssClass = string.Format("{0} dnnLeft", this.CssClass); + pnlEditor.CssClass = $"{this.CssClass} dnnLeft"; } this.richTextEditor = HtmlEditorProvider.Instance(); @@ -126,8 +127,8 @@ protected override void CreateChildControls() /// protected override void OnDataChanged(EventArgs e) { - var strValue = RemoveBaseTags(Convert.ToString(this.Value)); - var strOldValue = RemoveBaseTags(Convert.ToString(this.OldValue)); + var strValue = RemoveBaseTags(Convert.ToString(this.Value, CultureInfo.InvariantCulture)); + var strOldValue = RemoveBaseTags(Convert.ToString(this.OldValue, CultureInfo.InvariantCulture)); var args = new PropertyEditorEventArgs(this.Name) { Value = this.Page.Server.HtmlEncode(strValue), OldValue = this.Page.Server.HtmlEncode(strOldValue), StringValue = this.Page.Server.HtmlEncode(RemoveBaseTags(this.StringValue)) }; this.OnValueChanged(args); } @@ -145,7 +146,7 @@ protected override void OnPreRender(EventArgs e) base.OnPreRender(e); if (this.EditMode == PropertyEditorMode.Edit) { - this.EditorText = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); + this.EditorText = this.Page.Server.HtmlDecode(Convert.ToString(this.Value, CultureInfo.InvariantCulture)); } if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) @@ -163,7 +164,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) /// protected override void RenderViewMode(HtmlTextWriter writer) { - string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); + string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value, CultureInfo.InvariantCulture)); this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(propValue); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs index 382b28389c0..669f4076c11 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs @@ -36,7 +36,7 @@ protected DateTime DateValue DateTime dteValue = Null.NullDate; try { - var dteString = Convert.ToString(this.Value); + var dteString = Convert.ToString(this.Value, CultureInfo.InvariantCulture); DateTime.TryParse(dteString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dteValue); } catch (Exception exc) @@ -115,9 +115,9 @@ protected override string StringValue get { string stringValue = Null.NullString; - if (this.DateValue.ToUniversalTime().Date != DateTime.Parse("1754/01/01") && this.DateValue != Null.NullDate) + if (this.DateValue.ToUniversalTime().Date != new DateTime(1754, 1, 1) && this.DateValue != Null.NullDate) { - stringValue = this.DateValue.ToString(this.Format); + stringValue = this.DateValue.ToString(this.Format, CultureInfo.InvariantCulture); } return stringValue; @@ -125,7 +125,7 @@ protected override string StringValue set { - this.Value = DateTime.Parse(value); + this.Value = DateTime.Parse(value, CultureInfo.InvariantCulture); } } @@ -138,7 +138,7 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo string postedValue = postCollection[postDataKey + "date"]; if (!presentValue.Equals(postedValue, StringComparison.Ordinal)) { - this.Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); + this.Value = DateTime.Parse(postedValue, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); dataChanged = true; } @@ -168,7 +168,7 @@ protected virtual void LoadDateControls() { if (this.DateValue != Null.NullDate) { - this.dateField.Text = this.DateValue.Date.ToString("d"); + this.dateField.Text = this.DateValue.Date.ToString("d", CultureInfo.CurrentCulture); } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs index 49a623505e5..386bf764927 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs @@ -57,14 +57,13 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo if (postedHours != "12" || this.is24HourClock) { - int hours = 0; - if (int.TryParse(postedHours, out hours)) + if (int.TryParse(postedHours, out var hours)) { postedValue = postedValue.AddHours(hours); } } - postedValue = postedValue.AddMinutes(int.Parse(postedMinutes)); + postedValue = postedValue.AddMinutes(int.Parse(postedMinutes, CultureInfo.InvariantCulture)); if (!this.is24HourClock && postedAMPM.Equals("PM", StringComparison.Ordinal)) { postedValue = postedValue.AddHours(12); @@ -105,7 +104,7 @@ protected override void CreateChildControls() for (int i = minHour; i <= maxHour; i++) { - this.hourField.Items.Add(new ListItem(i.ToString("00"), i.ToString())); + this.hourField.Items.Add(new ListItem(i.ToString("00", CultureInfo.CurrentCulture), i.ToString(CultureInfo.InvariantCulture))); } this.hourField.ControlStyle.CopyFrom(this.ControlStyle); @@ -115,7 +114,7 @@ protected override void CreateChildControls() this.minutesField = new DropDownList(); for (int i = 0; i <= 59; i++) { - this.minutesField.Items.Add(new ListItem(i.ToString("00"), i.ToString())); + this.minutesField.Items.Add(new ListItem(i.ToString("00", CultureInfo.CurrentCulture), i.ToString(CultureInfo.InvariantCulture))); } this.minutesField.ControlStyle.CopyFrom(this.ControlStyle); @@ -154,15 +153,8 @@ protected override void LoadDateControls() } } - if (this.hourField.Items.FindByValue(hour.ToString()) != null) - { - this.hourField.Items.FindByValue(hour.ToString()).Selected = true; - } - - if (this.minutesField.Items.FindByValue(minute.ToString()) != null) - { - this.minutesField.Items.FindByValue(minute.ToString()).Selected = true; - } + this.hourField.Items.FindByValue(hour.ToString(CultureInfo.InvariantCulture))?.Selected = true; + this.minutesField.Items.FindByValue(minute.ToString(CultureInfo.InvariantCulture))?.Selected = true; if (!this.is24HourClock) { diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs index 84959e74e54..35dab5f5734 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.WebControls { using System; using System.Collections.Specialized; + using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; @@ -156,7 +157,7 @@ protected virtual void OnValueChanged(PropertyEditorEventArgs e) /// A HtmlTextWriter. protected virtual void RenderViewMode(HtmlTextWriter writer) { - string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); + string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value, CultureInfo.InvariantCulture)); this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); @@ -169,7 +170,7 @@ protected virtual void RenderViewMode(HtmlTextWriter writer) /// A HtmlTextWriter. protected virtual void RenderEditMode(HtmlTextWriter writer) { - string propValue = Convert.ToString(this.Value); + string propValue = Convert.ToString(this.Value, CultureInfo.InvariantCulture); this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs index c1df8a9c5f9..edad4953473 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs @@ -34,13 +34,13 @@ protected override string StringValue { get { - var retValue = Convert.ToInt32(this.Value); + var retValue = Convert.ToInt32(this.Value, CultureInfo.InvariantCulture); return retValue.ToString(CultureInfo.InvariantCulture); } set { - int setValue = int.Parse(value); + int setValue = int.Parse(value, CultureInfo.InvariantCulture); this.Value = setValue; } } @@ -49,8 +49,8 @@ protected override string StringValue /// The event arguments. protected override void OnDataChanged(EventArgs e) { - int intValue = Convert.ToInt32(this.Value); - int intOldValue = Convert.ToInt32(this.OldValue); + int intValue = Convert.ToInt32(this.Value, CultureInfo.InvariantCulture); + int intOldValue = Convert.ToInt32(this.OldValue, CultureInfo.InvariantCulture); var args = new PropertyEditorEventArgs(this.Name) { Value = Enum.ToObject(this.enumType, intValue), OldValue = Enum.ToObject(this.enumType, intOldValue) }; @@ -62,8 +62,8 @@ protected override void OnDataChanged(EventArgs e) /// A HtmlTextWriter. protected override void RenderEditMode(HtmlTextWriter writer) { - int propValue = Convert.ToInt32(this.Value); - Array enumValues = Enum.GetValues(this.enumType); + int propValue = Convert.ToInt32(this.Value, CultureInfo.InvariantCulture); + var enumValues = Enum.GetValues(this.enumType); // Render the Select Tag this.ControlStyle.AddAttributesToRender(writer); @@ -74,7 +74,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) for (int i = 0; i <= enumValues.Length - 1; i++) { - int enumValue = Convert.ToInt32(enumValues.GetValue(i)); + int enumValue = (int)enumValues.GetValue(i); string enumName = Enum.GetName(this.enumType, enumValue); enumName = Localization.GetString(enumName, this.LocalResourceFile); @@ -101,7 +101,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) /// A HtmlTextWriter. protected override void RenderViewMode(HtmlTextWriter writer) { - int propValue = Convert.ToInt32(this.Value); + int propValue = Convert.ToInt32(this.Value, CultureInfo.InvariantCulture); string enumValue = Enum.Format(this.enumType, propValue, "G"); this.ControlStyle.AddAttributesToRender(writer); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs index dd5ff140c25..19f148c4aec 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common.Utilities; @@ -81,12 +82,12 @@ protected override string StringValue { get { - return this.IntegerValue.ToString(); + return this.IntegerValue.ToString(CultureInfo.InvariantCulture); } set { - int setValue = int.Parse(value); + int setValue = int.Parse(value, CultureInfo.InvariantCulture); this.Value = setValue; } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/MultiLineTextEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/MultiLineTextEditControl.cs index 8a2fbc56ae5..cfbae516001 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/MultiLineTextEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/MultiLineTextEditControl.cs @@ -1,29 +1,30 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.WebControls -{ - using System; +namespace DotNetNuke.UI.WebControls +{ + using System; + using System.Globalization; using System.Web.UI; - /// - /// The MultiLineTextEditControl control provides a standard UI component for editing - /// string/text properties. - /// - [ToolboxData("<{0}:MultiLineTextEditControl runat=server>")] - public class MultiLineTextEditControl : TextEditControl + /// + /// The MultiLineTextEditControl control provides a standard UI component for editing + /// string/text properties. + /// + [ToolboxData("<{0}:MultiLineTextEditControl runat=server>")] + public class MultiLineTextEditControl : TextEditControl { /// - protected override void RenderEditMode(HtmlTextWriter writer) - { - string propValue = Convert.ToString(this.Value); - this.ControlStyle.AddAttributesToRender(writer); - writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); - writer.AddAttribute("aria-label", "editor"); - writer.RenderBeginTag(HtmlTextWriterTag.Textarea); - writer.Write(propValue); - writer.RenderEndTag(); - } - } -} + protected override void RenderEditMode(HtmlTextWriter writer) + { + string propValue = Convert.ToString(this.Value, CultureInfo.InvariantCulture); + this.ControlStyle.AddAttributesToRender(writer); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + writer.AddAttribute("aria-label", "editor"); + writer.RenderBeginTag(HtmlTextWriterTag.Textarea); + writer.Write(propValue); + writer.RenderEndTag(); + } + } +} diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs index 0eadf86a8fc..5eb15c72463 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common.Utilities; @@ -32,13 +33,7 @@ public TextEditControl(string type) /// Gets oldStringValue returns the Boolean representation of the OldValue. /// A String representing the OldValue. - protected string OldStringValue - { - get - { - return Convert.ToString(this.OldValue); - } - } + protected string OldStringValue => Convert.ToString(this.OldValue, CultureInfo.InvariantCulture); /// Gets or sets stringValue is the value of the control expressed as a String. /// A string representing the Value. @@ -49,7 +44,7 @@ protected override string StringValue string strValue = Null.NullString; if (this.Value != null) { - strValue = Convert.ToString(this.Value); + strValue = Convert.ToString(this.Value, CultureInfo.InvariantCulture); } return strValue; @@ -81,10 +76,9 @@ protected override void RenderEditMode(HtmlTextWriter writer) { foreach (Attribute attribute in this.CustomAttributes) { - if (attribute is MaxLengthAttribute) + if (attribute is MaxLengthAttribute maxLengthAttribute) { - var lengthAtt = (MaxLengthAttribute)attribute; - length = lengthAtt.Length; + length = maxLengthAttribute.Length; break; } } @@ -95,7 +89,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.AddAttribute(HtmlTextWriterAttribute.Value, this.StringValue); if (length > Null.NullInteger) { - writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString(CultureInfo.InvariantCulture)); } writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs index be60389cf5b..ab93d212bad 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common.Utilities; @@ -34,8 +35,8 @@ protected bool BooleanValue bool boolValue = Null.NullBoolean; try { - // Try and cast the value to an Boolean - boolValue = Convert.ToBoolean(this.Value); + // Try and cast the value to a Boolean + boolValue = Convert.ToBoolean(this.Value, CultureInfo.InvariantCulture); } catch (Exception exc) { @@ -56,7 +57,7 @@ protected bool OldBooleanValue try { // Try and cast the value to an Boolean - boolValue = Convert.ToBoolean(this.OldValue); + boolValue = Convert.ToBoolean(this.OldValue, CultureInfo.InvariantCulture); } catch (Exception exc) { diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs index 0cd7a7a2592..37459acd61c 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.WebControls { using System; using System.Collections.Specialized; + using System.Globalization; using System.Web.UI; /// The VersionEditControl control provides a standard UI component for editing properties. @@ -62,7 +63,7 @@ protected void RenderDropDownList(HtmlTextWriter writer, string type, int val) for (int i = 0; i <= 99; i++) { // Add the Value Attribute - writer.AddAttribute(HtmlTextWriterAttribute.Value, i.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Value, i.ToString(CultureInfo.InvariantCulture)); if (val == i) { // Add the Selected Attribute @@ -71,7 +72,7 @@ protected void RenderDropDownList(HtmlTextWriter writer, string type, int val) // Render Option Tag writer.RenderBeginTag(HtmlTextWriterTag.Option); - writer.Write(i.ToString("00")); + writer.Write(i.ToString("00", CultureInfo.CurrentCulture)); writer.RenderEndTag(); } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/EditorCreatedEventHandler.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/EditorCreatedEventHandler.cs index 61743aa8ddc..9fb4d4a37f5 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/EditorCreatedEventHandler.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/EditorCreatedEventHandler.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.WebControls -{ - public delegate void EditorCreatedEventHandler(object sender, PropertyEditorItemEventArgs e); -} +namespace DotNetNuke.UI.WebControls; + +using System.Diagnostics.CodeAnalysis; + +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] +public delegate void EditorCreatedEventHandler(object sender, PropertyEditorItemEventArgs e); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyChangedEventHandler.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyChangedEventHandler.cs index 2269708549c..4b043c44d38 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyChangedEventHandler.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyChangedEventHandler.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.WebControls -{ - public delegate void PropertyChangedEventHandler(object sender, PropertyEditorEventArgs e); -} +namespace DotNetNuke.UI.WebControls; + +using System.Diagnostics.CodeAnalysis; + +[SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] +public delegate void PropertyChangedEventHandler(object sender, PropertyEditorEventArgs e); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs index f16d1e4b614..41709458887 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using System.Web.UI; using DotNetNuke.Common; @@ -69,20 +70,18 @@ protected override void CreateEditor() foreach (FieldEditorControl checkEditor in this.Fields) { - if (checkEditor.Editor is DNNCountryEditControl) + if (checkEditor.Editor is DNNCountryEditControl countryEdit) { - if (editor.Editor.Category == checkEditor.Editor.Category) + if (editor.Editor.Category == countryEdit.Category) { - var countryEdit = (DNNCountryEditControl)checkEditor.Editor; - country = Convert.ToString(countryEdit.Value); + country = Convert.ToString(countryEdit.Value, CultureInfo.InvariantCulture); } } } // Create a ListAttribute for the Region string countryKey = "Unknown"; - int entryId; - if (int.TryParse(country, out entryId)) + if (int.TryParse(country, out var entryId)) { ListController lc = new ListController(); ListEntryInfo item = lc.GetListEntryInfo(entryId); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs index 10ea02da015..924ec4634f0 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs @@ -9,6 +9,7 @@ namespace DotNetNuke.UI.WebControls using System.Collections; using System.Collections.Generic; using System.ComponentModel; + using System.Globalization; using System.Linq; using System.Reflection; using System.Web.UI; @@ -627,7 +628,7 @@ protected virtual string[] GetGroups(IEnumerable arrObjects) var strGroups = new string[arrGroups.Count]; for (int i = 0; i <= arrGroups.Count - 1; i++) { - strGroups[i] = Convert.ToString(arrGroups[i]); + strGroups[i] = Convert.ToString(arrGroups[i], CultureInfo.InvariantCulture); } return strGroups; diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs index 0bd5b3afb73..ee159cce768 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.UI.WebControls using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; @@ -23,16 +24,22 @@ namespace DotNetNuke.UI.WebControls public class PropertyLabelControl : WebControl { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected LinkButton cmdHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected HtmlGenericControl label; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblHelp; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Label lblLabel; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel pnlTooltip; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] protected Panel pnlHelp; private string resourceKey; @@ -253,7 +260,7 @@ protected override void CreateChildControls() /// The event arguments. protected override void OnDataBinding(EventArgs e) { - // If there is a DataSource bind the relevent Properties + // If there is a DataSource bind the relevant Properties if (this.DataSource != null) { this.EnsureChildControls(); @@ -263,12 +270,12 @@ protected override void OnDataBinding(EventArgs e) var dataRow = (DataRowView)this.DataSource; if (this.ResourceKey == string.Empty) { - this.ResourceKey = Convert.ToString(dataRow[this.DataField]); + this.ResourceKey = Convert.ToString(dataRow[this.DataField], CultureInfo.InvariantCulture); } if (this.DesignMode) { - this.label.InnerText = Convert.ToString(dataRow[this.DataField]); + this.label.InnerText = Convert.ToString(dataRow[this.DataField], CultureInfo.InvariantCulture); } } } @@ -302,18 +309,18 @@ protected override void OnPreRender(EventArgs e) // DNNClientAPI.EnableMinMax(cmdHelp, pnlHelp, true, DNNClientAPI.MinMaxPersistanceType.None); if (this.EditControl != null) { - this.label.Attributes.Add("for", this.EditControl is EditControl ? ((EditControl)this.EditControl).EditControlClientId : this.EditControl.ClientID); + this.label.Attributes.Add("for", this.EditControl is EditControl editControl ? editControl.EditControlClientId : this.EditControl.ClientID); } // make sure the help container have the default css class to active js handler. if (!this.pnlHelp.ControlStyle.CssClass.Contains("dnnClear")) { - this.pnlHelp.ControlStyle.CssClass = string.Format("dnnClear {0}", this.pnlHelp.ControlStyle.CssClass); + this.pnlHelp.ControlStyle.CssClass = $"dnnClear {this.pnlHelp.ControlStyle.CssClass}"; } if (!this.pnlHelp.ControlStyle.CssClass.Contains("dnnFormHelpContent")) { - this.pnlHelp.ControlStyle.CssClass = string.Format("dnnFormHelpContent {0}", this.pnlHelp.ControlStyle.CssClass); + this.pnlHelp.ControlStyle.CssClass = $"dnnFormHelpContent {this.pnlHelp.ControlStyle.CssClass}"; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs index d56c9c75a5e..0b7fc074df6 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.WebControls { using System; + using System.Globalization; using DotNetNuke.Instrumentation; @@ -18,11 +19,11 @@ public class SettingInfo /// The setting value. public SettingInfo(object name, object value) { - this.Name = Convert.ToString(name); + this.Name = Convert.ToString(name, CultureInfo.InvariantCulture); this.Value = value; this.type = value.GetType(); this.Editor = EditorInfo.GetEditor(-1); - string strValue = Convert.ToString(value); + string strValue = Convert.ToString(value, CultureInfo.InvariantCulture); bool isFound = false; if (this.type.IsEnum) { @@ -47,7 +48,7 @@ public SettingInfo(object name, object value) { try { - int intValue = int.Parse(strValue); + int intValue = int.Parse(strValue, CultureInfo.InvariantCulture); this.Editor = EditorInfo.GetEditor("Integer"); isFound = true; } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs index 10a3f3d87b6..c5119ac5d47 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.UI.WebControls using System; using System.Collections; using System.ComponentModel; + using System.Globalization; using System.Web.UI; using System.Web.UI.WebControls; @@ -76,10 +77,10 @@ protected override void AddEditorRow(object obj) protected override bool GetRowVisibility(object obj) { var info = (SettingInfo)obj; - bool isVisible = true; - if ((this.Visibility != null) && (this.Visibility[info.Name] != null)) + var isVisible = true; + if (this.Visibility?[info.Name] != null) { - isVisible = Convert.ToBoolean(this.Visibility[info.Name]); + isVisible = Convert.ToBoolean(this.Visibility[info.Name], CultureInfo.InvariantCulture); } return isVisible; @@ -90,13 +91,13 @@ private ArrayList GetSettings() { var settings = (Hashtable)this.DataSource; var arrSettings = new ArrayList(); - IDictionaryEnumerator settingsEnumerator = settings.GetEnumerator(); + var settingsEnumerator = settings.GetEnumerator(); while (settingsEnumerator.MoveNext()) { var info = new SettingInfo(settingsEnumerator.Key, settingsEnumerator.Value); - if ((this.CustomEditors != null) && (this.CustomEditors[settingsEnumerator.Key] != null)) + if (this.CustomEditors?[settingsEnumerator.Key] != null) { - info.Editor = Convert.ToString(this.CustomEditors[settingsEnumerator.Key]); + info.Editor = Convert.ToString(this.CustomEditors[settingsEnumerator.Key], CultureInfo.InvariantCulture); } arrSettings.Add(info); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs index efc3731a25c..8bf5efd37b0 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs @@ -50,7 +50,7 @@ protected ProfileVisibility Visibility set { this.Value = value; } } - /// LoadPostData loads the Post Back Data and determines whether the value has change. + /// LoadPostData loads the Post Back Data and determines whether the value has changed. /// A key to the PostBack Data to load. /// A name value collection of postback data. /// if the value has changed, otherwise . @@ -58,7 +58,7 @@ public virtual bool LoadPostData(string postDataKey, NameValueCollection postCol { var dataChanged = false; var presentVisibility = this.Visibility.VisibilityMode; - var postedValue = Convert.ToInt32(postCollection[postDataKey]); + var postedValue = Convert.ToInt32(postCollection[postDataKey], CultureInfo.InvariantCulture); var postedVisibility = (UserVisibilityMode)Enum.ToObject(typeof(UserVisibilityMode), postedValue); if (!presentVisibility.Equals(postedVisibility) || postedVisibility == UserVisibilityMode.FriendsAndGroups) { diff --git a/DNN Platform/Library/WebControls/WebControlBase.cs b/DNN Platform/Library/WebControls/WebControlBase.cs index a646eeda49f..a3828e576a9 100644 --- a/DNN Platform/Library/WebControls/WebControlBase.cs +++ b/DNN Platform/Library/WebControls/WebControlBase.cs @@ -54,7 +54,7 @@ public string StyleSheetUrl { get { - if (this.styleSheetUrl.StartsWith("~")) + if (this.styleSheetUrl.StartsWith("~", StringComparison.Ordinal)) { return Globals.ResolveUrl(this.styleSheetUrl); } @@ -72,6 +72,7 @@ public string StyleSheetUrl /// Renders the html for this WebControl to the output. /// The output to write to. + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] protected override void RenderContents(HtmlTextWriter output) { output.Write(this.HtmlOutput); diff --git a/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs b/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs index ef3609d9b35..1b61c18f8ae 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs @@ -478,7 +478,7 @@ private string LocalizeActionString(string key, int desktopModuleId) var resourceFile = string.Format( "~/DesktopModules/{0}/{1}/{2}", - desktopModule.FolderName.Replace("\\", "/"), + desktopModule.FolderName.Replace(@"\", "/"), Localization.LocalResourceDirectory, Localization.LocalSharedResourceFile); diff --git a/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs b/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs index f9184b3a7fe..b58353eaf21 100644 --- a/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs +++ b/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs @@ -71,12 +71,12 @@ public string Resolve(string path, params RelativeTo[] roots) } } - if (path.StartsWith("/")) + if (path.StartsWith("/", StringComparison.Ordinal)) { path = path.Substring(1); } - if (!path.StartsWith("~") && !path.Contains(":")) + if (!path.StartsWith("~", StringComparison.Ordinal) && !path.Contains(":")) { foreach (var root in roots) { diff --git a/DNN Platform/Modules/DDRMenu/MenuNode.cs b/DNN Platform/Modules/DDRMenu/MenuNode.cs index f0b64901877..24a726c36be 100644 --- a/DNN Platform/Modules/DDRMenu/MenuNode.cs +++ b/DNN Platform/Modules/DDRMenu/MenuNode.cs @@ -494,7 +494,7 @@ private string ApplyContextToImagePath(string imagePath, string defaultImagePath { result = Globals.ResolveUrl(result); } - else if (!(result.Contains("://") || result.StartsWith("/"))) + else if (!(result.Contains("://") || result.StartsWith("/", StringComparison.Ordinal))) { result = defaultImagePath + result; } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs index bde3b476b60..6a3b2efd607 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs @@ -23,8 +23,10 @@ namespace DotNetNuke.Web.DDRMenu.TemplateEngine public class TemplateDefinition { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public List ClientOptions = new List(); [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public List TemplateArguments = new List(); [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] internal readonly Dictionary> ScriptLibraries = new Dictionary>(); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs index ed2cdde14c8..bed41e446df 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs @@ -42,7 +42,7 @@ public static void UnZipArchive(string archivePath, string extractFolder, bool o /// Full path to archive with name. /// Full path to the target folder. /// Overwrites the files on target if true. - /// List of files to exlude from extraction. + /// List of files to exclude from extraction. /// Delete the files from the archive after extraction. public static void UnZipArchiveExcept( string archivePath, @@ -56,31 +56,28 @@ public static void UnZipArchiveExcept( return; } - using (var archive = OpenCreate(archivePath)) + using var archive = OpenCreate(archivePath); + foreach ( + var entry in + archive.Entries.Where( + entry => + ((exceptionList != null && !exceptionList.Contains(entry.FullName)) || exceptionList == null) && + !entry.FullName.EndsWith(@"\", StringComparison.Ordinal) && !entry.FullName.EndsWith("/", StringComparison.Ordinal) && entry.Length > 0)) { - foreach ( - var entry in - archive.Entries.Where( - entry => - ((exceptionList != null && !exceptionList.Contains(entry.FullName)) || - exceptionList == null) && - !entry.FullName.EndsWith("\\") && !entry.FullName.EndsWith("/") && entry.Length > 0)) + var path = Path.GetDirectoryName(Path.Combine(extractFolder, entry.FullName)); + if (!string.IsNullOrEmpty(path) && !Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + if (!File.Exists(Path.Combine(extractFolder, entry.FullName)) || overwrite) { - var path = Path.GetDirectoryName(Path.Combine(extractFolder, entry.FullName)); - if (!string.IsNullOrEmpty(path) && !Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - if (!File.Exists(Path.Combine(extractFolder, entry.FullName)) || overwrite) - { - entry.ExtractToFile(Path.Combine(extractFolder, entry.FullName), overwrite); - } - - if (deleteFromSoure) - { - entry.Delete(); - } + entry.ExtractToFile(Path.Combine(extractFolder, entry.FullName), overwrite); + } + + if (deleteFromSoure) + { + entry.Delete(); } } } @@ -103,24 +100,22 @@ public static void UnZipFileFromArchive( return; } - using (var archive = OpenCreate(archivePath)) + using var archive = OpenCreate(archivePath); + var fileUnzipFullName = Path.Combine(extractFolder, fileName); + if (File.Exists(fileUnzipFullName) && !overwrite) { - var fileUnzipFullName = Path.Combine(extractFolder, fileName); - if (File.Exists(fileUnzipFullName) && !overwrite) - { - return; - } + return; + } - var fileEntry = archive.GetEntry(fileName); - if (!File.Exists(Path.Combine(extractFolder, fileEntry.FullName)) || overwrite) - { - fileEntry?.ExtractToFile(Path.Combine(extractFolder, fileName), overwrite); - } + var fileEntry = archive.GetEntry(fileName); + if (!File.Exists(Path.Combine(extractFolder, fileEntry.FullName)) || overwrite) + { + fileEntry?.ExtractToFile(Path.Combine(extractFolder, fileName), overwrite); + } - if (deleteFromSoure) - { - fileEntry?.Delete(); - } + if (deleteFromSoure) + { + fileEntry?.Delete(); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs index 4a403dcf919..1166870c48b 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs @@ -19,6 +19,7 @@ public class Constants // these are set by the API caller #pragma warning disable SA1310 // Field names should not contain underscore, bypassing this warning in case something unexpected consumes these. #pragma warning disable SA1600 // Elements should be documented, these names carry their meaning enough to not need documenting. +#pragma warning disable CA1707 // Identifiers should not contain underscores public const string Category_Users = "USERS"; public const string Category_Vocabularies = "VOCABULARIES"; public const string Category_Roles = "ROLES"; @@ -63,5 +64,6 @@ public class Constants internal static readonly int MaxZipFilesMemory = 104857600; // 100 MB #pragma warning restore SA1310 // Field names should not contain underscore #pragma warning restore SA1600 // Elements should be documented +#pragma warning restore CA1707 } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs index 6f43c151136..599073eafaa 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs @@ -6,6 +6,7 @@ namespace Dnn.ExportImport.Components.Common { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Reflection; using System.Text; @@ -32,17 +33,17 @@ namespace Dnn.ExportImport.Components.Common public static partial class Util { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Util)); - private static int noRole = Convert.ToInt32(Globals.glbRoleNothing); + private static int noRole = Convert.ToInt32(Globals.glbRoleNothing, CultureInfo.InvariantCulture); - /// Checks if a string is either null or empty (""). + /// Checks if a string is either null or empty (""). /// The string to check. /// A value indicating whether the string is null or empty. [DnnDeprecated(9, 8, 0, "Use string.IsNullOrEmpty from System.String instead")] public static partial bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s); - /// Checks if a string is either null or contains only whitespace (" "). + /// Checks if a string is either null or contains only whitespace (" "). /// The string to check. - /// A value indicating whether the string is null or contains only whtespace. + /// A value indicating whether the string is null or contains only whitespace. [DnnDeprecated(9, 8, 0, "Use string.IsNullOrWhiteSpace from System.String instead")] public static partial bool IsNullOrWhiteSpace(this string s) => string.IsNullOrWhiteSpace(s); @@ -68,10 +69,10 @@ public static IEnumerable GetPortableImplementors(IServiceP return serviceProvider.GetServices(); } - /// Formats a size to a human readable format. + /// Formats a size to a human-readable format. /// The amount of bytes to represent. /// How many decimal places to use in the resulting string. - /// A human readable size format, for instance 1024 would return 1 KB. + /// A human-readable size format, for instance 1024 would return 1 KB. public static string FormatSize(long bytes, byte decimals = 1) { const long kb = 1024; @@ -85,33 +86,33 @@ public static string FormatSize(long bytes, byte decimals = 1) if (bytes < mb) { - return (1.0 * bytes / kb).ToString("F" + decimals) + " KB"; + return (1.0 * bytes / kb).ToString("F" + decimals, CultureInfo.CurrentCulture) + " KB"; } if (bytes < gb) { - return (1.0 * bytes / mb).ToString("F" + decimals) + " MB"; + return (1.0 * bytes / mb).ToString("F" + decimals, CultureInfo.CurrentCulture) + " MB"; } - return (1.0 * bytes / gb).ToString("F" + decimals) + " GB"; + return (1.0 * bytes / gb).ToString("F" + decimals, CultureInfo.CurrentCulture) + " GB"; } /// Gets the export/import job cache key. /// The job to generate the key for. - /// A string representing the cacke key. + /// A string representing the cache key. public static string GetExpImpJobCacheKey(ExportImportJob job) { - return string.Join(":", "ExpImpKey", job.PortalId.ToString(), job.JobId.ToString()); + return string.Join(":", "ExpImpKey", job.PortalId.ToString(CultureInfo.InvariantCulture), job.JobId.ToString(CultureInfo.InvariantCulture)); } /// Get the id of a user for populating audit control values. /// A reference to the import job. /// The user id for the user that created the export. - /// The user name for the user that creted the export. + /// The username for the user that created the export. /// -1 if not found, 1 if the user is HOST, the user id if found on the imported site. public static int GetUserIdByName(ExportImportJob importJob, int? exportedUserId, string exportUsername) { - if (!exportedUserId.HasValue || exportedUserId <= 0) + if (exportedUserId is null or <= 0) { return -1; } @@ -336,7 +337,7 @@ public static DateTime ToLocalDateTime(DateTime dateTime, UserInfo userInfo) /// A human readable representation of the date and time. public static string GetDateTimeString(DateTime? dateTime) { - return dateTime?.ToString(Thread.CurrentThread.CurrentUICulture) ?? string.Empty; + return dateTime?.ToString(Thread.CurrentThread.CurrentCulture) ?? string.Empty; } /// Gets a string representation of a number formatted for the current thread culture. @@ -344,7 +345,7 @@ public static string GetDateTimeString(DateTime? dateTime) /// A string representing a number in the current thread culture format. public static string FormatNumber(int? number) { - return number?.ToString("n0", Thread.CurrentThread.CurrentUICulture); + return number?.ToString("n0", Thread.CurrentThread.CurrentCulture); } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs index 845ac0d6af4..18930c5b051 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs @@ -7,6 +7,7 @@ namespace Dnn.ExportImport.Components.Controllers using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Linq; @@ -301,7 +302,7 @@ protected void AddEventLog(int portalId, int userId, int jobId, string logTypeKe LogUserID = userId, }; - log.AddProperty("JobID", jobId.ToString()); + log.AddProperty("JobID", jobId.ToString(CultureInfo.InvariantCulture)); LogController.Instance.AddLog(log); } @@ -314,7 +315,7 @@ private static JobItem ToJobItem(ExportImportJob job) { JobId = job.JobId, PortalId = job.PortalId, - User = user?.DisplayName ?? user?.Username ?? job.CreatedByUserId.ToString(), + User = user?.DisplayName ?? user?.Username ?? job.CreatedByUserId.ToString(CultureInfo.InvariantCulture), JobType = Localization.GetString("JobType_" + job.JobType, Constants.SharedResources), Status = (int)job.JobStatus, Cancelled = job.IsCancelled, diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs index eafb7d10648..70f38869593 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs @@ -6,6 +6,7 @@ namespace Dnn.ExportImport.Components.Controllers using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using Dnn.ExportImport.Components.Common; @@ -46,7 +47,7 @@ public int QueueOperation(int userId, ExportDto exportDto) exportDto.ProductVersion = Globals.FormatVersion(DotNetNuke.Application.DotNetNukeContext.Current.Application.Version, true); var dbTime = DateUtils.GetDatabaseUtcTime(); exportDto.ToDateUtc = dbTime.AddMilliseconds(-dbTime.Millisecond); - var directory = dbTime.ToString("yyyy-MM-dd_HH-mm-ss"); + var directory = dbTime.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture); if (exportDto.ExportMode == ExportMode.Differential) { exportDto.FromDateUtc = this.GetLastJobTime(exportDto.PortalId, JobType.Export); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs b/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs index dd7b34c5d5e..659bf09caa0 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs @@ -8,6 +8,7 @@ namespace Dnn.ExportImport.Components.Engines using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.IO; using System.Linq; @@ -665,7 +666,7 @@ private static void SetLastJobStartTime(int scheduleId, DateTimeOffset time) scheduleId, Constants.LastJobStartTimeKey, time.ToUniversalTime() - .DateTime.ToString(Constants.JobRunDateTimeFormat)); + .DateTime.ToString(Constants.JobRunDateTimeFormat, CultureInfo.InvariantCulture)); } private static void DoPacking(ExportImportJob exportJob, string dbName) @@ -724,6 +725,7 @@ private static void CleanupDatabaseIfDirty(ExportImportRepository repository) catch (Exception e) { Logger.ErrorFormat( + CultureInfo.InvariantCulture, "Unable to clear {0} while calling CleanupDatabaseIfDirty. Error: {1}", type.Name, e.Message); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs b/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs index e758c2a1c38..e6112135aae 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs @@ -5,6 +5,7 @@ namespace Dnn.ExportImport.Components.Scheduler { using System; + using System.Globalization; using System.Text; using System.Threading; @@ -165,7 +166,7 @@ public override void DoWork() var sb = new StringBuilder(); var jobType = Localization.GetString("JobType_" + job.JobType, Constants.SharedResources); var jobStatus = Localization.GetString("JobStatus_" + job.JobStatus, Constants.SharedResources); - sb.AppendFormat("
    {0} {1}", jobType, jobStatus); + sb.AppendFormat(CultureInfo.InvariantCulture, "
    {0} {1}", jobType, jobStatus); var summary = result.Summary; if (summary.Count > 0) { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs index 82dd5618af1..3131631ff3e 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs @@ -5,6 +5,7 @@ namespace Dnn.ExportImport.Components.Services { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; @@ -68,7 +69,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var portalId = exportJob.PortalId; try { - var assetsFile = string.Format(this.assetsFolder, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); + var assetsFile = string.Format(CultureInfo.InvariantCulture, this.assetsFolder, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); if (this.CheckPoint.Stage == 0) { @@ -106,21 +107,18 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) CBO.FillCollection( DataProvider.Instance() .GetFiles(portalId, folder.FolderId, toDate, fromDate)).Where(x => x.Extension != Constants.TemplatesExtension).ToList(); - int? userId; - if (IsUserFolder(folder.FolderPath, out userId)) + if (IsUserFolder(folder.FolderPath, out var userId)) { isUserFolder = true; folder.UserId = userId; folder.Username = - UserController.GetUserById(portalId, Convert.ToInt32(userId))?.Username; + UserController.GetUserById(portalId, userId)?.Username; } - if (folder.ParentId != null && folder.ParentId > 0) + if (folder.ParentId is > 0) { // If parent id exists then change the parent folder id to parent id. - folder.ParentId = - this.Repository.GetItem( - x => x.FolderId == Convert.ToInt32(folder.ParentId))?.Id; + folder.ParentId = this.Repository.GetItem(x => x.FolderId == folder.ParentId)?.Id; } this.Repository.CreateItem(folder, null); @@ -138,8 +136,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.Repository.CreateItems(files, folder.Id); totalFilesExported += files.Count; - var folderOffset = portal.HomeDirectoryMapPath.Length + - (portal.HomeDirectoryMapPath.EndsWith("\\") ? 0 : 1); + var folderOffset = portal.HomeDirectoryMapPath.Length + (portal.HomeDirectoryMapPath.EndsWith(@"\", StringComparison.Ordinal) ? 0 : 1); if (folder.StorageLocation != (int)FolderController.StorageLocationTypes.DatabaseSecure) { @@ -180,9 +177,9 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; this.CheckPointStageCallback(this); - this.Result.AddSummary("Exported Folders", totalFolderExported.ToString()); - this.Result.AddSummary("Exported Folder Permissions", totalFolderPermissionsExported.ToString()); - this.Result.AddSummary("Exported Files", totalFilesExported.ToString()); + this.Result.AddSummary("Exported Folders", totalFolderExported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Exported Folder Permissions", totalFolderPermissionsExported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Exported Files", totalFilesExported.ToString(CultureInfo.InvariantCulture)); } } @@ -210,8 +207,8 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var currentIndex = skip; var portalId = importJob.PortalId; var portal = PortalController.Instance.GetPortal(portalId); - var assetsFile = string.Format(this.assetsFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); - var userFolderPath = string.Format(UsersAssetsTempFolder, portal.HomeDirectoryMapPath.TrimEnd('\\')); + var assetsFile = string.Format(CultureInfo.InvariantCulture, this.assetsFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); + var userFolderPath = string.Format(CultureInfo.InvariantCulture, UsersAssetsTempFolder, portal.HomeDirectoryMapPath.TrimEnd('\\')); if (this.CheckPoint.Stage == 0) { if (!File.Exists(assetsFile)) @@ -359,9 +356,9 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) : null; this.CheckPointStageCallback(this); - this.Result.AddSummary("Imported Folders", totalFolderImported.ToString()); - this.Result.AddSummary("Imported Folder Permissions", totalFolderPermissionsImported.ToString()); - this.Result.AddSummary("Imported Files", totalFilesImported.ToString()); + this.Result.AddSummary("Imported Folders", totalFolderImported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Imported Folder Permissions", totalFolderPermissionsImported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Imported Files", totalFilesImported.ToString(CultureInfo.InvariantCulture)); if (Directory.Exists(userFolderPath) && currentIndex == 0) { @@ -377,13 +374,13 @@ public override int GetImportTotal() return this.Repository.GetCount(); } - private static bool IsUserFolder(string folderPath, out int? userId) + private static bool IsUserFolder(string folderPath, out int userId) { - userId = null; + userId = -1; var match = UserFolderEx.Match(folderPath); if (match.Success) { - userId = int.Parse(match.Groups[1].Value); + userId = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); } return match.Success; @@ -392,7 +389,7 @@ private static bool IsUserFolder(string folderPath, out int? userId) private static void ProcessFolderPermission(ExportImportJob importJob, ImportDto importDto, ExportFolderPermission folderPermission, IEnumerable localPermissions) { var portalId = importJob.PortalId; - var noRole = Convert.ToInt32(Globals.glbRoleNothing); + var noRole = Convert.ToInt32(Globals.glbRoleNothing, CultureInfo.InvariantCulture); if (folderPermission == null) { return; @@ -436,7 +433,7 @@ private static void ProcessFolderPermission(ExportImportJob importJob, ImportDto existingFolderPermission.FolderPermissionId, folderPermission.FolderId, existingFolderPermission.PermissionId, - existingFolderPermission.RoleId ?? Convert.ToInt32(Globals.glbRoleNothing), + existingFolderPermission.RoleId ?? Convert.ToInt32(Globals.glbRoleNothing, CultureInfo.InvariantCulture), folderPermission.AllowAccess, existingFolderPermission.UserId ?? Null.NullInteger, modifiedBy); @@ -453,8 +450,8 @@ private static void ProcessFolderPermission(ExportImportJob importJob, ImportDto if (permissionId != null) { - folderPermission.PermissionId = Convert.ToInt32(permissionId); - if (folderPermission.UserId != null && folderPermission.UserId > 0 && !string.IsNullOrEmpty(folderPermission.Username)) + folderPermission.PermissionId = permissionId.Value; + if (folderPermission.UserId is > 0 && !string.IsNullOrEmpty(folderPermission.Username)) { folderPermission.UserId = userId; if (folderPermission.UserId == null) @@ -585,7 +582,7 @@ private static void SyncUserFolder(int portalId, ExportFolder folder) { var portal = PortalController.Instance.GetPortal(portalId); var tempUsersFolderPath = - $"{string.Format(UsersAssetsTempFolder, portal.HomeDirectoryMapPath.TrimEnd('\\'))}{folder.FolderPath}"; + string.Format(CultureInfo.InvariantCulture, UsersAssetsTempFolder, portal.HomeDirectoryMapPath.TrimEnd('\\')) + folder.FolderPath; var newUsersFolderPath = $"{portal.HomeDirectoryMapPath}{folder.FolderPath}"; if (!Directory.Exists(tempUsersFolderPath)) { @@ -603,12 +600,12 @@ private static void SyncUserFolder(int portalId, ExportFolder folder) var mFile in files.Select(file => new System.IO.FileInfo(file))) { - if (File.Exists(dirInfo + "\\" + mFile.Name)) + if (File.Exists(dirInfo + @"\" + mFile.Name)) { - File.Delete(dirInfo + "\\" + mFile.Name); + File.Delete(dirInfo + @"\" + mFile.Name); } - mFile.MoveTo(dirInfo + "\\" + mFile.Name); + mFile.MoveTo(dirInfo + @"\" + mFile.Name); } } @@ -683,14 +680,14 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor { folder.FolderMappingId = folderMapping.FolderMappingID; var createdBy = Util.GetUserIdByName(importJob, folder.CreatedByUserId, folder.CreatedByUserName); - if (folder.ParentId != null && folder.ParentId > 0) + if (folder.ParentId is > 0) { // Find the previously created parent folder id. folder.ParentId = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().GetFolder(portalId, folder.ParentFolderPath ?? string.Empty))?.FolderId; } // ignore folders which start with Users but are not user folders. - if (!folder.FolderPath.StartsWith(DefaultUsersFoldersPath)) + if (!folder.FolderPath.StartsWith(DefaultUsersFoldersPath, StringComparison.OrdinalIgnoreCase)) { folder.FolderId = DotNetNuke.Data.DataProvider.Instance() .AddFolder( @@ -711,7 +708,7 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor } // Case when the folder is a user folder. - else if (folder.UserId != null && folder.UserId > 0 && !string.IsNullOrEmpty(folder.Username)) + else if (folder.UserId is > 0 && !string.IsNullOrEmpty(folder.Username)) { var userInfo = UserController.GetUserByName(portalId, folder.Username); if (userInfo == null) diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs index a042421c9a0..000f98f5429 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs @@ -5,6 +5,7 @@ namespace Dnn.ExportImport.Components.Services { using System; + using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; @@ -57,8 +58,8 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var totalPackagesExported = 0; try { - var packagesZipFileFormat = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{{0}}\\{Constants.ExportZipPackages}"; - var packagesZipFile = string.Format(packagesZipFileFormat, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); + var packagesZipFileFormat = $@"{Globals.ApplicationMapPath}{Constants.ExportFolder}{{0}}\{Constants.ExportZipPackages}"; + var packagesZipFile = string.Format(CultureInfo.InvariantCulture, packagesZipFileFormat, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); if (this.CheckPoint.Stage == 0) { @@ -111,9 +112,9 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } finally { - this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; + this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex, }) : null; this.CheckPointStageCallback(this); - this.Result.AddSummary("Exported Packages", totalPackagesExported.ToString()); + this.Result.AddSummary("Exported Packages", totalPackagesExported.ToString(CultureInfo.InvariantCulture)); } } @@ -197,7 +198,7 @@ private static bool IsValidPackage(string filePath, DateTime fromDate, DateTime return false; } - return fileInfo.Name.StartsWith("Skin_") || fileInfo.Name.StartsWith("Container_"); + return fileInfo.Name.StartsWith("Skin_", StringComparison.OrdinalIgnoreCase) || fileInfo.Name.StartsWith("Container_", StringComparison.OrdinalIgnoreCase); } private static ExportPackage GenerateExportPackage(string filePath) diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs index ab4455cc24a..5448a572bf5 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs @@ -4,6 +4,7 @@ namespace Dnn.ExportImport.Components.Services { using System; + using System.Globalization; using System.IO; using System.Linq; @@ -55,7 +56,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var portalId = exportJob.PortalId; try { - var templatesFile = string.Format(this.templatesFolder, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); + var templatesFile = string.Format(CultureInfo.InvariantCulture, this.templatesFolder, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); if (this.CheckPoint.Stage == 0) { @@ -83,7 +84,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.Repository.CreateItem(template, null); totalTemplatesExported += 1; var folderOffset = portal.HomeDirectoryMapPath.Length + - (portal.HomeDirectoryMapPath.EndsWith("\\") ? 0 : 1); + (portal.HomeDirectoryMapPath.EndsWith(@"\", StringComparison.Ordinal) ? 0 : 1); var folder = FolderManager.Instance.GetFolder(template.FolderId); CompressionUtil.AddFileToArchive( @@ -110,9 +111,9 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } finally { - this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex }) : null; + this.CheckPoint.StageData = currentIndex > 0 ? JsonConvert.SerializeObject(new { skip = currentIndex, }) : null; this.CheckPointStageCallback(this); - this.Result.AddSummary("Exported Templates", totalTemplatesExported.ToString()); + this.Result.AddSummary("Exported Templates", totalTemplatesExported.ToString(CultureInfo.InvariantCulture)); } } @@ -131,7 +132,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } var portalId = importJob.PortalId; - var templatesFile = string.Format(this.templatesFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); + var templatesFile = string.Format(CultureInfo.InvariantCulture, this.templatesFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); var totalTemplates = this.GetImportTotal(); this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalTemplates : this.CheckPoint.TotalItems; @@ -160,7 +161,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) portal.HomeDirectoryMapPath, importDto.CollisionResolution == CollisionResolution.Overwrite); - this.Result.AddSummary("Imported templates", totalTemplates.ToString()); + this.Result.AddSummary("Imported templates", totalTemplates.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Stage++; this.CheckPoint.StageData = null; this.CheckPoint.Progress = 90; diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs index f1e2f040c9d..ee3c247966f 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs @@ -5,6 +5,7 @@ namespace Dnn.ExportImport.Components.Services { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; @@ -561,9 +562,9 @@ private static void RepairReferenceTabs(IList referenceTabs, IList if (localTab != null && int.TryParse(localTab.Url, out int urlTabId)) { var exportTab = exportTabs.FirstOrDefault(t => t.TabId == urlTabId); - if (exportTab != null && exportTab.LocalId.HasValue) + if (exportTab is { LocalId: not null, }) { - localTab.Url = exportTab.LocalId.ToString(); + localTab.Url = exportTab.LocalId.Value.ToString(CultureInfo.InvariantCulture); TabController.Instance.UpdateTab(localTab); } } @@ -731,7 +732,7 @@ private int ImportTabSettings(TabInfo localTab, ExportTab otherTab, bool isNew) var tabSettings = this.Repository.GetRelatedItems(otherTab.Id).ToList(); foreach (var other in tabSettings) { - var localValue = isNew ? string.Empty : Convert.ToString(localTab.TabSettings[other.SettingName]); + var localValue = isNew ? string.Empty : Convert.ToString(localTab.TabSettings[other.SettingName], CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(localValue)) { this.tabController.UpdateTabSetting(localTab.TabID, other.SettingName, other.SettingValue); @@ -791,7 +792,7 @@ private int ImportTabPermissions(TabInfo localTab, ExportTab otherTab, bool isNe return 0; } - var noRole = Convert.ToInt32(Globals.glbRoleNothing); + var noRole = Convert.ToInt32(Globals.glbRoleNothing, CultureInfo.InvariantCulture); var count = 0; var tabPermissions = this.Repository.GetRelatedItems(otherTab.Id).ToList(); var localTabPermissions = localTab.TabPermissions.OfType().ToList(); @@ -1086,10 +1087,10 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab this.totals.TotalContents += this.ImportPortableContent(localTab.TabID, local, otherModule, isNew); } - this.Result.AddLogEntry("Added module", local.ModuleID.ToString()); + this.Result.AddLogEntry("Added module", local.ModuleID.ToString(CultureInfo.InvariantCulture)); } - this.Result.AddLogEntry("Added tab module", local.TabModuleID.ToString()); + this.Result.AddLogEntry("Added tab module", local.TabModuleID.ToString(CultureInfo.InvariantCulture)); count++; } catch (Exception ex) @@ -1257,8 +1258,8 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab this.totals.TotalContents += this.ImportPortableContent(localTab.TabID, local, otherModule, isNew); } - this.Result.AddLogEntry("Updated tab module", local.TabModuleID.ToString()); - this.Result.AddLogEntry("Updated module", local.ModuleID.ToString()); + this.Result.AddLogEntry("Updated tab module", local.TabModuleID.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry("Updated module", local.ModuleID.ToString(CultureInfo.InvariantCulture)); count++; } @@ -1316,7 +1317,7 @@ private int ImportModuleSettings(ModuleInfo localModule, ExportModule otherModul var moduleSettings = this.Repository.GetRelatedItems(otherModule.Id).ToList(); foreach (var other in moduleSettings) { - var localValue = isNew ? string.Empty : Convert.ToString(localModule.ModuleSettings[other.SettingName]); + var localValue = isNew ? string.Empty : Convert.ToString(localModule.ModuleSettings[other.SettingName], CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(localValue)) { this.moduleController.UpdateModuleSetting(localModule.ModuleID, other.SettingName, other.SettingValue); @@ -1374,10 +1375,10 @@ private int ImportModuleSettings(ModuleInfo localModule, ExportModule otherModul private int ImportModulePermissions(ModuleInfo localModule, ExportModule otherModule, bool isNew) { var count = 0; - var noRole = Convert.ToInt32(Globals.glbRoleNothing); + var noRole = Convert.ToInt32(Globals.glbRoleNothing, CultureInfo.InvariantCulture); var modulePermissions = this.Repository.GetRelatedItems(otherModule.Id).ToList(); var localModulePermissions = isNew - ? new List() + ? [] : localModule.ModulePermissions.OfType().ToList(); foreach (var other in modulePermissions) { @@ -1399,7 +1400,7 @@ private int ImportModulePermissions(ModuleInfo localModule, ExportModule otherMo AllowAccess = other.AllowAccess, PermissionID = permissionId.Value, }; - if (other.UserID != null && other.UserID > 0 && !string.IsNullOrEmpty(other.Username)) + if (other.UserID is > 0 && !string.IsNullOrEmpty(other.Username)) { if (userId == null) { @@ -1514,6 +1515,7 @@ private int ImportPortableContent(int tabId, ModuleInfo localModule, ExportModul ex.Message, ReportLevel.Error); Logger.ErrorFormat( + CultureInfo.InvariantCulture, "ModuleContent: (Module ID={0}). Error: {1}{2}{3}", localModule.ModuleID, ex, @@ -1593,7 +1595,7 @@ private int ImportTabModuleSettings(ModuleInfo localTabModule, ExportTabModule o var tabModuleSettings = this.Repository.GetRelatedItems(otherTabModule.Id).ToList(); foreach (var other in tabModuleSettings) { - var localValue = isNew ? string.Empty : Convert.ToString(localTabModule.TabModuleSettings[other.SettingName]); + var localValue = isNew ? string.Empty : Convert.ToString(localTabModule.TabModuleSettings[other.SettingName], CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(localValue)) { // the next will clear the cache @@ -2074,16 +2076,16 @@ private void ReportImportTotals() private void ReportTotals(string prefix) { - this.Result.AddSummary(prefix + " Tabs", this.totals.TotalTabs.ToString()); - this.Result.AddLogEntry(prefix + " Tab Settings", this.totals.TotalTabSettings.ToString()); - this.Result.AddLogEntry(prefix + " Tab Permissions", this.totals.TotalTabPermissions.ToString()); - this.Result.AddLogEntry(prefix + " Tab Urls", this.totals.TotalTabUrls.ToString()); - this.Result.AddLogEntry(prefix + " Modules", this.totals.TotalModules.ToString()); - this.Result.AddLogEntry(prefix + " Module Settings", this.totals.TotalModuleSettings.ToString()); - this.Result.AddLogEntry(prefix + " Module Permissions", this.totals.TotalModulePermissions.ToString()); - this.Result.AddLogEntry(prefix + " Tab Modules", this.totals.TotalTabModules.ToString()); - this.Result.AddLogEntry(prefix + " Tab Module Settings", this.totals.TotalTabModuleSettings.ToString()); - this.Result.AddLogEntry(prefix + " Module Packages", this.totals.TotalPackages.ToString()); + this.Result.AddSummary(prefix + " Tabs", this.totals.TotalTabs.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Tab Settings", this.totals.TotalTabSettings.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Tab Permissions", this.totals.TotalTabPermissions.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Tab Urls", this.totals.TotalTabUrls.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Modules", this.totals.TotalModules.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Module Settings", this.totals.TotalModuleSettings.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Module Permissions", this.totals.TotalModulePermissions.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Tab Modules", this.totals.TotalTabModules.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Tab Module Settings", this.totals.TotalTabModuleSettings.ToString(CultureInfo.InvariantCulture)); + this.Result.AddLogEntry(prefix + " Module Packages", this.totals.TotalPackages.ToString(CultureInfo.InvariantCulture)); } private void UpdateTotalProcessedPackages() @@ -2236,7 +2238,7 @@ private void UpdateParentInPartialImportTabs(TabInfo localTab, ExportTab parentE } else { - tabWithoutParentId.Url = localTab.TabID.ToString(); + tabWithoutParentId.Url = localTab.TabID.ToString(CultureInfo.InvariantCulture); } this.tabController.UpdateTab(tabWithoutParentId); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs index c2e5922b28e..73af1f205cb 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs @@ -77,7 +77,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.Repository.CreateItems(portalSettings); } - this.Result.AddSummary("Exported Portal Settings", portalSettings.Count.ToString()); + this.Result.AddSummary("Exported Portal Settings", portalSettings.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 50; this.CheckPoint.ProcessedItems = portalSettings.Count; @@ -102,7 +102,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } this.Repository.CreateItems(portalLanguages); - this.Result.AddSummary("Exported Portal Languages", portalLanguages.Count.ToString()); + this.Result.AddSummary("Exported Portal Languages", portalLanguages.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 100; this.CheckPoint.Completed = true; this.CheckPoint.Stage++; @@ -131,7 +131,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var portalSettings = this.Repository.GetAllItems().ToList(); this.ProcessPortalSettings(importJob, importDto, portalSettings); this.CheckPoint.TotalItems = this.GetImportTotal(); - this.Result.AddSummary("Imported Portal Settings", portalSettings.Count.ToString()); + this.Result.AddSummary("Imported Portal Settings", portalSettings.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress += 50; this.CheckPoint.Stage++; this.CheckPoint.ProcessedItems = portalSettings.Count; @@ -145,7 +145,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { var portalLanguages = this.Repository.GetAllItems().ToList(); this.ProcessPortalLanguages(importJob, importDto, portalLanguages); - this.Result.AddSummary("Imported Portal Languages", portalLanguages.Count.ToString()); + this.Result.AddSummary("Imported Portal Languages", portalLanguages.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress += 50; this.CheckPoint.Completed = true; this.CheckPoint.Stage++; diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs index 01a0de27b2c..fcd4245fd4a 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs @@ -4,6 +4,7 @@ namespace Dnn.ExportImport.Components.Services { using System; + using System.Globalization; using System.Linq; using Dnn.ExportImport.Components.Common; @@ -65,7 +66,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } this.Repository.CreateItems(profileProperties); - this.Result.AddSummary("Exported Profile Properties", profileProperties.Count.ToString()); + this.Result.AddSummary("Exported Profile Properties", profileProperties.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 100; this.CheckPoint.ProcessedItems = profileProperties.Count; this.CheckPoint.Completed = true; @@ -122,7 +123,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } } - this.Result.AddSummary("Imported Profile Properties", profileProperties.Count.ToString()); + this.Result.AddSummary("Imported Profile Properties", profileProperties.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.ProcessedItems = profileProperties.Count; this.CheckPoint.Completed = true; this.CheckPoint.Progress = 100; diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs index 44393755235..8bdfc57f06e 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs @@ -6,6 +6,7 @@ namespace Dnn.ExportImport.Components.Services { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using Dnn.ExportImport.Components.Common; @@ -63,7 +64,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPointStageCallback(this); this.Repository.CreateItems(roleGroups); - this.Result.AddSummary("Exported Role Groups", roleGroups.Count.ToString()); + this.Result.AddSummary("Exported Role Groups", roleGroups.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.ProcessedItems = roleGroups.Count; this.CheckPoint.Progress = 30; this.CheckPoint.Stage++; @@ -87,7 +88,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } this.Repository.CreateItems(roles); - this.Result.AddSummary("Exported Roles", roles.Count.ToString()); + this.Result.AddSummary("Exported Roles", roles.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 80; this.CheckPoint.ProcessedItems += roles.Count; this.CheckPoint.Stage++; @@ -111,7 +112,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } this.Repository.CreateItems(roleSettings); - this.Result.AddSummary("Exported Role Settings", roleSettings.Count.ToString()); + this.Result.AddSummary("Exported Role Settings", roleSettings.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 100; this.CheckPoint.ProcessedItems += roleSettings.Count; this.CheckPoint.Completed = true; @@ -142,7 +143,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { this.ProcessRoleGroups(importJob, importDto, otherRoleGroups); this.Repository.UpdateItems(otherRoleGroups); - this.Result.AddSummary("Imported Role Groups", otherRoleGroups.Count.ToString()); + this.Result.AddSummary("Imported Role Groups", otherRoleGroups.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 40; this.CheckPoint.ProcessedItems = otherRoleGroups.Count; this.CheckPoint.Stage++; @@ -160,7 +161,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var otherRoles = this.Repository.GetAllItems().ToList(); if (this.CheckPoint.Stage == 1) { - this.Result.AddSummary("Imported Roles", otherRoles.Count.ToString()); + this.Result.AddSummary("Imported Roles", otherRoles.Count.ToString(CultureInfo.InvariantCulture)); this.ProcessRoles(importJob, importDto, otherRoleGroups, otherRoles); this.Repository.UpdateItems(otherRoles); this.CheckPoint.Progress = 50; @@ -182,7 +183,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var otherRoleSettings = this.Repository.GetAllItems().ToList(); this.ProcessRoleSettings(importJob, importDto, otherRoles, otherRoleSettings); this.Repository.UpdateItems(otherRoleSettings); - this.Result.AddSummary("Imported Role Settings", otherRoleSettings.Count.ToString()); + this.Result.AddSummary("Imported Role Settings", otherRoleSettings.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 100; this.CheckPoint.ProcessedItems += otherRoleSettings.Count; this.CheckPoint.Completed = true; @@ -273,7 +274,7 @@ private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, I }; RoleController.UpdateRoleGroup(roleGroup, false); changedGroups.Add(new RoleGroupItem(roleGroup.RoleGroupID, createdBy, modifiedBy)); - DataCache.ClearCache(string.Format(DataCache.RoleGroupsCacheKey, local.RoleGroupID)); + DataCache.ClearCache(string.Format(CultureInfo.InvariantCulture, DataCache.RoleGroupsCacheKey, local.RoleGroupID)); this.Result.AddLogEntry("Updated role group", other.RoleGroupName); break; default: diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs index 984f206b3ea..b276e0829be 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs @@ -6,6 +6,7 @@ namespace Dnn.ExportImport.Components.Services { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; @@ -58,8 +59,8 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var totalThemesExported = 0; try { - var packagesZipFileFormat = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{{0}}\\{Constants.ExportZipThemes}"; - var packagesZipFile = string.Format(packagesZipFileFormat, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); + var packagesZipFileFormat = $@"{Globals.ApplicationMapPath}{Constants.ExportFolder}{{0}}\{Constants.ExportZipThemes}"; + var packagesZipFile = string.Format(CultureInfo.InvariantCulture, packagesZipFileFormat, exportJob.Directory.TrimEnd('\\').TrimEnd('/')); if (this.CheckPoint.Stage == 0) { @@ -111,7 +112,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) finally { this.CheckPointStageCallback(this); - this.Result.AddSummary("Exported Themes", totalThemesExported.ToString()); + this.Result.AddSummary("Exported Themes", totalThemesExported.ToString(CultureInfo.InvariantCulture)); } } @@ -154,15 +155,15 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { try { - var checkFolder = file.Replace(tempFolder + "\\", string.Empty).Split('\\')[0]; - var relativePath = file.Substring((tempFolder + "\\" + checkFolder + "\\").Length); + var checkFolder = file.Replace($@"{tempFolder}\", string.Empty).Split('\\')[0]; + var relativePath = file.Substring($@"{tempFolder}\{checkFolder}\".Length); string targetPath; if (checkFolder == "_default") { targetPath = Path.Combine(Globals.HostMapPath, relativePath); } - else if (checkFolder.EndsWith("-System")) + else if (checkFolder.EndsWith("-System", StringComparison.OrdinalIgnoreCase)) { targetPath = Path.Combine(portalSettings.HomeSystemDirectoryMapPath, relativePath); } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs index bd041ebb3d2..bb4554a5a74 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs @@ -7,6 +7,7 @@ namespace Dnn.ExportImport.Components.Services using System; using System.Collections.Generic; using System.Data; + using System.Globalization; using System.Linq; using Dnn.ExportImport.Components.Common; @@ -158,7 +159,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) continue; } - if (!(roleId > Convert.ToInt32(Globals.glbRoleNothing))) + if (!(roleId > Convert.ToInt32(Globals.glbRoleNothing, CultureInfo.InvariantCulture))) { continue; } @@ -263,10 +264,10 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) finally { this.CheckPointStageCallback(this); - this.Result.AddSummary("Imported User Roles", totalUserRolesImported.ToString()); + this.Result.AddSummary("Imported User Roles", totalUserRolesImported.ToString(CultureInfo.InvariantCulture)); if (includeProfile) { - this.Result.AddSummary("Imported User Profiles", totalProfilesImported.ToString()); + this.Result.AddSummary("Imported User Profiles", totalProfilesImported.ToString(CultureInfo.InvariantCulture)); } } } @@ -311,9 +312,8 @@ private string GetUserPhotoId(int portalId, string importFileId, ExportUser user files.Any(x => x.FileName == profilePicture.FileName)) { return Convert.ToString( - files.First( - x => x.FileName == profilePicture.FileName) - .FileId); + files.First(x => x.FileName == profilePicture.FileName).FileId, + CultureInfo.InvariantCulture); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs index 9a65c538e0c..899699c2d82 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs @@ -7,6 +7,7 @@ namespace Dnn.ExportImport.Components.Services using System; using System.Collections.Generic; using System.Data; + using System.Globalization; using System.Linq; using Dnn.ExportImport.Components.Common; @@ -255,17 +256,17 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) finally { this.CheckPointStageCallback(this); - this.Result.AddSummary("Exported Users", totalUsersExported.ToString()); - this.Result.AddSummary("Exported User Portals", totalPortalsExported.ToString()); - this.Result.AddSummary("Exported User Roles", totalUserRolesExported.ToString()); + this.Result.AddSummary("Exported Users", totalUsersExported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Exported User Portals", totalPortalsExported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Exported User Roles", totalUserRolesExported.ToString(CultureInfo.InvariantCulture)); if (includeProfile) { - this.Result.AddSummary("Exported User Profiles", totalProfilesExported.ToString()); + this.Result.AddSummary("Exported User Profiles", totalProfilesExported.ToString(CultureInfo.InvariantCulture)); } - this.Result.AddSummary("Exported User Authentication", totalAuthenticationExported.ToString()); - this.Result.AddSummary("Exported Aspnet User", totalAspnetUserExported.ToString()); - this.Result.AddSummary("Exported Aspnet Membership", totalAspnetMembershipExported.ToString()); + this.Result.AddSummary("Exported User Authentication", totalAuthenticationExported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Exported Aspnet User", totalAspnetUserExported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Exported Aspnet Membership", totalAspnetMembershipExported.ToString(CultureInfo.InvariantCulture)); } } @@ -480,11 +481,11 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) finally { this.CheckPointStageCallback(this); - this.Result.AddSummary("Imported Users", totalUsersImported.ToString()); - this.Result.AddSummary("Imported User Portals", totalPortalsImported.ToString()); - this.Result.AddSummary("Import User Authentications", totalUserAuthenticationCount.ToString()); - this.Result.AddSummary("Imported Aspnet Users", totalAspnetUserImported.ToString()); - this.Result.AddSummary("Imported Aspnet Memberships", totalAspnetMembershipImported.ToString()); + this.Result.AddSummary("Imported Users", totalUsersImported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Imported User Portals", totalPortalsImported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Import User Authentications", totalUserAuthenticationCount.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Imported Aspnet Users", totalAspnetUserImported.ToString(CultureInfo.InvariantCulture)); + this.Result.AddSummary("Imported Aspnet Memberships", totalAspnetMembershipImported.ToString(CultureInfo.InvariantCulture)); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs index 3459d96872a..8fabd69ea05 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs @@ -6,6 +6,7 @@ namespace Dnn.ExportImport.Components.Services { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using Dnn.ExportImport.Components.Common; @@ -93,7 +94,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } this.Repository.CreateItems(taxonomyTerms); - this.Result.AddSummary("Exported Vocabularies", taxonomyTerms.Count.ToString()); + this.Result.AddSummary("Exported Vocabularies", taxonomyTerms.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 75; this.CheckPoint.ProcessedItems += taxonomyTerms.Count; this.CheckPoint.Stage++; @@ -108,7 +109,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } this.Repository.CreateItems(taxonomyVocabularies); - this.Result.AddSummary("Exported Terms", taxonomyVocabularies.Count.ToString()); + this.Result.AddSummary("Exported Terms", taxonomyVocabularies.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 100; this.CheckPoint.ProcessedItems += taxonomyVocabularies.Count; this.CheckPoint.Stage++; @@ -146,14 +147,14 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var otherVocabularies = this.Repository.GetAllItems().ToList(); this.ProcessVocabularies(importJob, importDto, otherScopeTypes, otherVocabularies); this.Repository.UpdateItems(otherVocabularies); - this.Result.AddSummary("Imported Vocabularies", otherVocabularies.Count.ToString()); + this.Result.AddSummary("Imported Vocabularies", otherVocabularies.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 60; this.CheckPoint.ProcessedItems += otherVocabularies.Count; var otherTaxonomyTerms = this.Repository.GetAllItems().ToList(); this.ProcessTaxonomyTerms(importJob, importDto, otherVocabularies, otherTaxonomyTerms); this.Repository.UpdateItems(otherTaxonomyTerms); - this.Result.AddSummary("Imported Terms", otherTaxonomyTerms.Count.ToString()); + this.Result.AddSummary("Imported Terms", otherTaxonomyTerms.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.Progress = 100; this.CheckPoint.ProcessedItems += otherTaxonomyTerms.Count; this.CheckPoint.Stage++; @@ -289,7 +290,7 @@ private void ProcessTaxonomyTerms(ExportImportJob importJob, ImportDto importDto dataService.UpdateSimpleTerm(term, modifiedBy); } - DataCache.ClearCache(string.Format(DataCache.TermCacheKey, term.TermId)); + DataCache.ClearCache(string.Format(CultureInfo.InvariantCulture, DataCache.TermCacheKey, term.TermId)); this.Result.AddLogEntry("Updated taxonomy", other.Name); break; default: diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs index 71e1db0a9e7..436ad46a1ea 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs @@ -6,6 +6,7 @@ namespace Dnn.ExportImport.Components.Services { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using Dnn.ExportImport.Components.Common; @@ -59,14 +60,11 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { var defaultWorkflowId = TabWorkflowSettings.Instance.GetDefaultTabWorkflowId(exportDto.PortalId); var defaultWorkflow = contentWorkflows.FirstOrDefault(w => w.WorkflowID == defaultWorkflowId); - if (defaultWorkflow != null) - { - defaultWorkflow.IsDefault = true; - } + defaultWorkflow?.IsDefault = true; this.CheckPoint.TotalItems = contentWorkflows.Count; this.Repository.CreateItems(contentWorkflows); - this.Result.AddLogEntry("Exported ContentWorkflows", contentWorkflows.Count.ToString()); + this.Result.AddLogEntry("Exported ContentWorkflows", contentWorkflows.Count.ToString(CultureInfo.InvariantCulture)); foreach (var workflow in contentWorkflows) { @@ -153,7 +151,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) workflowState.SendNotification = importState.SendNotification; workflowState.SendNotificationToAdministrators = importState.SendNotificationToAdministrators; workflowStateManager.UpdateWorkflowState(workflowState); - this.Result.AddLogEntry("Updated workflow state", workflowState.StateID.ToString()); + this.Result.AddLogEntry("Updated workflow state", workflowState.StateID.ToString(CultureInfo.InvariantCulture)); } } else @@ -168,7 +166,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) SendNotificationToAdministrators = importState.SendNotificationToAdministrators, }; WorkflowStateManager.Instance.AddWorkflowState(workflowState); - this.Result.AddLogEntry("Added workflow state", workflowState.StateID.ToString()); + this.Result.AddLogEntry("Added workflow state", workflowState.StateID.ToString(CultureInfo.InvariantCulture)); } importState.LocalId = workflowState.StateID; @@ -182,7 +180,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) if (permissionId != null) { - var noRole = Convert.ToInt32(Globals.glbRoleNothing); + var noRole = Convert.ToInt32(Globals.glbRoleNothing, CultureInfo.InvariantCulture); var userId = UserController.GetUserByName(importDto.PortalId, importPermission.Username)?.UserID; var roleId = Util.GetRoleIdByName(importDto.PortalId, importPermission.RoleID ?? noRole, importPermission.RoleName); @@ -195,7 +193,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) AllowAccess = importPermission.AllowAccess, }; - if (importPermission.UserID != null && importPermission.UserID > 0 && !string.IsNullOrEmpty(importPermission.Username)) + if (importPermission.UserID is > 0 && !string.IsNullOrEmpty(importPermission.Username)) { if (userId == null) { @@ -237,7 +235,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) importPermission.LocalId = permission.WorkflowStatePermissionID; this.Result.AddLogEntry( "Added workflow state permission", - permission.WorkflowStatePermissionID.ToString()); + permission.WorkflowStatePermissionID.ToString(CultureInfo.InvariantCulture)); } else { @@ -254,7 +252,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } this.Repository.UpdateItems(importStates); - this.Result.AddSummary("Imported Workflow", importWorkflows.Count.ToString()); + this.Result.AddSummary("Imported Workflow", importWorkflows.Count.ToString(CultureInfo.InvariantCulture)); this.CheckPoint.ProcessedItems++; this.CheckPointStageCallback(this); // no need to return; very small amount of data processed } diff --git a/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj b/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj index eb5b1f1f5e3..44fe36bbd42 100644 --- a/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj +++ b/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj @@ -13,7 +13,7 @@ Recommended true CS1591 - CS0618,SA1600,CA1305,CA1310,CA1707,CA1725 + CS0618,SA1600 true false diff --git a/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs b/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs index 4d425cb796a..67fc7a14a2e 100644 --- a/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs +++ b/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs @@ -2,20 +2,25 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace Dnn.ExportImport.Services -{ - using DotNetNuke.Web.Api; +namespace Dnn.ExportImport.Services +{ + using System.Diagnostics.CodeAnalysis; - public class ServiceRouteMapper : IServiceRouteMapper + using DotNetNuke.Web.Api; + + public class ServiceRouteMapper : IServiceRouteMapper { + private static readonly string[] Namespaces = [typeof(ServiceRouteMapper).Namespace,]; + /// - public void RegisterRoutes(IMapRoute routeManager) - { - routeManager.MapHttpRoute( - "SiteExportImport", - "default", - "{controller}/{action}", - new[] { typeof(ServiceRouteMapper).Namespace }); - } - } -} + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] + public void RegisterRoutes(IMapRoute routeManager) + { + routeManager.MapHttpRoute( + "SiteExportImport", + "default", + "{controller}/{action}", + Namespaces); + } + } +} diff --git a/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj b/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj index f29d04cb8fa..991dab03e79 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj +++ b/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj @@ -11,7 +11,7 @@ Recommended true CS1591 - CS0618,SA1600,CA1711 + CS0618,SA1600 true false diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs index ec7cceda3a6..30fa8a4bf55 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs @@ -2,50 +2,52 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace Dnn.ExportImport.Dto.Assets -{ - using System; - - public class ExportFolderPermission : BasicExportImportDto - { - public int FolderPermissionId { get; set; } - - public int FolderId { get; set; } - - public string FolderPath { get; set; } - - public int PermissionId { get; set; } - - public bool AllowAccess { get; set; } - - public int? RoleId { get; set; } - - public string RoleName { get; set; } - - public int? UserId { get; set; } - - public string Username { get; set; } - - public string DisplayName { get; set; } - - public string PermissionCode { get; set; } - - public int ModuleDefId { get; set; } - - public string PermissionKey { get; set; } - - public string PermissionName { get; set; } - - public int? CreatedByUserId { get; set; } - - public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - - public DateTime? CreatedOnDate { get; set; } - - public int? LastModifiedByUserId { get; set; } - - public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - - public DateTime? LastModifiedOnDate { get; set; } - } -} +namespace Dnn.ExportImport.Dto.Assets +{ + using System; + using System.Diagnostics.CodeAnalysis; + + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public class ExportFolderPermission : BasicExportImportDto + { + public int FolderPermissionId { get; set; } + + public int FolderId { get; set; } + + public string FolderPath { get; set; } + + public int PermissionId { get; set; } + + public bool AllowAccess { get; set; } + + public int? RoleId { get; set; } + + public string RoleName { get; set; } + + public int? UserId { get; set; } + + public string Username { get; set; } + + public string DisplayName { get; set; } + + public string PermissionCode { get; set; } + + public int ModuleDefId { get; set; } + + public string PermissionKey { get; set; } + + public string PermissionName { get; set; } + + public int? CreatedByUserId { get; set; } + + public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" + + public DateTime? CreatedOnDate { get; set; } + + public int? LastModifiedByUserId { get; set; } + + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" + + public DateTime? LastModifiedOnDate { get; set; } + } +} diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs index f5f8b8fecdc..4844ac5270e 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs @@ -2,45 +2,47 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -// ReSharper disable InconsistentNaming -namespace Dnn.ExportImport.Dto.Pages -{ - using System; - - public class ExportModulePermission : BasicExportImportDto - { - public int ModulePermissionID { get; set; } - - public int ModuleID { get; set; } - - public int PermissionID { get; set; } - - public string PermissionCode { get; set; } - - public string PermissionKey { get; set; } - - public string PermissionName { get; set; } - - public bool AllowAccess { get; set; } - - public int? RoleID { get; set; } - - public string RoleName { get; set; } - - public int? UserID { get; set; } - - public string Username { get; set; } - - public int? CreatedByUserID { get; set; } - - public DateTime? CreatedOnDate { get; set; } - - public int? LastModifiedByUserID { get; set; } - - public DateTime? LastModifiedOnDate { get; set; } - - public string CreatedByUserName { get; set; } - - public string LastModifiedByUserName { get; set; } - } -} +// ReSharper disable InconsistentNaming +namespace Dnn.ExportImport.Dto.Pages +{ + using System; + using System.Diagnostics.CodeAnalysis; + + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public class ExportModulePermission : BasicExportImportDto + { + public int ModulePermissionID { get; set; } + + public int ModuleID { get; set; } + + public int PermissionID { get; set; } + + public string PermissionCode { get; set; } + + public string PermissionKey { get; set; } + + public string PermissionName { get; set; } + + public bool AllowAccess { get; set; } + + public int? RoleID { get; set; } + + public string RoleName { get; set; } + + public int? UserID { get; set; } + + public string Username { get; set; } + + public int? CreatedByUserID { get; set; } + + public DateTime? CreatedOnDate { get; set; } + + public int? LastModifiedByUserID { get; set; } + + public DateTime? LastModifiedOnDate { get; set; } + + public string CreatedByUserName { get; set; } + + public string LastModifiedByUserName { get; set; } + } +} diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs index b22e753468e..987e883fba6 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs @@ -2,49 +2,51 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -// ReSharper disable InconsistentNaming -namespace Dnn.ExportImport.Dto.Pages -{ - using System; - - public class ExportTabPermission : BasicExportImportDto - { - public int TabPermissionID { get; set; } - - public int TabID { get; set; } - - public int PermissionID { get; set; } - - public string PermissionCode { get; set; } - - public string PermissionKey { get; set; } - - public string PermissionName { get; set; } - - public bool AllowAccess { get; set; } - - public int? RoleID { get; set; } - - public string RoleName { get; set; } - - public int? UserID { get; set; } - - public string Username { get; set; } - - public int? ModuleDefID { get; set; } - - public string FriendlyName { get; set; } // this is ModuleDefinition.FriendlyName - - public int? CreatedByUserID { get; set; } - - public DateTime? CreatedOnDate { get; set; } - - public int? LastModifiedByUserID { get; set; } - - public DateTime? LastModifiedOnDate { get; set; } - - public string CreatedByUserName { get; set; } - - public string LastModifiedByUserName { get; set; } - } -} +// ReSharper disable InconsistentNaming +namespace Dnn.ExportImport.Dto.Pages +{ + using System; + using System.Diagnostics.CodeAnalysis; + + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public class ExportTabPermission : BasicExportImportDto + { + public int TabPermissionID { get; set; } + + public int TabID { get; set; } + + public int PermissionID { get; set; } + + public string PermissionCode { get; set; } + + public string PermissionKey { get; set; } + + public string PermissionName { get; set; } + + public bool AllowAccess { get; set; } + + public int? RoleID { get; set; } + + public string RoleName { get; set; } + + public int? UserID { get; set; } + + public string Username { get; set; } + + public int? ModuleDefID { get; set; } + + public string FriendlyName { get; set; } // this is ModuleDefinition.FriendlyName + + public int? CreatedByUserID { get; set; } + + public DateTime? CreatedOnDate { get; set; } + + public int? LastModifiedByUserID { get; set; } + + public DateTime? LastModifiedOnDate { get; set; } + + public string CreatedByUserName { get; set; } + + public string LastModifiedByUserName { get; set; } + } +} diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs index f033541e84c..c6ea9016c8f 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs @@ -2,45 +2,47 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace Dnn.ExportImport.Dto.Workflow -{ - using System; - - public class ExportWorkflowStatePermission : BasicExportImportDto - { - public int WorkflowStatePermissionID { get; set; } - - public int StateID { get; set; } - - public int PermissionID { get; set; } - - public string PermissionCode { get; set; } - - public string PermissionKey { get; set; } - - public string PermissionName { get; set; } - - public bool AllowAccess { get; set; } - - public int? RoleID { get; set; } - - public string RoleName { get; set; } - - public int? UserID { get; set; } - - public string Username { get; set; } - - // public int? ModuleDefID { get; set; } - public int? CreatedByUserID { get; set; } - - public DateTime? CreatedOnDate { get; set; } - - public int? LastModifiedByUserID { get; set; } - - public DateTime? LastModifiedOnDate { get; set; } - - public string CreatedByUserName { get; set; } - - public string LastModifiedByUserName { get; set; } - } -} +namespace Dnn.ExportImport.Dto.Workflow +{ + using System; + using System.Diagnostics.CodeAnalysis; + + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] + public class ExportWorkflowStatePermission : BasicExportImportDto + { + public int WorkflowStatePermissionID { get; set; } + + public int StateID { get; set; } + + public int PermissionID { get; set; } + + public string PermissionCode { get; set; } + + public string PermissionKey { get; set; } + + public string PermissionName { get; set; } + + public bool AllowAccess { get; set; } + + public int? RoleID { get; set; } + + public string RoleName { get; set; } + + public int? UserID { get; set; } + + public string Username { get; set; } + + // public int? ModuleDefID { get; set; } + public int? CreatedByUserID { get; set; } + + public DateTime? CreatedOnDate { get; set; } + + public int? LastModifiedByUserID { get; set; } + + public DateTime? LastModifiedOnDate { get; set; } + + public string CreatedByUserName { get; set; } + + public string LastModifiedByUserName { get; set; } + } +} diff --git a/DNN Platform/Modules/Groups/Create.ascx.cs b/DNN Platform/Modules/Groups/Create.ascx.cs index 557ae2a511c..f66e758fe79 100644 --- a/DNN Platform/Modules/Groups/Create.ascx.cs +++ b/DNN Platform/Modules/Groups/Create.ascx.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Modules.Groups; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Web.UI; @@ -106,7 +107,7 @@ private void Create_Click(object sender, EventArgs e) { if (modulePermissionInfo.PermissionKey == "MODGROUP" && modulePermissionInfo.AllowAccess) { - if (modulePermissionInfo.RoleId > int.Parse(Globals.glbRoleNothing)) + if (modulePermissionInfo.RoleId > int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture)) { modRoles.Add(this.roleController.GetRoleById(this.PortalId, modulePermissionInfo.RoleId)); } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs index 9d5cda53129..ccb5087b2b8 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs @@ -726,12 +726,12 @@ private string DeTokeniseLinks(string content, int portalId) { var portal = PortalController.Instance.GetPortal(portalId); var portalRoot = UrlUtils.Combine(Globals.ApplicationPath, portal.HomeDirectory); - if (!portalRoot.StartsWith("/")) + if (!portalRoot.StartsWith("/", StringComparison.Ordinal)) { portalRoot = "/" + portalRoot; } - if (!portalRoot.EndsWith("/")) + if (!portalRoot.EndsWith("/", StringComparison.Ordinal)) { portalRoot = portalRoot + "/"; } @@ -746,12 +746,12 @@ private string TokeniseLinks(string content, int portalId) // Replace any relative portal root reference by a token "{{PortalRoot}}" var portal = PortalController.Instance.GetPortal(portalId); var portalRoot = UrlUtils.Combine(Globals.ApplicationPath, portal.HomeDirectory); - if (!portalRoot.StartsWith("/")) + if (!portalRoot.StartsWith("/", StringComparison.Ordinal)) { portalRoot = "/" + portalRoot; } - if (!portalRoot.EndsWith("/")) + if (!portalRoot.EndsWith("/", StringComparison.Ordinal)) { portalRoot = portalRoot + "/"; } diff --git a/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs b/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs index ff4389844e6..12248c988e3 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs @@ -201,7 +201,7 @@ private string UpdateTelerikEncryptionKey(string keyName) Config.AddAppSetting(xmlConfig, keyName, newKey); // save a copy of the existing web.config - var backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); + var backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), @"\"); strError += Config.Save(this.applicationStatusInfo, xmlConfig, backupFolder + "web_.config") + Environment.NewLine; // save the web.config diff --git a/DNN Platform/Modules/Journal/FileUploadController.cs b/DNN Platform/Modules/Journal/FileUploadController.cs index 4528a83551d..a0776309456 100644 --- a/DNN Platform/Modules/Journal/FileUploadController.cs +++ b/DNN Platform/Modules/Journal/FileUploadController.cs @@ -23,7 +23,7 @@ public class FileUploadController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileUploadController)); - private static readonly List ImageExtensions = new List { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG", ".ICO", ".SVG" }; + private static readonly HashSet ImageExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG", ".ICO", ".SVG", }; [DnnAuthorize] [HttpPost] @@ -41,15 +41,15 @@ public HttpResponseMessage UploadFile() Logger.Error(exc); } - return this.IframeSafeJson(statuses); + return IframeSafeJson(statuses); } private static bool IsImageExtension(string extension) { - return ImageExtensions.Contains(extension.ToUpper()); + return ImageExtensions.Contains(extension); } - private HttpResponseMessage IframeSafeJson(List statuses) + private static HttpResponseMessage IframeSafeJson(List statuses) { // return json but label it as plain text return new HttpResponseMessage diff --git a/DNN Platform/Modules/Journal/View.ascx.cs b/DNN Platform/Modules/Journal/View.ascx.cs index dbd85ac7c82..9008f4d391a 100644 --- a/DNN Platform/Modules/Journal/View.ascx.cs +++ b/DNN Platform/Modules/Journal/View.ascx.cs @@ -24,33 +24,47 @@ namespace DotNetNuke.Modules.Journal public partial class View : JournalModuleBase { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public int PageSize = 20; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool AllowPhotos = true; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool AllowFiles = true; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public int MaxMessageLength = 250; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool CanRender = true; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool ShowEditor = true; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool CanComment = true; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool IsGroup; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string BaseUrl; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public string ProfilePage; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public int Gid = -1; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public int Pid = -1; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public long MaxUploadSize = Config.GetMaxUploadSize(); [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public bool IsPublicGroup; private readonly INavigationManager navigationManager; @@ -191,7 +205,7 @@ private void Page_Load(object sender, EventArgs e) try { this.BaseUrl = Globals.ApplicationPath; - this.BaseUrl = this.BaseUrl.EndsWith("/") ? this.BaseUrl : this.BaseUrl + "/"; + this.BaseUrl = this.BaseUrl.EndsWith("/", StringComparison.Ordinal) ? this.BaseUrl : this.BaseUrl + "/"; this.BaseUrl += "DesktopModules/Journal/"; this.ProfilePage = this.navigationManager.NavigateURL(this.PortalSettings.UserTabId, string.Empty, new[] { "userId=xxx" }); diff --git a/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs b/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs index c98945f85b7..18921d24eb9 100644 --- a/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs +++ b/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs @@ -18,10 +18,13 @@ namespace DotNetNuke.Modules.MemberDirectory.ViewModels public partial class MemberDirectorySettingsModel : SettingsModel { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public IList ProfileProperties; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public IList Relationships; [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] + [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Breaking change")] public IList Groups; } } diff --git a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs index 037173d32f4..32500468d94 100644 --- a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs +++ b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Modules.RazorHost { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Web.UI.WebControls; @@ -279,7 +280,7 @@ private void LoadScripts() { string scriptPath = script.Replace(basePath, string.Empty); var item = new ListItem(scriptPath, scriptPath); - if (!string.IsNullOrEmpty(scriptFileSetting) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) + if (!string.IsNullOrEmpty(scriptFileSetting) && string.Equals(scriptPath, scriptFileSetting, StringComparison.OrdinalIgnoreCase)) { item.Selected = true; } @@ -292,8 +293,8 @@ private void DisplayFile() { string scriptFile = string.Format(this.razorScriptFileFormatString, this.scriptList.SelectedValue); - this.lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", this.LocalResourceFile), scriptFile); - this.lblModuleControl.Text = string.Format(Localization.GetString("SourceControl", this.LocalResourceFile), this.ModuleControl); + this.lblSourceFile.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("SourceFile", this.LocalResourceFile), scriptFile); + this.lblModuleControl.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("SourceControl", this.LocalResourceFile), this.ModuleControl); } private void CmdCancel_Click(object sender, EventArgs e) diff --git a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs index 840810bc08c..677520a555d 100644 --- a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Modules.RazorHost { using System; + using System.Globalization; using System.IO; using System.Web.UI.WebControls; @@ -103,7 +104,7 @@ private void DisplayFile() string scriptFile = string.Format(this.razorScriptFileFormatString, this.scriptList.SelectedValue); string srcFile = this.Server.MapPath(scriptFile); - this.lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", this.LocalResourceFile), scriptFile); + this.lblSourceFile.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("SourceFile", this.LocalResourceFile), scriptFile); StreamReader objStreamReader = null; objStreamReader = File.OpenText(srcFile); diff --git a/DNN Platform/Modules/ResourceManager/Components/Common/Utils.cs b/DNN Platform/Modules/ResourceManager/Components/Common/Utils.cs index 30b780abf72..e5cb640c15d 100644 --- a/DNN Platform/Modules/ResourceManager/Components/Common/Utils.cs +++ b/DNN Platform/Modules/ResourceManager/Components/Common/Utils.cs @@ -50,7 +50,7 @@ public static int GetFolderGroupId(int folderId) var prefixLength = Constants.GroupFolderPathStart.Length; var folderGroupIdString = folderPath.Substring(prefixLength - 1); - folderGroupIdString = folderGroupIdString.Substring(0, folderGroupIdString.IndexOf("/")); + folderGroupIdString = folderGroupIdString.Substring(0, folderGroupIdString.IndexOf("/", StringComparison.Ordinal)); if (!int.TryParse(folderGroupIdString, out var folderGroupId)) { diff --git a/DNN Platform/Modules/ResourceManager/Components/LocalizationController.cs b/DNN Platform/Modules/ResourceManager/Components/LocalizationController.cs index f682f227caa..f0ee0d92a3b 100644 --- a/DNN Platform/Modules/ResourceManager/Components/LocalizationController.cs +++ b/DNN Platform/Modules/ResourceManager/Components/LocalizationController.cs @@ -1,252 +1,252 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace Dnn.Modules.ResourceManager.Components -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Threading; - using System.Web.Caching; - using System.Xml; - - using Dnn.Modules.ResourceManager.Components.Models; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Framework; - using DotNetNuke.Services.Cache; - - /// Provides localization services. - public class LocalizationController : ServiceLocator, ILocalizationController - { - /// - public string CultureName => Instance.CultureName; - - /// - public Dictionary GetLocalizedDictionary(string resourceFile, string culture) => - Instance.GetLocalizedDictionary(resourceFile, culture); - - /// - public Dictionary GetLocalizedDictionary(string resourceFile, string culture, Localization localization) => - Instance.GetLocalizedDictionary(resourceFile, culture, localization); - - /// - public long GetResxTimeStamp(string resourceFile, Localization localization) - => Instance.GetResxTimeStamp(resourceFile, localization); - - /// - protected override Func GetFactory() - { - return () => new LocalizationControllerImplementation(); - } - - /// The localization controller implementation. - private class LocalizationControllerImplementation : ILocalizationController - { - private static readonly TimeSpan FiveMinutes = TimeSpan.FromMinutes(5); - private static readonly TimeSpan OneHour = TimeSpan.FromHours(1); - - /// - public string CultureName - { - get { return Thread.CurrentThread.CurrentUICulture.Name; } +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace Dnn.Modules.ResourceManager.Components +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Threading; + using System.Web.Caching; + using System.Xml; + + using Dnn.Modules.ResourceManager.Components.Models; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; + using DotNetNuke.Services.Cache; + + /// Provides localization services. + public class LocalizationController : ServiceLocator, ILocalizationController + { + /// + public string CultureName => Instance.CultureName; + + /// + public Dictionary GetLocalizedDictionary(string resourceFile, string culture) => + Instance.GetLocalizedDictionary(resourceFile, culture); + + /// + public Dictionary GetLocalizedDictionary(string resourceFile, string culture, Localization localization) => + Instance.GetLocalizedDictionary(resourceFile, culture, localization); + + /// + public long GetResxTimeStamp(string resourceFile, Localization localization) + => Instance.GetResxTimeStamp(resourceFile, localization); + + /// + protected override Func GetFactory() + { + return () => new LocalizationControllerImplementation(); + } + + /// The localization controller implementation. + private class LocalizationControllerImplementation : ILocalizationController + { + private static readonly TimeSpan FiveMinutes = TimeSpan.FromMinutes(5); + private static readonly TimeSpan OneHour = TimeSpan.FromHours(1); + + /// + public string CultureName + { + get { return Thread.CurrentThread.CurrentUICulture.Name; } + } + + /// + public long GetResxTimeStamp(string resourceFile, Localization localization) + { + return this.GetLastModifiedTime(resourceFile, this.CultureName, localization).Ticks; } - /// - public long GetResxTimeStamp(string resourceFile, Localization localization) - { - return this.GetLastModifiedTime(resourceFile, this.CultureName, localization).Ticks; + /// + public Dictionary GetLocalizedDictionary(string resourceFile, string culture, Localization localization) + { + Requires.NotNullOrEmpty("resourceFile", resourceFile); + Requires.NotNullOrEmpty("culture", culture); + + var cacheKey = string.Format(CultureInfo.CurrentCulture, localization.ResxDataCacheKey, culture, resourceFile); + if (DataCache.GetCache(cacheKey) is Dictionary localizedDict) + { + return localizedDict; + } + + var dictionary = new Dictionary(); + + foreach ( + var kvp in + GetLocalizationValues(resourceFile, culture).Where(kvp => !dictionary.ContainsKey(kvp.Key))) + { + dictionary[kvp.Key] = kvp.Value; + } + + DataCache.SetCache( + cacheKey, + dictionary, + default(DNNCacheDependency), + Cache.NoAbsoluteExpiration, + FiveMinutes, + CacheItemPriority.Normal, + null); + + return dictionary; } - /// - public Dictionary GetLocalizedDictionary(string resourceFile, string culture, Localization localization) - { - Requires.NotNullOrEmpty("resourceFile", resourceFile); - Requires.NotNullOrEmpty("culture", culture); - - var cacheKey = string.Format(localization.ResxDataCacheKey, culture, resourceFile); - var localizedDict = DataCache.GetCache(cacheKey) as Dictionary; - if (localizedDict != null) - { - return localizedDict; - } - - var dictionary = new Dictionary(); - - foreach ( - var kvp in - GetLocalizationValues(resourceFile, culture).Where(kvp => !dictionary.ContainsKey(kvp.Key))) - { - dictionary[kvp.Key] = kvp.Value; - } - - DataCache.SetCache( - cacheKey, - dictionary, - default(DNNCacheDependency), - Cache.NoAbsoluteExpiration, - FiveMinutes, - CacheItemPriority.Normal, - null); - - return dictionary; + /// + public Dictionary GetLocalizedDictionary(string resourceFile, string culture) + { + Requires.NotNullOrEmpty("resourceFile", resourceFile); + Requires.NotNullOrEmpty("culture", culture); + + var cacheKey = string.Format(Constants.LocalizationDataCacheKey, culture, resourceFile); + var localizedDict = DataCache.GetCache(cacheKey) as Dictionary; + if (localizedDict != null) + { + return localizedDict; + } + + var dictionary = new Dictionary(); + foreach ( + var kvp in + GetLocalizationValues(resourceFile, culture).Where(kvp => !dictionary.ContainsKey(kvp.Key))) + { + dictionary[kvp.Key] = kvp.Value; + } + + DataCache.SetCache( + cacheKey, + dictionary, + default(DNNCacheDependency), + Cache.NoAbsoluteExpiration, + Constants.FiveMinutes, + CacheItemPriority.Normal, + null); + + return dictionary; } - /// - public Dictionary GetLocalizedDictionary(string resourceFile, string culture) - { - Requires.NotNullOrEmpty("resourceFile", resourceFile); - Requires.NotNullOrEmpty("culture", culture); - - var cacheKey = string.Format(Constants.LocalizationDataCacheKey, culture, resourceFile); - var localizedDict = DataCache.GetCache(cacheKey) as Dictionary; - if (localizedDict != null) - { - return localizedDict; - } - - var dictionary = new Dictionary(); - foreach ( - var kvp in - GetLocalizationValues(resourceFile, culture).Where(kvp => !dictionary.ContainsKey(kvp.Key))) - { - dictionary[kvp.Key] = kvp.Value; - } - - DataCache.SetCache( - cacheKey, - dictionary, - default(DNNCacheDependency), - Cache.NoAbsoluteExpiration, - Constants.FiveMinutes, - CacheItemPriority.Normal, - null); - - return dictionary; - } - - private static string GetNameAttribute(XmlNode node) - { - if (node.Attributes != null) - { - var attribute = node.Attributes.GetNamedItem("name"); - if (attribute != null) - { - return attribute.Value; - } - } - - return null; - } - - private static void AssertHeaderValue(IEnumerable headers, string key, string value) - { - var header = - headers.FirstOrDefault( - x => GetNameAttribute(x).Equals(key, StringComparison.InvariantCultureIgnoreCase)); - if (header != null) - { - if (!header.InnerText.Equals(value, StringComparison.InvariantCultureIgnoreCase)) - { - throw new ApplicationException(string.Format("Resource header '{0}' != '{1}'", key, value)); - } - } - else - { - throw new ApplicationException(string.Format("Resource header '{0}' is missing", key)); - } - } - - private static IEnumerable> GetLocalizationValues(string fullPath, string culture) - { - using ( - var stream = new FileStream( - System.Web.HttpContext.Current.Server.MapPath(fullPath), - FileMode.Open, - FileAccess.Read)) - { - var document = new XmlDocument { XmlResolver = null }; - document.Load(stream); - - var headers = document.SelectNodes(@"/root/resheader").Cast().ToArray(); - AssertHeaderValue(headers, "resmimetype", "text/microsoft-resx"); - - foreach (var xmlNode in document.SelectNodes("/root/data").Cast()) - { - var name = GetNameAttribute(xmlNode); - - const string textPostFix = ".Text"; - if (name.EndsWith(textPostFix)) - { - name = name.Substring(0, name.Length - textPostFix.Length); - } - - if (string.IsNullOrEmpty(name)) - { - continue; - } - - var key = name; - if (key.Contains(".")) - { - key = name + textPostFix; - } - - var value = DotNetNuke.Services.Localization.Localization.GetString(key, fullPath, culture); - - yield return new KeyValuePair(name, value); - } - } - } - - private DateTime GetLastModifiedTime(string resourceFile, string culture, Localization localization) - { - Requires.NotNullOrEmpty("culture", culture); - - var cacheKey = string.Format(localization.ResxModifiedDateCacheKey, culture); - var cachedData = DataCache.GetCache(cacheKey); - if (cachedData is DateTime) - { - return (DateTime)DataCache.GetCache(cacheKey); - } - - var lastModifiedDate = this.GetLastModifiedTimeInternal(resourceFile, culture); - - DataCache.SetCache( - cacheKey, - lastModifiedDate, - default(DNNCacheDependency), - Cache.NoAbsoluteExpiration, - OneHour, - CacheItemPriority.Normal, - null); - - return lastModifiedDate; - } - - private DateTime GetLastModifiedTimeInternal(string resourceFile, string culture) - { - var cultureSpecificFile = System.Web.HttpContext.Current.Server.MapPath( - resourceFile.Replace(".resx", string.Empty) + "." + culture + ".resx"); - var lastModifiedDate = DateTime.MinValue; - - if (File.Exists(cultureSpecificFile)) - { - lastModifiedDate = File.GetLastWriteTime(cultureSpecificFile); - } - else - { - var cultureNeutralFile = System.Web.HttpContext.Current.Server.MapPath(resourceFile); - if (File.Exists(cultureNeutralFile)) - { - lastModifiedDate = File.GetLastWriteTime(cultureNeutralFile); - } - } - - return lastModifiedDate; - } - } - } -} + private static string GetNameAttribute(XmlNode node) + { + if (node.Attributes != null) + { + var attribute = node.Attributes.GetNamedItem("name"); + if (attribute != null) + { + return attribute.Value; + } + } + + return null; + } + + private static void AssertHeaderValue(IEnumerable headers, string key, string value) + { + var header = + headers.FirstOrDefault( + x => GetNameAttribute(x).Equals(key, StringComparison.InvariantCultureIgnoreCase)); + if (header != null) + { + if (!header.InnerText.Equals(value, StringComparison.InvariantCultureIgnoreCase)) + { + throw new ApplicationException(string.Format("Resource header '{0}' != '{1}'", key, value)); + } + } + else + { + throw new ApplicationException(string.Format("Resource header '{0}' is missing", key)); + } + } + + private static IEnumerable> GetLocalizationValues(string fullPath, string culture) + { + using ( + var stream = new FileStream( + System.Web.HttpContext.Current.Server.MapPath(fullPath), + FileMode.Open, + FileAccess.Read)) + { + var document = new XmlDocument { XmlResolver = null }; + document.Load(stream); + + var headers = document.SelectNodes(@"/root/resheader").Cast().ToArray(); + AssertHeaderValue(headers, "resmimetype", "text/microsoft-resx"); + + foreach (var xmlNode in document.SelectNodes("/root/data").Cast()) + { + var name = GetNameAttribute(xmlNode); + + const string textPostFix = ".Text"; + if (name.EndsWith(textPostFix)) + { + name = name.Substring(0, name.Length - textPostFix.Length); + } + + if (string.IsNullOrEmpty(name)) + { + continue; + } + + var key = name; + if (key.Contains(".")) + { + key = name + textPostFix; + } + + var value = DotNetNuke.Services.Localization.Localization.GetString(key, fullPath, culture); + + yield return new KeyValuePair(name, value); + } + } + } + + private DateTime GetLastModifiedTime(string resourceFile, string culture, Localization localization) + { + Requires.NotNullOrEmpty("culture", culture); + + var cacheKey = string.Format(CultureInfo.CurrentCulture, localization.ResxModifiedDateCacheKey, culture); + var cachedData = DataCache.GetCache(cacheKey); + if (cachedData is DateTime) + { + return (DateTime)DataCache.GetCache(cacheKey); + } + + var lastModifiedDate = this.GetLastModifiedTimeInternal(resourceFile, culture); + + DataCache.SetCache( + cacheKey, + lastModifiedDate, + default(DNNCacheDependency), + Cache.NoAbsoluteExpiration, + OneHour, + CacheItemPriority.Normal, + null); + + return lastModifiedDate; + } + + private DateTime GetLastModifiedTimeInternal(string resourceFile, string culture) + { + var cultureSpecificFile = System.Web.HttpContext.Current.Server.MapPath( + resourceFile.Replace(".resx", string.Empty) + "." + culture + ".resx"); + var lastModifiedDate = DateTime.MinValue; + + if (File.Exists(cultureSpecificFile)) + { + lastModifiedDate = File.GetLastWriteTime(cultureSpecificFile); + } + else + { + var cultureNeutralFile = System.Web.HttpContext.Current.Server.MapPath(resourceFile); + if (File.Exists(cultureNeutralFile)) + { + lastModifiedDate = File.GetLastWriteTime(cultureNeutralFile); + } + } + + return lastModifiedDate; + } + } + } +} diff --git a/DNN Platform/Modules/ResourceManager/Components/PermissionHelper.cs b/DNN Platform/Modules/ResourceManager/Components/PermissionHelper.cs index 4e0622bbe55..473e254adc0 100644 --- a/DNN Platform/Modules/ResourceManager/Components/PermissionHelper.cs +++ b/DNN Platform/Modules/ResourceManager/Components/PermissionHelper.cs @@ -6,6 +6,7 @@ namespace Dnn.Modules.ResourceManager.Components { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using Dnn.Modules.ResourceManager.Services.Dto; @@ -86,7 +87,7 @@ public static void EnsureDefaultRoles(this Permissions dto) // Show also default roles dto.EnsureRole(RoleController.Instance.GetRoleById(PortalSettings.Current.PortalId, PortalSettings.Current.RegisteredRoleId), false, true); - dto.EnsureRole(new RoleInfo { RoleID = int.Parse(Globals.glbRoleAllUsers), RoleName = Globals.glbRoleAllUsersName }, false, true); + dto.EnsureRole(new RoleInfo { RoleID = int.Parse(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture), RoleName = Globals.glbRoleAllUsersName, }, false, true); } /// Ensures the dto has the given role. @@ -171,8 +172,8 @@ public static object GetRoles(RoleProvider roleProvider, IRoleController roleCon } // Retrieves roles info - data.Roles.Add(new { RoleID = int.Parse(Globals.glbRoleUnauthUser), GroupId = -1, RoleName = Globals.glbRoleUnauthUserName }); - data.Roles.Add(new { RoleID = int.Parse(Globals.glbRoleAllUsers), GroupId = -1, RoleName = Globals.glbRoleAllUsersName }); + data.Roles.Add(new { RoleID = int.Parse(Globals.glbRoleUnauthUser, CultureInfo.InvariantCulture), GroupId = -1, RoleName = Globals.glbRoleUnauthUserName }); + data.Roles.Add(new { RoleID = int.Parse(Globals.glbRoleAllUsers, CultureInfo.InvariantCulture), GroupId = -1, RoleName = Globals.glbRoleAllUsersName }); foreach (var role in roleController.GetRoles(portalId).OrderBy(r => r.RoleName)) { data.Roles.Add(new { GroupId = role.RoleGroupID, RoleId = role.RoleID, Name = role.RoleName }); @@ -221,7 +222,7 @@ public static IEnumerable AsFolderPermissions(this IEnumer IFolderPermissionInfo iInfo = info; iInfo.FolderId = folderId; iInfo.PermissionId = permission.PermissionId; - iInfo.RoleId = int.Parse(Globals.glbRoleNothing); + iInfo.RoleId = int.Parse(Globals.glbRoleNothing, CultureInfo.InvariantCulture); iInfo.UserId = p.UserId; return info; }); diff --git a/DNN Platform/Modules/ResourceManager/Components/ThumbnailsManager.cs b/DNN Platform/Modules/ResourceManager/Components/ThumbnailsManager.cs index 598031b651e..52f289502ee 100644 --- a/DNN Platform/Modules/ResourceManager/Components/ThumbnailsManager.cs +++ b/DNN Platform/Modules/ResourceManager/Components/ThumbnailsManager.cs @@ -54,7 +54,7 @@ private enum ThumbnailExtensions public bool ThumbnailAvailable(string fileName) { var ext = Path.GetExtension(fileName).ToUpperInvariant(); - ext = ext.StartsWith(".") ? ext.Substring(1) : ext; + ext = ext.StartsWith(".", StringComparison.Ordinal) ? ext.Substring(1) : ext; return Enum.TryParse(ext, out ThumbnailExtensions _); } diff --git a/DNN Platform/Modules/Samples/Dnn.ContactList.Spa/Components/SettingsPropertyAccess.cs b/DNN Platform/Modules/Samples/Dnn.ContactList.Spa/Components/SettingsPropertyAccess.cs index 80d8f62935b..165cb3aadd1 100644 --- a/DNN Platform/Modules/Samples/Dnn.ContactList.Spa/Components/SettingsPropertyAccess.cs +++ b/DNN Platform/Modules/Samples/Dnn.ContactList.Spa/Components/SettingsPropertyAccess.cs @@ -66,7 +66,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format switch (propertyName) { case "IsFormEnabled": - propertyValue = _service.IsFormEnabled(_moduleId, _tabId).ToString().ToLower(); + propertyValue = _service.IsFormEnabled(_moduleId, _tabId).ToString().ToLowerInvariant(); break; case "EmailRegex": propertyValue = Regex.Escape(Globals.glbEmailRegEx); diff --git a/DNN Platform/Modules/Samples/Dnn.ContactList.SpaReact/Components/ContextTokens.cs b/DNN Platform/Modules/Samples/Dnn.ContactList.SpaReact/Components/ContextTokens.cs index fda4d55303b..eedfe76bc25 100644 --- a/DNN Platform/Modules/Samples/Dnn.ContactList.SpaReact/Components/ContextTokens.cs +++ b/DNN Platform/Modules/Samples/Dnn.ContactList.SpaReact/Components/ContextTokens.cs @@ -1,46 +1,49 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information - -using System.Globalization; -using System.Web; -using DotNetNuke.Entities.Users; -using DotNetNuke.Services.Tokens; -using DotNetNuke.UI.Modules; -using Newtonsoft.Json; - -namespace Dnn.ContactList.SpaReact.Components -{ - public class ContextTokens : IPropertyAccess - { - public CacheLevel Cacheability => CacheLevel.notCacheable; - private readonly SecurityContext security; - private readonly ModuleInstanceContext moduleContext; - - public ContextTokens(ModuleInstanceContext moduleContext, UserInfo user) - { - this.moduleContext = moduleContext; - this.security = new SecurityContext(moduleContext.Configuration, user); - } - - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) - { - switch (propertyName.ToLower()) - { - case "security": - return HttpUtility.HtmlAttributeEncode(JsonConvert.SerializeObject(this.security)); - case "module": - return HttpUtility.HtmlAttributeEncode(JsonConvert.SerializeObject(new - { - this.moduleContext.ModuleId, - this.moduleContext.TabId, - this.moduleContext.TabModuleId, - this.moduleContext.PortalId, - })); - default: - propertyNotFound = true; - return string.Empty; - } - } - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +using System.Globalization; +using System.Web; +using DotNetNuke.Entities.Users; +using DotNetNuke.Services.Tokens; +using DotNetNuke.UI.Modules; +using Newtonsoft.Json; + +namespace Dnn.ContactList.SpaReact.Components +{ + public class ContextTokens : IPropertyAccess + { + public CacheLevel Cacheability => CacheLevel.notCacheable; + private readonly SecurityContext security; + private readonly ModuleInstanceContext moduleContext; + + public ContextTokens(ModuleInstanceContext moduleContext, UserInfo user) + { + this.moduleContext = moduleContext; + this.security = new SecurityContext(moduleContext.Configuration, user); + } + + /// + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + { + switch (propertyName.ToUpperInvariant()) + { + case "SECURITY": + return HttpUtility.HtmlAttributeEncode(JsonConvert.SerializeObject(this.security)); + case "MODULE": + return HttpUtility.HtmlAttributeEncode( + JsonConvert.SerializeObject( + new + { + this.moduleContext.ModuleId, + this.moduleContext.TabId, + this.moduleContext.TabModuleId, + this.moduleContext.PortalId, + })); + default: + propertyNotFound = true; + return string.Empty; + } + } + } +} diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj index 2f3871bdfa9..a00fe1d9469 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj @@ -9,7 +9,6 @@ Recommended true CS1591,0618 - CA1725 true false diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs index ca5811fa506..118f7697fa8 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider { using System; + using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Threading; @@ -46,7 +47,7 @@ public override void Clear(string type, string data) // Clear the local cache this.ClearCacheInternal(type, data, true); - // Per API implementation standards only notify others if expiration has not been desabled + // Per API implementation standards only notify others if expiration has not been disabled if (CacheExpirationDisable) { return; @@ -57,6 +58,7 @@ public override void Clear(string type, string data) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override void Remove(string key) { // Remove from local cache diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs index 5c3676a4079..b7ab363cea9 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Providers.AspNetClientCapabilityProvider using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Web; @@ -58,7 +59,7 @@ public AspNetClientCapability(string userAgent, HttpCapabilitiesBase browserCaps this.ScreenResolutionHeightInPixels = browserCaps.ScreenPixelsHeight; this.IsTouchScreen = false; this.BrowserName = browserCaps.Browser; - this.properties = browserCaps.Capabilities?.Cast().ToDictionary(kvp => Convert.ToString(kvp.Key), kvp => Convert.ToString(kvp.Value)) ?? new Dictionary(0); + this.properties = browserCaps.Capabilities?.Cast().ToDictionary(kvp => Convert.ToString(kvp.Key, CultureInfo.InvariantCulture), kvp => Convert.ToString(kvp.Value, CultureInfo.InvariantCulture)) ?? new Dictionary(0); this.SupportsFlash = false; this.HtmlPreferedDTD = null; diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.cs index 7dd706fbd38..7f9abe55420 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Providers.AspNetClientCapabilityProvider using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; + using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Web; using System.Web.Configuration; @@ -155,6 +156,7 @@ public override IClientCapability GetClientCapability(string userAgent) } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public override IClientCapability GetClientCapabilityById(string deviceId) { Requires.NotNullOrEmpty("deviceId", deviceId); diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj index 19de784c537..2d01bd76f29 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj @@ -13,7 +13,6 @@ Recommended true CS1591,0618 - CA1305,CA1707,CA1725 true false diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs index 82d18c9d0b3..fa2f0d2c53c 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Providers.AspNetClientCapabilityProvider.Properties { using System; + using System.Diagnostics.CodeAnalysis; /// A list of constants to use with the purchase solution. public static class RetailerConstants @@ -17,10 +18,12 @@ public static class RetailerConstants #pragma warning disable SA1310 // Field should not contain an underscore /// The url to send purchasers to. [Obsolete("Deprecated in DotNetNuke 9.8.1. Use RetailerUrl instead. Scheduled removal in v11.0.0.")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] public const string RETAILER_URL = RetailerUrl; /// The name of the retailer. [Obsolete("Deprecated in DotNetNuke 9.8.1. Use RetailerName instead. Scheduled removal in v11.0.0.")] + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] public const string RETAILER_NAME = RetailerName; #pragma warning restore SA1310 // Field should not contain an underscore } diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/BlobItemExtensions.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/BlobItemExtensions.cs index 654d0172254..255532bd9ea 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/BlobItemExtensions.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/BlobItemExtensions.cs @@ -2,21 +2,23 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider -{ - using Microsoft.WindowsAzure.Storage.Blob; +namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider +{ + using System; - internal static class BlobItemExtensions - { - public static string RelativePath(this IListBlobItem item) - { - var filterUrl = item.Container.Uri.AbsoluteUri; - if (!filterUrl.EndsWith("/")) - { - filterUrl = filterUrl + "/"; - } - - return item.Uri.AbsoluteUri.Replace(filterUrl, string.Empty); - } - } -} + using Microsoft.WindowsAzure.Storage.Blob; + + internal static class BlobItemExtensions + { + public static string RelativePath(this IListBlobItem item) + { + var filterUrl = item.Container.Uri.AbsoluteUri; + if (!filterUrl.EndsWith("/", StringComparison.Ordinal)) + { + filterUrl = filterUrl + "/"; + } + + return item.Uri.AbsoluteUri.Replace(filterUrl, string.Empty); + } + } +} diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/Browser.aspx.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/Browser.aspx.cs index 4ccb9457580..5450748fb43 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/Browser.aspx.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/Browser.aspx.cs @@ -10,6 +10,7 @@ namespace DNNConnect.CKEditorProvider.Browser; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; +using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -375,7 +376,7 @@ public List GetFiles(IFolderInfo currentFolderInfo) return null; default: - if (extension.StartsWith(".")) + if (extension.StartsWith(".", StringComparison.Ordinal)) { extension = extension.Replace(".", string.Empty); } @@ -551,7 +552,7 @@ protected virtual string GetJavaScriptCode(string fileName, string fileUrl, bool if (!string.IsNullOrEmpty(fileUrl) && !string.IsNullOrEmpty(fileName)) { // If we have both, combine them - fileUrl = !fileUrl.EndsWith("/") + fileUrl = !fileUrl.EndsWith("/", StringComparison.Ordinal) ? $"{fileUrl}/{fileName}" : $"{fileUrl}{fileName}"; } @@ -597,7 +598,7 @@ protected virtual string GetJavaScriptCode(string fileName, string fileUrl, bool /// Returns the formatted JavaScript block. protected virtual string GetJsUploadCode(string fileName, string fileUrl) { - fileUrl = string.Format(!fileUrl.EndsWith("/") ? "{0}/{1}" : "{0}{1}", fileUrl, fileName); + fileUrl = string.Format(!fileUrl.EndsWith("/", StringComparison.Ordinal) ? "{0}/{1}" : "{0}{1}", fileUrl, fileName); var httpRequest = HttpContext.Current.Request; @@ -1289,7 +1290,7 @@ private static string MapUrl(string sPath) string sAppPath = HttpContext.Current.Server.MapPath("~"); return HttpContext.Current.Request.ApplicationPath + - sPath.Replace(sAppPath, string.Empty).Replace("\\", "/"); + sPath.Replace(sAppPath, string.Empty).Replace(@"\", "/"); } /// Get File Name without .resources extension. @@ -1385,7 +1386,7 @@ from permission in this.permissionDefinitionService.GetDefinitionsByFolder() { FolderID = folderInfo.FolderID, UserID = currentUserInfo.UserID, - RoleID = Convert.ToInt32(Globals.glbRoleNothing), + RoleID = Convert.ToInt32(Globals.glbRoleNothing, CultureInfo.InvariantCulture), AllowAccess = true, }; foreach (var folderPermission in folderPermissions) @@ -1579,7 +1580,7 @@ private IFolderInfo StartingDir() var folderStart = startingFolderInfo.PhysicalPath; - folderStart = folderStart.Substring(this.portalSettings.HomeDirectoryMapPath.Length).Replace("\\", "/"); + folderStart = folderStart.Substring(this.portalSettings.HomeDirectoryMapPath.Length).Replace(@"\", "/"); startingFolderInfo = this.folderManager.AddFolder(this.portalSettings.PortalId, folderStart); @@ -1604,7 +1605,7 @@ private IFolderInfo GetUserFolderInfo(string startingDir) { var folderStart = userFolderPath; - folderStart = folderStart.Substring(this.portalSettings.HomeDirectoryMapPath.Length).Replace("\\", "/"); + folderStart = folderStart.Substring(this.portalSettings.HomeDirectoryMapPath.Length).Replace(@"\", "/"); userFolderInfo = this.folderManager.AddFolder(this.portalSettings.PortalId, folderStart); @@ -1620,7 +1621,7 @@ private IFolderInfo GetUserFolderInfo(string startingDir) { var folderStart = userFolderPath; - folderStart = folderStart.Substring(this.portalSettings.HomeDirectoryMapPath.Length).Replace("\\", "/"); + folderStart = folderStart.Substring(this.portalSettings.HomeDirectoryMapPath.Length).Replace(@"\", "/"); userFolderInfo = this.folderManager.AddFolder(this.portalSettings.PortalId, folderStart); @@ -2290,7 +2291,7 @@ private void UploadFile(HttpPostedFile file, string command) if (command == "EasyImageUpload") { - var fileUrl = string.Format(!MapUrl(uploadPhysicalPath).EndsWith("/") ? "{0}/{1}" : "{0}{1}", MapUrl(uploadPhysicalPath), fileName); + var fileUrl = string.Format(!MapUrl(uploadPhysicalPath).EndsWith("/", StringComparison.Ordinal) ? "{0}/{1}" : "{0}{1}", MapUrl(uploadPhysicalPath), fileName); this.Response.ClearContent(); this.Response.ContentType = "application/json"; this.Response.Write($$"""{"default": {{HttpUtility.JavaScriptStringEncode(fileUrl, addDoubleQuotes: true)}}}"""); @@ -2300,7 +2301,7 @@ private void UploadFile(HttpPostedFile file, string command) // querystring parameter responseType equals "json" when the request comes from drag/drop if (this.Request.QueryString["responseType"]?.Equals("json", StringComparison.InvariantCultureIgnoreCase) == true) { - var fileUrl = string.Format(!MapUrl(uploadPhysicalPath).EndsWith("/") ? "{0}/{1}" : "{0}{1}", MapUrl(uploadPhysicalPath), fileName); + var fileUrl = string.Format(!MapUrl(uploadPhysicalPath).EndsWith("/", StringComparison.Ordinal) ? "{0}/{1}" : "{0}{1}", MapUrl(uploadPhysicalPath), fileName); this.Response.ClearContent(); this.Response.ContentType = "application/json"; this.Response.Write($$"""{"uploaded": 1, "fileName": {{HttpUtility.JavaScriptStringEncode(fileName, addDoubleQuotes: true)}}, "url": {{HttpUtility.JavaScriptStringEncode(fileUrl, addDoubleQuotes: true)}}}"""); @@ -2783,7 +2784,7 @@ private void FindAnchorsOnTab(TabInfo selectedTab) var tabUrl = selectedTab.FullUrl; - if (tabUrl.StartsWith("/")) + if (tabUrl.StartsWith("/", StringComparison.Ordinal)) { var requestUrl = HttpContext.Current.Request.Url; tabUrl = $"{requestUrl.Scheme}://{requestUrl.Authority}{tabUrl}"; diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/ProcessImage.ashx.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/ProcessImage.ashx.cs index 3b8c24cb9e3..b2e82398c3d 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/ProcessImage.ashx.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/ProcessImage.ashx.cs @@ -255,7 +255,7 @@ private static Image RotateImage(Image img, double rotationAngle) private static string CleanName(string name) { - name = name.Replace("\\", "/"); + name = name.Replace(@"\", "/"); if (name.Contains("/")) { name = name.Substring(name.LastIndexOf('/') + 1); diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Controls/UrlControl.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Controls/UrlControl.cs index 5ec6fb8fba1..e57059ef2e3 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Controls/UrlControl.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Controls/UrlControl.cs @@ -6,6 +6,7 @@ namespace DNNConnect.CKEditorProvider.Controls { using System; using System.Collections; + using System.Globalization; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; @@ -195,7 +196,7 @@ public void BindData() this.ReloadFiles = false; - var url = Convert.ToString(this.ViewState["Url"]); + var url = Convert.ToString(this.ViewState["Url"], CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(url)) { @@ -205,9 +206,9 @@ public void BindData() var urlType = Globals.GetURLType(url).ToString("g").Substring(0, 1); if (urlType == "F") { - if (url.ToLower().StartsWith("fileid=")) + if (url.StartsWith("fileid=", StringComparison.OrdinalIgnoreCase)) { - var objFile = FileManager.Instance.GetFile(int.Parse(url.Substring(7))); + var objFile = FileManager.Instance.GetFile(int.Parse(url.Substring(7), CultureInfo.InvariantCulture)); if (objFile != null) { diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Tabs.ashx.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Tabs.ashx.cs index c358bb5e442..599a4689e29 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Tabs.ashx.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Tabs.ashx.cs @@ -4,6 +4,7 @@ namespace DNNConnect.CKEditorProvider { + using System; using System.Text; using System.Text.RegularExpressions; using System.Web; @@ -76,7 +77,7 @@ public void ProcessRequest(HttpContext context) } } - if (pagesArray.ToString().EndsWith(",")) + if (pagesArray.ToString().EndsWith(",", StringComparison.Ordinal)) { pagesArray.Remove(pagesArray.Length - 1, 1); } diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/Utility.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/Utility.cs index e3dbcd45a0c..826d6cdcddd 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/Utility.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/Utility.cs @@ -221,7 +221,7 @@ public static string ConvertUnicodeChars(string input) input = regS.Replace(input, "s"); input = regSS.Replace(input, "S"); input = regDot.Replace(input, "."); // full-width dot -> ASCII period - input = regBackslash.Replace(input, "\\"); // backslash-like chars -> ASCII backslash + input = regBackslash.Replace(input, @"\"); // backslash-like chars -> ASCII backslash input = input.Replace("�", string.Empty); @@ -271,11 +271,11 @@ public static IFolderInfo ConvertFilePathToFolderInfo(string folderPath, IPortal { if (!string.IsNullOrEmpty(portalSettings.HomeDirectoryMapPath) && folderPath.Length >= portalSettings.HomeDirectoryMapPath.Length) { - folderPath = folderPath.Substring(portalSettings.HomeDirectoryMapPath.Length).Replace("\\", "/"); + folderPath = folderPath.Substring(portalSettings.HomeDirectoryMapPath.Length).Replace(@"\", "/"); } else { - folderPath = folderPath.Replace("\\", "/"); + folderPath = folderPath.Replace(@"\", "/"); } return FolderManager.Instance.GetFolder(portalSettings.PortalId, folderPath); @@ -406,7 +406,7 @@ public static T FindControl(Control startingControl, string id) where T : Control { // this is null by default - T found = default(T); + T found = null; int controlCount = startingControl.Controls.Count; @@ -420,7 +420,7 @@ public static T FindControl(Control startingControl, string id) { found = startingControl.Controls[i] as T; - if (found.ID.ToLower().Contains(id.ToLower())) + if (found.ID.Contains(id, StringComparison.OrdinalIgnoreCase)) { break; } @@ -443,7 +443,7 @@ public static T FindControl(Control startingControl, string id) } /// Gets the size of the max upload. - /// if set to Returns Value as kilo byte otherwise as byte. + /// if set to Returns Value as kilobyte otherwise as byte. /// /// Returns the Max. Upload Size. /// @@ -525,5 +525,10 @@ private static bool CheckIfUserHasFolderAccess(int folderId, IPortalSettings por return false; } } + + private static bool Contains(this string @this, string value, StringComparison comparisonType) + { + return @this.IndexOf(value, comparisonType) > -1; + } } } diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Web/EditorControl.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Web/EditorControl.cs index 3b10e1983a6..9aaaa649d08 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Web/EditorControl.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Web/EditorControl.cs @@ -115,14 +115,14 @@ PropertyInfo info in if (info.PropertyType.Name == "Boolean") { - this.settings[xmlAttributeAttribute.AttributeName] = settingValue.ToLower(); + this.settings[xmlAttributeAttribute.AttributeName] = settingValue.ToLowerInvariant(); } else { switch (info.Name) { case "ToolbarLocation": - this.settings[xmlAttributeAttribute.AttributeName] = settingValue.ToLower(); + this.settings[xmlAttributeAttribute.AttributeName] = settingValue.ToLowerInvariant(); break; case "EnterMode": case "ShiftEnterMode": @@ -182,7 +182,7 @@ PropertyInfo info in codeMirrorArray.AppendFormat("{0}: '{1}',", xmlAttribute.AttributeName, HttpUtility.JavaScriptStringEncode(codeMirrorSettingValue)); break; case "Boolean": - codeMirrorArray.AppendFormat("{0}: {1},", xmlAttribute.AttributeName, codeMirrorSettingValue.ToLower()); + codeMirrorArray.AppendFormat("{0}: {1},", xmlAttribute.AttributeName, codeMirrorSettingValue.ToLowerInvariant()); break; } } @@ -219,15 +219,15 @@ PropertyInfo info in wordcountArray.AppendFormat("{0}: '{1}',", xmlAttribute.AttributeName, HttpUtility.JavaScriptStringEncode(wordCountSettingValue)); break; case "Boolean": - wordcountArray.AppendFormat("{0}: {1},", xmlAttribute.AttributeName, wordCountSettingValue.ToLower()); + wordcountArray.AppendFormat("{0}: {1},", xmlAttribute.AttributeName, wordCountSettingValue.ToLowerInvariant()); break; } } - var wordcountSettings = wordcountArray.ToString(); + var wordCountSettings = wordcountArray.ToString(); this.settings["wordcount"] = - $"{{ {wordcountSettings.Remove(wordcountSettings.Length - 1, 1)} }}"; + $"{{ {wordCountSettings.Remove(wordCountSettings.Length - 1, 1)} }}"; } break; @@ -865,7 +865,7 @@ private void CKEditorInit(object sender, EventArgs e) // Get Parent ModuleID From this ClientID string sClientId = this.ClientID.Substring(this.ClientID.IndexOf("ctr") + 3); - sClientId = sClientId.Remove(this.ClientID.IndexOf("_")); + sClientId = sClientId.Remove(this.ClientID.IndexOf("_", StringComparison.Ordinal)); if (!int.TryParse(sClientId, out this.parentModulId)) { @@ -1014,7 +1014,7 @@ private string FormatUrl(string inputUrl) return formattedUrl; } - if (inputUrl.StartsWith("http://") || inputUrl.StartsWith("https://") || inputUrl.StartsWith("//")) + if (inputUrl.StartsWith("http://") || inputUrl.StartsWith("https://") || inputUrl.StartsWith("//", StringComparison.Ordinal)) { formattedUrl = inputUrl; } @@ -1246,7 +1246,7 @@ private void GenerateEditorLoadScript() // Is boolean state or string if (value.Equals("true", StringComparison.InvariantCultureIgnoreCase) || value.Equals("false", StringComparison.InvariantCultureIgnoreCase) || value.StartsWith("[") - || value.StartsWith("{") || Utility.IsNumeric(value)) + || value.StartsWith("{", StringComparison.Ordinal) || Utility.IsNumeric(value)) { if (value.Equals("True")) { diff --git a/DNN Platform/Syndication/DotNetNuke.Syndication.csproj b/DNN Platform/Syndication/DotNetNuke.Syndication.csproj index a12919872d5..eaa403340cc 100644 --- a/DNN Platform/Syndication/DotNetNuke.Syndication.csproj +++ b/DNN Platform/Syndication/DotNetNuke.Syndication.csproj @@ -14,7 +14,7 @@ Recommended true CS1591 - CA1305,CA1310,CA1711,CA3075 + CA3075 true false diff --git a/DNN Platform/Syndication/OPML/Opml.cs b/DNN Platform/Syndication/OPML/Opml.cs index e35dbd1cc5d..64bb5e0cf76 100644 --- a/DNN Platform/Syndication/OPML/Opml.cs +++ b/DNN Platform/Syndication/OPML/Opml.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Services.Syndication { using System; + using System.Globalization; using System.Xml; using DotNetNuke.Instrumentation; @@ -122,12 +123,12 @@ public static Opml LoadFromXml(XmlDocument doc) if (dateCreated != null) { - @out.DateCreated = DateTime.Parse(dateCreated.InnerText); + @out.DateCreated = DateTime.Parse(dateCreated.InnerText, CultureInfo.InvariantCulture); } if (dateModified != null) { - @out.DateModified = DateTime.Parse(dateModified.InnerText); + @out.DateModified = DateTime.Parse(dateModified.InnerText, CultureInfo.InvariantCulture); } if (ownerName != null) @@ -340,7 +341,7 @@ internal static OpmlOutline ParseXml(XmlElement node) newOutline.IsBreakpoint = ParseElement(node, "isBreakpoint") == "true" ? true : false; try { - newOutline.Created = DateTime.Parse(ParseElement(node, "created")); + newOutline.Created = DateTime.Parse(ParseElement(node, "created"), CultureInfo.InvariantCulture); } catch (Exception ex) { diff --git a/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs b/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs index 72ca573c9ba..3865ab7653e 100644 --- a/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs +++ b/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs @@ -101,7 +101,7 @@ private static string GetTempFileNamePrefixFromUrl(Uri uri) { try { - return string.Format("{0}_{1:x8}", uri.Host.Replace('.', '_'), uri.AbsolutePath.GetHashCode()); + return $"{uri.Host.Replace('.', '_')}_{uri.AbsolutePath.GetHashCode():x8}"; } catch { @@ -226,9 +226,9 @@ private void TrySaveToDisk(XmlDocument doc, Uri uri, DateTime utcExpiry) return; } - doc.InsertBefore(doc.CreateComment(string.Format("{0}@{1}", utcExpiry.ToBinary(), uri.AbsoluteUri)), doc.DocumentElement); + doc.InsertBefore(doc.CreateComment($"{utcExpiry.ToBinary()}@{uri.AbsoluteUri}"), doc.DocumentElement); - string fileName = string.Format("{0}_{1:x8}.opml.resources", GetTempFileNamePrefixFromUrl(uri), Guid.NewGuid().ToString().GetHashCode()); + string fileName = $"{GetTempFileNamePrefixFromUrl(uri)}_{Guid.NewGuid().ToString().GetHashCode():x8}.opml.resources"; try { diff --git a/DNN Platform/Syndication/RSS/RssDownloadManager.cs b/DNN Platform/Syndication/RSS/RssDownloadManager.cs index 61b6ecfbb18..cda0f7183d5 100644 --- a/DNN Platform/Syndication/RSS/RssDownloadManager.cs +++ b/DNN Platform/Syndication/RSS/RssDownloadManager.cs @@ -87,7 +87,7 @@ private static string GetTempFileNamePrefixFromUrl(string url) try { var uri = new Uri(url); - return string.Format("{0}_{1:x8}", uri.Host.Replace('.', '_'), uri.AbsolutePath.GetHashCode()); + return $"{uri.Host.Replace('.', '_')}_{uri.AbsolutePath.GetHashCode():x8}"; } catch { @@ -213,9 +213,9 @@ private void TrySaveToDisk(XmlDocument doc, string url, DateTime utcExpiry) return; } - doc.InsertBefore(doc.CreateComment(string.Format("{0}@{1}", utcExpiry.ToBinary(), url)), doc.DocumentElement); + doc.InsertBefore(doc.CreateComment($"{utcExpiry.ToBinary()}@{url}"), doc.DocumentElement); - string fileName = string.Format("{0}_{1:x8}.rss.resources", GetTempFileNamePrefixFromUrl(url), Guid.NewGuid().ToString().GetHashCode()); + string fileName = $"{GetTempFileNamePrefixFromUrl(url)}_{Guid.NewGuid().ToString().GetHashCode():x8}.rss.resources"; try { diff --git a/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs b/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs index eed458907aa..5f20e58ccdc 100644 --- a/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs +++ b/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs @@ -4,17 +4,20 @@ namespace DotNetNuke.Services.Syndication { using System; + using System.Diagnostics.CodeAnalysis; using System.Web; using System.Xml; /// A function which handles the event. /// The event source, i.e. the instance. /// Empty event args. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public delegate void InitEventHandler(object source, EventArgs e); /// A function which handles the event. /// The event source, i.e. the instance. /// Empty event args. + [SuppressMessage("Microsoft.Design", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Breaking change")] public delegate void PreRenderEventHandler(object source, EventArgs e); /// Base class for RssHttpHandler - Generic handler and strongly typed ones are derived from it. diff --git a/DNN Platform/Syndication/RSS/RssXmlHelper.cs b/DNN Platform/Syndication/RSS/RssXmlHelper.cs index e69eb99dd1a..c1f243bbcfe 100644 --- a/DNN Platform/Syndication/RSS/RssXmlHelper.cs +++ b/DNN Platform/Syndication/RSS/RssXmlHelper.cs @@ -161,7 +161,7 @@ private static bool NodeHasSubElements(XmlNode node) private static string ResolveAppRelativeLinkToUrl(string link) { - if (!string.IsNullOrEmpty(link) && link.StartsWith("~/")) + if (!string.IsNullOrEmpty(link) && link.StartsWith("~/", StringComparison.Ordinal)) { HttpContext context = HttpContext.Current; diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs index 4c1441552b9..508a9903c28 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs @@ -2,32 +2,33 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DNN.Integration.Test.Framework.Helpers -{ - public static class DnnDataHelper - { - private static int? _portalId; - - public static int PortalId - { - get - { - if (!_portalId.HasValue) - { - var alias = AppConfigHelper.SiteUrl.Replace("http://", string.Empty).Replace("https://", string.Empty); - if (alias.EndsWith("/")) - { - alias = alias.Substring(0, alias.Length - 1); - } - - var query = string.Format( - "SELECT TOP(1) PortalID FROM {{objectQualifier}}PortalAlias WHERE HTTPAlias='{0}'", alias); - var id = DatabaseHelper.ExecuteScalar(query); - _portalId = id; - } - - return _portalId.Value; - } - } - } -} +namespace DNN.Integration.Test.Framework.Helpers +{ + using System; + + public static class DnnDataHelper + { + private static int? _portalId; + + public static int PortalId + { + get + { + if (!_portalId.HasValue) + { + var alias = AppConfigHelper.SiteUrl.Replace("http://", string.Empty).Replace("https://", string.Empty); + if (alias.EndsWith("/", StringComparison.Ordinal)) + { + alias = alias.Substring(0, alias.Length - 1); + } + + var query = $"SELECT TOP(1) PortalID FROM {{objectQualifier}}PortalAlias WHERE HTTPAlias='{alias}'"; + var id = DatabaseHelper.ExecuteScalar(query); + _portalId = id; + } + + return _portalId.Value; + } + } + } +} diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs index a9df6b79f7e..f1e70760743 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs @@ -2,25 +2,26 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DNN.Integration.Test.Framework.Helpers -{ - using System.IO; - using System.Reflection; +namespace DNN.Integration.Test.Framework.Helpers +{ + using System; + using System.IO; + using System.Reflection; - public static class FileHelper - { - public static string GetAbsoluteDir(string relativePathIn) - { - if (!relativePathIn.StartsWith("\\")) - { - relativePathIn = "\\" + relativePathIn; - } - - var rootDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - - var pathOut = rootDirectory + relativePathIn; - - return pathOut; - } - } -} + public static class FileHelper + { + public static string GetAbsoluteDir(string relativePathIn) + { + if (!relativePathIn.StartsWith(@"\", StringComparison.Ordinal)) + { + relativePathIn = @"\" + relativePathIn; + } + + var rootDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + + var pathOut = rootDirectory + relativePathIn; + + return pathOut; + } + } +} diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FolderHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FolderHelper.cs index fe51064368f..f20dc72309b 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FolderHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FolderHelper.cs @@ -20,7 +20,7 @@ public static string GetUserFolderPath(int userId) var fullPath = Path.Combine(Path.Combine(rootFolder, subFolder), userId.ToString(CultureInfo.InvariantCulture)); - return string.Format("Users/{0}/", fullPath.Replace("\\", "/")); + return string.Format("Users/{0}/", fullPath.Replace(@"\", "/")); } private static string GetUserFolderPathRoot(int userId) diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs index 11b60bdf002..ad48b51aee1 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs @@ -598,7 +598,7 @@ private static string CombineUrlPath(Uri domain, string path) } var url = domain.AbsoluteUri; - if (!url.EndsWith("/")) + if (!url.EndsWith("/", StringComparison.Ordinal)) { url += "/"; } @@ -608,7 +608,7 @@ private static string CombineUrlPath(Uri domain, string path) path = string.Empty; } - if (path.StartsWith("/")) + if (path.StartsWith("/", StringComparison.Ordinal)) { return url + path.Substring(1); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs index 564696c5218..6441725330e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Social using System; using System.Collections.Generic; using System.Data; + using System.Globalization; using DotNetNuke.Abstractions.Application; using DotNetNuke.Abstractions.Logging; @@ -368,7 +369,7 @@ public void RelationshipController_DeleteRelationship_Calls_DataCache_RemoveCach // Arrange var portalId = 1; var relationshipController = this.CreateRelationshipController(); - var cacheKey = CachingProvider.GetCacheKey(string.Format(DataCache.RelationshipByPortalIDCacheKey, portalId)); + var cacheKey = CachingProvider.GetCacheKey(string.Format(CultureInfo.InvariantCulture, DataCache.RelationshipByPortalIDCacheKey, portalId)); var relationship = new Relationship() { RelationshipId = Constants.SOCIAL_FollowerRelationshipID, diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/EscapedStringTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/EscapedStringTest.cs index c0f5d00eb9b..548bd33e167 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/EscapedStringTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/EscapedStringTest.cs @@ -18,115 +18,147 @@ public class EscapedStringTest [Test] public void SimpleCase() { - DoTest(new[] { "first", "second" }, "first,second"); + DoTest( + new[] { "first", "second", }, + "first,second"); } [Test] public void CombinesWithSpecifiedSeparator() { - string result = EscapedString.Combine(new[] { "first", "second" }, ';'); - - Assert.That(result, Is.EqualTo("first;second")); + Assert.That( + EscapedString.Combine(new[] { "first", "second", }, ';'), + Is.EqualTo("first;second")); } [Test] public void SeparatesWithSpecifiedSeparator() { - IEnumerable result = EscapedString.Seperate("first]second", ']'); - - Assert.That(result, Is.EqualTo(new[] { "first", "second" }).AsCollection); + Assert.That( + EscapedString.Seperate("first]second", ']'), + Is.EqualTo(["first", "second"]).AsCollection); } [Test] public void EmbeddedSeparator() { - DoTest(new[] { "fi,rst", "second" }, @"fi\,rst,second"); + DoTest( + new[] { "fi,rst", "second" }, + @"fi\,rst,second"); } [Test] public void DoubleSeparator() { - DoTest(new[] { "fi,,rst", "second" }, @"fi\,\,rst,second"); + DoTest( + new[] { "fi,,rst", "second" }, + @"fi\,\,rst,second"); } [Test] public void MultipleSeparators() { - DoTest(new[] { "fi,rst", ",second," }, @"fi\,rst,\,second\,"); + DoTest( + new[] { "fi,rst", ",second," }, + @"fi\,rst,\,second\,"); } [Test] public void EscapeCharacter() { - DoTest(new[] { @"fi\rst", "second" }, @"fi\\rst,second"); + DoTest( + new[] { @"fi\rst", "second" }, + @"fi\\rst,second"); } [Test] public void EmbeddedEscapeSequence() { - DoTest(new[] { @"fi\,rst", "second" }, @"fi\\\,rst,second"); + DoTest( + new[] { @"fi\,rst", "second" }, + @"fi\\\,rst,second"); } [Test] public void CrazyContrivedStuff() { - DoTest(new[] { @"\\\,,fi\,rst,,\,\\", "second" }, @"\\\\\\\,\,fi\\\,rst\,\,\\\,\\\\,second"); + DoTest( + new[] { @"\\\,,fi\,rst,,\,\\", "second" }, + @"\\\\\\\,\,fi\\\,rst\,\,\\\,\\\\,second"); } [Test] public void EmptyElement() { - DoTest(new[] { "first", string.Empty, "third" }, "first,,third"); + DoTest( + new[] { "first", string.Empty, "third", }, + "first,,third"); } [Test] public void MultipleEmptyElements() { - DoTest(new[] { string.Empty, string.Empty, string.Empty }, ",,"); + DoTest( + new[] { string.Empty, string.Empty, string.Empty, }, + ",,"); } [Test] public void EmptyEnumerable() { - DoTest(new object[] { }, string.Empty); + DoTest( + Array.Empty(), + string.Empty); } [Test] public void SingleElement() { - DoTest(new[] { "only item here" }, "only item here"); + DoTest( + new[] { "only item here", }, + "only item here"); } [Test] public void AllEscapeChars() { - DoTest(new[] { @"\", @"\\", @"\\\" }, @"\\,\\\\,\\\\\\"); + DoTest( + new[] { @"\", @"\\", @"\\\" }, + @"\\,\\\\,\\\\\\"); } [Test] public void AllSeparatorChars() { - DoTest(new[] { ",", ",,", ",,," }, @"\,,\,\,,\,\,\,"); + DoTest( + new[] { ",", ",,", ",,," }, + @"\,,\,\,,\,\,\,"); } [Test] public void AllEscapedSeparators() { - DoTest(new[] { @"\,", @"\,\,", @"\,\,\," }, @"\\\,,\\\,\\\,,\\\,\\\,\\\,"); + DoTest( + new[] { @"\,", @"\,\,", @"\,\,\," }, + @"\\\,,\\\,\\\,,\\\,\\\,\\\,"); } [Test] public void TrimWhitespaces() { SeparateTest( - ["item1", "ite\nm2", "item3", "item4", "item5", "item6", "item7"], "item1,ite\nm2,\nitem3, item4,item5\t,\r\nitem6,\vitem7", true); + ["item1", "ite\nm2", "item3", "item4", "item5", "item6", "item7"], + "item1,ite\nm2,\nitem3, item4,item5\t,\r\nitem6,\vitem7", + true); } [Test] public void KeepWhitespaces() { SeparateTest( - ["item1", "ite\nm2", "\nitem3", " item4", "item5\t", "\r\nitem6", "\vitem7"], "item1,ite\nm2,\nitem3, item4,item5\t,\r\nitem6,\vitem7", false); + ["item1", "ite\nm2", "\nitem3", " item4", "item5\t", "\r\nitem6", "\vitem7"], + "item1,ite\nm2,\nitem3, item4,item5\t,\r\nitem6,\vitem7", + false); } private static void DoTest(IEnumerable enumerable, string s) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs index 721c4ebab89..4471900e7c1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs @@ -49,7 +49,7 @@ public void TearDown() [TestCase("//")] [TestCase("///")] [TestCase(@"\")] - [TestCase(@"\\")] + [TestCase("\\")] [TestCase(@"\\\")] [TestCase("/Test/../")] [TestCase("/Test/mmm/../../")] @@ -125,7 +125,7 @@ public void DeleteFile_Should_Delete_File() FileSystemUtils.DeleteFile(testPath); // Assert - Assert.That(testPath.Replace("/", "\\"), Does.Not.Exist); + Assert.That(testPath.Replace("/", @"\"), Does.Not.Exist); } [TestCase(null)] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs index 37db682ea0a..b53215d38f4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs @@ -933,7 +933,7 @@ public void GetFileSystemFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree var directories = new List { @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; this.directory.Setup(d => d.GetDirectories(It.IsAny())) - .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); + .Returns(path => directories.FindAll(sub => sub.StartsWith(path + @"\") && sub.LastIndexOf(@"\", StringComparison.Ordinal) == path.Length).ToArray()); var result = this.mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); @@ -958,7 +958,7 @@ public void GetFileSystemFoldersRecursive_Sets_ExistsInFileSystem_For_All_Items( var directories = new List { @"C:\folder", @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; this.directory.Setup(d => d.GetDirectories(It.IsAny())) - .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); + .Returns(path => directories.FindAll(sub => sub.StartsWith(path + @"\") && sub.LastIndexOf(@"\", StringComparison.Ordinal) == path.Length).ToArray()); var result = this.mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); @@ -1037,7 +1037,7 @@ public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() .Returns(parent => subfolders.FindAll(sub => sub.FolderPath.StartsWith(parent.FolderPath) && sub.FolderPath.Length > parent.FolderPath.Length && - sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); + sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/", StringComparison.Ordinal) == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/", StringComparison.Ordinal))); var result = this.mockFolderManager.Object.GetDatabaseFoldersRecursive(this.folderInfo.Object); @@ -1062,7 +1062,7 @@ public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() .Returns(parent => subfolders.FindAll(sub => sub.FolderPath.StartsWith(parent.FolderPath) && sub.FolderPath.Length > parent.FolderPath.Length && - sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); + sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/", StringComparison.Ordinal) == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/", StringComparison.Ordinal))); var result = this.mockFolderManager.Object.GetDatabaseFoldersRecursive(this.folderInfo.Object); @@ -1114,7 +1114,7 @@ public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() // .Returns((parent, fm) => subfolders.FindAll(sub => // sub.StartsWith(parent) && // sub.Length > parent.Length && - // sub.Substring(parent.Length).IndexOf("/") == sub.Substring(parent.Length).LastIndexOf("/"))); + // sub.Substring(parent.Length).IndexOf("/", StringComparison.Ordinal) == sub.Substring(parent.Length).LastIndexOf("/", StringComparison.Ordinal))); // var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, "folder/"); @@ -1132,7 +1132,7 @@ public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() // .Returns((parent, fm) => subfolders.FindAll(sub => // sub.StartsWith(parent) && // sub.Length > parent.Length && - // sub.Substring(parent.Length).IndexOf("/") == sub.Substring(parent.Length).LastIndexOf("/"))); + // sub.Substring(parent.Length).IndexOf("/", StringComparison.Ordinal) == sub.Substring(parent.Length).LastIndexOf("/", StringComparison.Ordinal))); // var result = _mockFolderManager.Object.GetFolderMappingFoldersRecursive(folderMapping, "folder/"); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs index 848d1da979f..7888f8d8bd3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs @@ -2,20 +2,20 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Tests.Data.Models -{ - using DotNetNuke.ComponentModel.DataAnnotations; - using DotNetNuke.Tests.Utilities; +namespace DotNetNuke.Tests.Data.Models +{ + using DotNetNuke.ComponentModel.DataAnnotations; + using DotNetNuke.Tests.Utilities; - [PrimaryKey(Constants.TABLENAME_Person_Key)] - [TableName(Constants.TABLENAME_Person)] - public class Person - { - public int? Age { get; set; } - - public int ID { get; set; } - - [ColumnName(Constants.COLUMNNAME_PersonName)] - public string Name { get; set; } - } -} + [PrimaryKey(Constants.TABLENAME_Person_Key)] + [TableName(Constants.TABLENAME_Person)] + public class Person + { + public int? Age { get; set; } + + public int ID { get; set; } + + [ColumnName(Constants.COLUMNNAME_PersonName)] + public string Name { get; set; } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs index 0e7c25618da..59462aac872 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs @@ -400,7 +400,7 @@ private void ExecuteTestForTab(string test, TabInfo tab, FriendlyUrlSettings set .Replace("{vanityUrl}", vanityUrl) .Replace("{defaultPage}", _defaultPage); - if (!string.IsNullOrEmpty(parameters) && !parameters.StartsWith("&")) + if (!string.IsNullOrEmpty(parameters) && !parameters.StartsWith("&", StringComparison.Ordinal)) { parameters = "&" + parameters; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs index 9daf03a16fd..6898768a836 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs @@ -389,7 +389,7 @@ private static string RightAfter(string original, string search) private static string ExtractQueryStringPart(Uri url) { var query = url.Query; - return query.StartsWith("?") ? query.Substring(1) : query; + return query.StartsWith("?", StringComparison.Ordinal) ? query.Substring(1) : query; } private void InitializeSession() diff --git a/DNN Platform/Website/Default.aspx.cs b/DNN Platform/Website/Default.aspx.cs index cbaa9f4c37a..ca921aba42c 100644 --- a/DNN Platform/Website/Default.aspx.cs +++ b/DNN Platform/Website/Default.aspx.cs @@ -841,7 +841,7 @@ private IFileInfo GetPageStylesheetInfoCallBack(CacheItemArgs itemArgs) private string GetCssVariablesStylesheet() { - var cacheKey = string.Format(DataCache.PortalStylesCacheKey, this.PortalSettings.PortalId); + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PortalStylesCacheKey, this.PortalSettings.PortalId); var cacheArgs = new CacheItemArgs( cacheKey, DataCache.PortalCacheTimeOut, diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs index 63f78031a1e..760d90fae25 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs @@ -649,7 +649,7 @@ protected void UserAuthenticated(object sender, UserAuthenticatedEventArgs e) case UserLoginStatus.LOGIN_USERLOCKEDOUT: if (this.hostSettings.AutoAccountUnlockDuration > TimeSpan.Zero) { - this.AddLocalizedModuleMessage(string.Format(Localization.GetString("UserLockedOut", this.LocalResourceFile), this.hostSettings.AutoAccountUnlockDuration.TotalMinutes), ModuleMessage.ModuleMessageType.RedError, true); + this.AddLocalizedModuleMessage(string.Format(CultureInfo.CurrentCulture, Localization.GetString("UserLockedOut", this.LocalResourceFile), this.hostSettings.AutoAccountUnlockDuration.TotalMinutes), ModuleMessage.ModuleMessageType.RedError, true); } else { @@ -1349,13 +1349,13 @@ private void ValidateUser(UserInfo objUser, bool ignoreExpiring) this.Response.Redirect(redirectUrl, true); break; case UserValidStatus.PASSWORDEXPIRED: - strMessage = string.Format(Localization.GetString("PasswordExpired", this.LocalResourceFile), expiryDate.ToLongDateString()); + strMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString("PasswordExpired", this.LocalResourceFile), expiryDate.ToLongDateString()); this.AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); this.PageNo = 2; this.pnlProceed.Visible = false; break; case UserValidStatus.PASSWORDEXPIRING: - strMessage = string.Format(Localization.GetString("PasswordExpiring", this.LocalResourceFile), expiryDate.ToLongDateString()); + strMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString("PasswordExpiring", this.LocalResourceFile), expiryDate.ToLongDateString()); this.AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); this.PageNo = 2; this.pnlProceed.Visible = true; diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs index b853305a651..422e3bb26b4 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Modules.Admin.Users using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Web; @@ -328,14 +329,14 @@ protected void cmdUpdate_Click(object sender, EventArgs e) // make sure username matches possibly changed email address if (this.PortalSettings.Registration.UseEmailAsUserName) { - if (this.UserInfo.Username.ToLower() != this.UserInfo.Email.ToLower()) + if (!string.Equals(this.UserInfo.Username, this.UserInfo.Email, StringComparison.OrdinalIgnoreCase)) { UserController.ChangeUsername(this.UserInfo.UserID, this.UserInfo.Email); // after username changed, should redirect to login page to let user authenticate again. var loginUrl = Globals.LoginURL(HttpUtility.UrlEncode(this.Request.RawUrl), false); - var spliter = loginUrl.Contains("?") ? "&" : "?"; - loginUrl = $"{loginUrl}{spliter}username={this.UserInfo.Email}&usernameChanged=true"; + var separator = loginUrl.Contains("?") ? "&" : "?"; + loginUrl = $"{loginUrl}{separator}username={this.UserInfo.Email}&usernameChanged=true"; this.Response.Redirect(loginUrl, true); } } @@ -615,11 +616,11 @@ private void SubscriptionUpdated(object sender, MemberServices.SubscriptionUpdat string message; if (e.Cancel) { - message = string.Format(Localization.GetString("UserUnSubscribed", this.LocalResourceFile), e.RoleName); + message = string.Format(CultureInfo.CurrentCulture, Localization.GetString("UserUnSubscribed", this.LocalResourceFile), e.RoleName); } else { - message = string.Format(Localization.GetString("UserSubscribed", this.LocalResourceFile), e.RoleName); + message = string.Format(CultureInfo.CurrentCulture, Localization.GetString("UserSubscribed", this.LocalResourceFile), e.RoleName); } this.AddLocalizedModuleMessage(message, ModuleMessage.ModuleMessageType.GreenSuccess, true); diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs index 1a4f5e72374..1c506613f15 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs @@ -6,6 +6,7 @@ namespace DotNetNuke.Modules.Admin.Users { using System; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web; using DotNetNuke.Abstractions; @@ -409,7 +410,7 @@ private void BindData() } else { - this.lblTitle.Text = string.Format(Localization.GetString("UserTitle", this.LocalResourceFile), this.User.Username, this.User.UserID); + this.lblTitle.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("UserTitle", this.LocalResourceFile), this.User.Username, this.User.UserID); } } } @@ -824,11 +825,11 @@ private void SubscriptionUpdated(object sender, MemberServices.SubscriptionUpdat string message = Null.NullString; if (e.Cancel) { - message = string.Format(Localization.GetString("UserUnSubscribed", this.LocalResourceFile), e.RoleName); + message = string.Format(CultureInfo.CurrentCulture, Localization.GetString("UserUnSubscribed", this.LocalResourceFile), e.RoleName); } else { - message = string.Format(Localization.GetString("UserSubscribed", this.LocalResourceFile), e.RoleName); + message = string.Format(CultureInfo.CurrentCulture, Localization.GetString("UserSubscribed", this.LocalResourceFile), e.RoleName); } this.AddLocalizedModuleMessage(message, ModuleMessage.ModuleMessageType.GreenSuccess, true); diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs index ae6686b6e58..a74e2668a81 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs @@ -8,6 +8,7 @@ namespace DotNetNuke.Modules.Admin.Security using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Web.UI.WebControls; using DotNetNuke.Common.Utilities; @@ -102,7 +103,7 @@ protected string FormatPrice(float price, int period, string frequency) formatPrice = this.FormatPrice(price); break; default: - formatPrice = string.Format(Localization.GetString("Fee", this.LocalResourceFile), this.FormatPrice(price), period, Localization.GetString("Frequency_" + frequency, this.LocalResourceFile)); + formatPrice = string.Format(CultureInfo.CurrentCulture, Localization.GetString("Fee", this.LocalResourceFile), this.FormatPrice(price), period, Localization.GetString("Frequency_" + frequency, this.LocalResourceFile)); break; } } @@ -158,7 +159,7 @@ protected string FormatURL() try { string serverPath = this.Request.ApplicationPath; - if (!serverPath.EndsWith("/")) + if (!serverPath.EndsWith("/", StringComparison.Ordinal)) { serverPath += "/"; } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs index 7ec771c6d33..a6757024da6 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs @@ -7,6 +7,7 @@ namespace DotNetNuke.Modules.Admin.Security using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Globalization; using System.Linq; using System.Threading; using System.Web.UI; @@ -431,7 +432,7 @@ private void BindData() // cboRoles.Items.Add(new ListItem(Role.RoleName, Role.RoleID.ToString())); this.cboRoles.AddItem(this.Role.RoleName, this.Role.RoleID.ToString()); this.cboRoles.Items[0].Selected = true; - this.lblTitle.Text = string.Format(Localization.GetString("RoleTitle.Text", this.LocalResourceFile), this.Role.RoleName, this.Role.RoleID); + this.lblTitle.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("RoleTitle.Text", this.LocalResourceFile), this.Role.RoleName, this.Role.RoleID); } this.cboRoles.Visible = false; @@ -479,7 +480,7 @@ private void BindData() if (this.User != null) { this.txtUsers.Text = this.User.UserID.ToString(); - this.lblTitle.Text = string.Format(Localization.GetString("UserTitle.Text", this.LocalResourceFile), this.User.Username, this.User.UserID); + this.lblTitle.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("UserTitle.Text", this.LocalResourceFile), this.User.Username, this.User.UserID); } this.txtUsers.Visible = false; @@ -699,11 +700,11 @@ private void GrdUserRoles_ItemCreated(object sender, DataGridItemEventArgs e) { if (this.roleId == Null.NullInteger) { - ClientAPI.AddButtonConfirm(cmdDeleteUserRole, string.Format(Localization.GetString("DeleteRoleFromUser.Text", this.LocalResourceFile), role.FullName, role.RoleName)); + ClientAPI.AddButtonConfirm(cmdDeleteUserRole, string.Format(CultureInfo.CurrentCulture, Localization.GetString("DeleteRoleFromUser.Text", this.LocalResourceFile), role.FullName, role.RoleName)); } else { - ClientAPI.AddButtonConfirm(cmdDeleteUserRole, string.Format(Localization.GetString("DeleteUsersFromRole.Text", this.LocalResourceFile), role.FullName, role.RoleName)); + ClientAPI.AddButtonConfirm(cmdDeleteUserRole, string.Format(CultureInfo.CurrentCulture, Localization.GetString("DeleteUsersFromRole.Text", this.LocalResourceFile), role.FullName, role.RoleName)); } cmdDeleteUserRole.Attributes.Add("roleId", role.RoleID.ToString()); diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs index 386081c7139..2957d102ebb 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Modules.Admin.Users { using System; using System.Collections; + using System.Globalization; using System.Linq; using System.Web.UI; @@ -221,7 +222,7 @@ public override void DataBind() ArrayList portals = PortalController.GetPortalsByUser(this.dataProvider, this.User.UserID); if (portals.Count > 1) { - this.numSites.Text = string.Format(Localization.GetString("UpdateUserName", this.LocalResourceFile), portals.Count.ToString()); + this.numSites.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("UpdateUserName", this.LocalResourceFile), portals.Count.ToString()); this.cboSites.Visible = true; this.cboSites.DataSource = portals; this.cboSites.DataTextField = "PortalName"; @@ -569,7 +570,7 @@ private void CmdUpdate_Click(object sender, EventArgs e) UserController.UpdateUser(this.UserPortalID, this.User); - if (this.PortalSettings.Registration.UseEmailAsUserName && (this.User.Username.ToLower() != this.User.Email.ToLower())) + if (this.PortalSettings.Registration.UseEmailAsUserName && (!string.Equals(this.User.Username, this.User.Email, StringComparison.OrdinalIgnoreCase))) { UserController.ChangeUsername(this.User.UserID, this.User.Email); } diff --git a/DNN Platform/Website/Install/InstallWizard.aspx.cs b/DNN Platform/Website/Install/InstallWizard.aspx.cs index 27d3a198e23..0f62e72724c 100644 --- a/DNN Platform/Website/Install/InstallWizard.aspx.cs +++ b/DNN Platform/Website/Install/InstallWizard.aspx.cs @@ -116,31 +116,13 @@ public InstallWizard(IPortalController portalController, IApplicationStatusInfo } /// Gets the current application version. - protected Version ApplicationVersion - { - get - { - return DotNetNukeContext.Current.Application.Version; - } - } + protected Version ApplicationVersion => DotNetNukeContext.Current.Application.Version; /// Gets the database version. - protected Version DatabaseVersion - { - get - { - return this.dataBaseVersion ?? (this.dataBaseVersion = DataProvider.Instance().GetVersion()); - } - } + protected Version DatabaseVersion => this.dataBaseVersion ??= DataProvider.Instance().GetVersion(); /// Gets the base version from the install template. - protected Version BaseVersion - { - get - { - return Upgrade.GetInstallVersion(this.InstallTemplate); - } - } + protected Version BaseVersion => Upgrade.GetInstallVersion(this.InstallTemplate); /// Gets the install template. protected XmlDocument InstallTemplate @@ -470,7 +452,7 @@ public string RaiseClientAPICallbackEvent(string eventArgument) /// A string representing the result of the action. public string ProcessAction(string someAction) { - // First check that we are not being targetted by an AJAX HttpPost, so get the current DB version + // First check that we are not being targeted by an AJAX HttpPost, so get the current DB version string strProviderPath = this.dataProvider.GetProviderPath(); string nextVersion = this.GetNextScriptVersion(strProviderPath, this.DatabaseVersion); if (someAction != nextVersion) @@ -852,7 +834,7 @@ private static void CurrentStepActivity(string status) private static void GetInstallerLocales(IApplicationStatusInfo appStatus) { - var filePath = appStatus.ApplicationMapPath + LocalesFile.Replace("/", "\\"); + var filePath = appStatus.ApplicationMapPath + LocalesFile.Replace("/", @"\"); if (File.Exists(filePath)) { @@ -915,14 +897,14 @@ private static string CheckDatabaseConnection(ConnectionConfig connectionConfig) var details = Localization.GetString("IsAbleToPerformDatabaseActionsCheck", localResourceFile); if (!InstallController.Instance.IsAbleToPerformDatabaseActions(connectionString)) { - connectionResult = "ERROR: " + string.Format(Localization.GetString("IsAbleToPerformDatabaseActions", localResourceFile), details); + connectionResult = "ERROR: " + string.Format(CultureInfo.CurrentCulture, Localization.GetString("IsAbleToPerformDatabaseActions", localResourceFile), details); } // database actions check-running sql 2008 or higher details = Localization.GetString("IsValidSqlServerVersionCheck", localResourceFile); if (!InstallController.Instance.IsValidSqlServerVersion(connectionString)) { - connectionResult = "ERROR: " + string.Format(Localization.GetString("IsValidSqlServerVersion", localResourceFile), details); + connectionResult = "ERROR: " + string.Format(CultureInfo.CurrentCulture, Localization.GetString("IsValidSqlServerVersion", localResourceFile), details); } return connectionResult; diff --git a/DNN Platform/Website/Install/UpgradeWizard.aspx.cs b/DNN Platform/Website/Install/UpgradeWizard.aspx.cs index 9a58c23417d..6954d9c6c46 100644 --- a/DNN Platform/Website/Install/UpgradeWizard.aspx.cs +++ b/DNN Platform/Website/Install/UpgradeWizard.aspx.cs @@ -596,7 +596,7 @@ private static void SetHostSetting(string key, string value, bool isSecure = fal private static void GetInstallerLocales(IApplicationStatusInfo applicationStatus) { - var filePath = applicationStatus.ApplicationMapPath + LocalesFile.Replace("/", "\\"); + var filePath = applicationStatus.ApplicationMapPath + LocalesFile.Replace("/", @"\"); if (File.Exists(filePath)) { diff --git a/DNN Platform/Website/Portals/_default/subhost.aspx b/DNN Platform/Website/Portals/_default/subhost.aspx index 7a481b77cd0..bd1bcca2ce2 100644 --- a/DNN Platform/Website/Portals/_default/subhost.aspx +++ b/DNN Platform/Website/Portals/_default/subhost.aspx @@ -25,12 +25,12 @@ for (urlIndex = 2; urlIndex <= url.GetUpperBound(0); urlIndex++) { bool willExit = false; - switch (url[urlIndex].ToLower()) + switch (url[urlIndex].ToUpperInvariant()) { - case "admin": - case "desktopmodules": - case "mobilemodules": - case "premiummodules": + case "ADMIN": + case "DESKTOPMODULES": + case "MOBILEMODULES": + case "PREMIUMMODULES": willExit = true; break; default: diff --git a/DNN Platform/Website/admin/Containers/PrintModule.ascx.cs b/DNN Platform/Website/admin/Containers/PrintModule.ascx.cs index ba64f691f53..3acdc0dccda 100644 --- a/DNN Platform/Website/admin/Containers/PrintModule.ascx.cs +++ b/DNN Platform/Website/admin/Containers/PrintModule.ascx.cs @@ -61,7 +61,7 @@ private void DisplayAction(ModuleAction action) var moduleActionIcon = new ImageButton(); if (!string.IsNullOrEmpty(this.PrintIcon)) { - moduleActionIcon.ImageUrl = this.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1) + this.PrintIcon; + moduleActionIcon.ImageUrl = this.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleContext.Configuration.ContainerPath.LastIndexOf("/", StringComparison.Ordinal) + 1) + this.PrintIcon; } else { diff --git a/DNN Platform/Website/admin/Containers/Visibility.ascx.cs b/DNN Platform/Website/admin/Containers/Visibility.ascx.cs index 27ef23a3323..a3f92ef6c18 100644 --- a/DNN Platform/Website/admin/Containers/Visibility.ascx.cs +++ b/DNN Platform/Website/admin/Containers/Visibility.ascx.cs @@ -134,7 +134,7 @@ private string ModulePath { get { - return this.ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1); + return this.ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/", StringComparison.Ordinal) + 1); } } diff --git a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx index c10fac12b62..067800f7330 100644 --- a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx +++ b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx @@ -27,8 +27,8 @@ /*globals jQuery, window */ (function ($) { var moduleId = <% = ModuleContext.ModuleId %>; - var displayQuickSettings = <% = DisplayQuickSettings.ToString().ToLower() %>; - var supportsQuickSettings = <% = SupportsQuickSettings.ToString().ToLower() %>; + var displayQuickSettings = <% = DisplayQuickSettings.ToString().ToLowerInvariant() %>; + var supportsQuickSettings = <% = SupportsQuickSettings.ToString().ToLowerInvariant() %>; function setUpActions() { var tabId = <% = ModuleContext.TabId %>; @@ -55,10 +55,10 @@ confirmTitle: '<%= Localization.GetSafeJSString("Confirm.Text", Localization.SharedResourceFile) %>', sharedText: '<%= Localization.GetSafeJSString("ModuleShared.Text", Localization.SharedResourceFile) %>', rootFolder: '<%= Page.ResolveClientUrl("~/") %>', - supportsMove: <% = SupportsMove.ToString().ToLower() %>, + supportsMove: <% = SupportsMove.ToString().ToLowerInvariant() %>, supportsQuickSettings: supportsQuickSettings, displayQuickSettings: displayQuickSettings, - isShared : <% = IsShared.ToString().ToLower() %>, + isShared : <% = IsShared.ToString().ToLowerInvariant() %>, moduleTitle: '<% = Localization.GetSafeJSString(ModuleTitle) %>' } ); diff --git a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs index cc928e8e3fc..a1daf0dbe94 100644 --- a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs +++ b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs @@ -161,13 +161,13 @@ protected override void OnLoad(EventArgs e) (action.Secure != SecurityAccessLevel.Anonymous && action.Secure != SecurityAccessLevel.View)) { if (!action.Icon.Contains("://") - && !action.Icon.StartsWith("/") - && !action.Icon.StartsWith("~/")) + && !action.Icon.StartsWith("/", StringComparison.Ordinal) + && !action.Icon.StartsWith("~/", StringComparison.Ordinal)) { action.Icon = "~/images/" + action.Icon; } - if (action.Icon.StartsWith("~/")) + if (action.Icon.StartsWith("~/", StringComparison.Ordinal)) { action.Icon = Globals.ResolveUrl(action.Icon); } diff --git a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.designer.cs b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.designer.cs index 685d38ddc59..574b3683471 100644 --- a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.designer.cs +++ b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.designer.cs @@ -1,31 +1,35 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace DotNetNuke.Admin.Containers { - - - public partial class ModuleActions { - /// actionButton control. - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.LinkButton actionButton; - /// quickSettings control. - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Panel quickSettings; - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DotNetNuke.Admin.Containers +{ + + + public partial class ModuleActions + { + + /// + /// actionButton control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.LinkButton actionButton; + + /// + /// quickSettings control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Panel quickSettings; + } +} diff --git a/DNN Platform/Website/admin/Modules/Export.ascx.cs b/DNN Platform/Website/admin/Modules/Export.ascx.cs index ea18908a414..1f15d1a26fa 100644 --- a/DNN Platform/Website/admin/Modules/Export.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Export.ascx.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Modules.Admin.Modules { using System; + using System.Globalization; using System.IO; using System.Text; using System.Web.UI.WebControls; @@ -204,14 +205,12 @@ private string ExportModule(int moduleID, string fileName, IFolderInfo folder) if (PortalController.Instance.HasSpaceAvailable(this.PortalId, content.Length)) { // add file to Files table - using (var fileContent = new MemoryStream(Encoding.UTF8.GetBytes(content))) - { - Services.FileSystem.FileManager.Instance.AddFile(folder, fileName, fileContent, true, true, "application/octet-stream"); - } + using var fileContent = new MemoryStream(Encoding.UTF8.GetBytes(content)); + Services.FileSystem.FileManager.Instance.AddFile(folder, fileName, fileContent, true, true, "application/octet-stream"); } else { - strMessage += "
    " + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); + strMessage += "
    " + string.Format(CultureInfo.CurrentCulture, Localization.GetString("DiskSpaceExceeded"), fileName); } } else diff --git a/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs b/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs index da89ced0c74..d67b119118e 100644 --- a/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs @@ -129,7 +129,7 @@ protected string GetInstalledOnLink(object dataItem) } else { - returnValue.AppendFormat("{0}", t.LocalizedTabName); + returnValue.Append(t.LocalizedTabName); } index = index + 1; @@ -142,8 +142,7 @@ protected string GetInstalledOnLink(object dataItem) protected string GetInstalledOnSite(object dataItem) { string returnValue = string.Empty; - var tab = dataItem as TabInfo; - if (tab != null) + if (dataItem is TabInfo tab) { var portal = PortalController.Instance.GetPortal(tab.PortalID); if (portal != null) diff --git a/DNN Platform/Website/admin/Modules/viewsource.ascx.cs b/DNN Platform/Website/admin/Modules/viewsource.ascx.cs index 1275ae1f886..a9f693fea04 100644 --- a/DNN Platform/Website/admin/Modules/viewsource.ascx.cs +++ b/DNN Platform/Website/admin/Modules/viewsource.ascx.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Modules.Admin.Modules { using System; + using System.Globalization; using System.IO; using DotNetNuke.Abstractions; @@ -160,7 +161,7 @@ private void DisplayFile() if (displaySource) { srcFile = this.GetSourceFileName(srcVirtualPath); - this.lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", this.LocalResourceFile), srcFile); + this.lblSourceFile.Text = string.Format(CultureInfo.CurrentCulture, Localization.GetString("SourceFile", this.LocalResourceFile), srcFile); var objStreamReader = File.OpenText(srcFile); this.txtSource.Text = objStreamReader.ReadToEnd(); diff --git a/DNN Platform/Website/admin/Security/SendPassword.ascx.cs b/DNN Platform/Website/admin/Security/SendPassword.ascx.cs index bf9be1cc5a9..6a31b38924d 100644 --- a/DNN Platform/Website/admin/Security/SendPassword.ascx.cs +++ b/DNN Platform/Website/admin/Security/SendPassword.ascx.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Modules.Admin.Security { using System; using System.Collections; + using System.Globalization; using System.Net; using System.Web; @@ -192,9 +193,9 @@ protected override void OnLoad(EventArgs e) /// The event arguments. protected void OnSendPasswordClick(object sender, EventArgs e) { - // pretty much always display the same message to avoid hinting on the existence of a user name + // pretty much always display the same message to avoid hinting on the existence of a username var input = string.IsNullOrEmpty(this.txtUsername.Text) ? this.txtEmail.Text : this.txtUsername.Text; - var message = string.Format(Localization.GetString("PasswordSent", this.LocalResourceFile), WebUtility.HtmlEncode(input)); + var message = string.Format(CultureInfo.CurrentCulture, Localization.GetString("PasswordSent", this.LocalResourceFile), WebUtility.HtmlEncode(input)); var moduleMessageType = ModuleMessage.ModuleMessageType.GreenSuccess; var canSend = true; diff --git a/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs b/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs index bb5224d8566..31459e05b0b 100644 --- a/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs +++ b/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs @@ -221,7 +221,7 @@ private void ResolveSeparatorPaths() var url = match.Groups[3].Value; var changed = false; - if (url.StartsWith("/")) + if (url.StartsWith("/", StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(Globals.ApplicationPath)) { @@ -229,7 +229,7 @@ private void ResolveSeparatorPaths() changed = true; } } - else if (url.StartsWith("~/")) + else if (url.StartsWith("~/", StringComparison.Ordinal)) { url = Globals.ResolveUrl(url); changed = true; diff --git a/DNN Platform/Website/admin/Skins/Copyright.ascx.cs b/DNN Platform/Website/admin/Skins/Copyright.ascx.cs index 409a64c92e5..d5e201e5df4 100644 --- a/DNN Platform/Website/admin/Skins/Copyright.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Copyright.ascx.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.Skins.Controls { using System; + using System.Globalization; using DotNetNuke.Services.Localization; @@ -25,11 +26,15 @@ protected override void OnLoad(EventArgs e) if (!string.IsNullOrEmpty(this.PortalSettings.FooterText)) { - this.lblCopyright.Text = this.PortalSettings.FooterText.Replace("[year]", DateTime.Now.ToString("yyyy")); + this.lblCopyright.Text = this.PortalSettings.FooterText.Replace("[year]", DateTime.Now.ToString("yyyy", CultureInfo.CurrentCulture)); } else { - this.lblCopyright.Text = string.Format(Localization.GetString("Copyright", Localization.GetResourceFile(this, MyFileName)), DateTime.Now.Year, this.PortalSettings.PortalName); + this.lblCopyright.Text = string.Format( + CultureInfo.CurrentCulture, + Localization.GetString("Copyright", Localization.GetResourceFile(this, MyFileName)), + DateTime.Now.Year, + this.PortalSettings.PortalName); } } } diff --git a/DNN Platform/Website/admin/Skins/Language.ascx.cs b/DNN Platform/Website/admin/Skins/Language.ascx.cs index 3956a7dc2a1..afc3f149165 100644 --- a/DNN Platform/Website/admin/Skins/Language.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Language.ascx.cs @@ -478,7 +478,7 @@ private void SelectCulture_SelectedIndexChanged(object sender, EventArgs e) this.LocalTokenReplace.Language = this.selectCulture.SelectedItem.Value; // DNN-6170 ensure skin value is culture specific in case of static localization - DataCache.RemoveCache(string.Format(DataCache.PortalSettingsCacheKey, this.PortalSettings.PortalId, Null.NullString)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.PortalSettingsCacheKey, this.PortalSettings.PortalId, Null.NullString)); this.Response.Redirect(this.LocalTokenReplace.ReplaceEnvironmentTokens("[URL]")); } } diff --git a/DNN Platform/Website/admin/Skins/Logo.ascx.cs b/DNN Platform/Website/admin/Skins/Logo.ascx.cs index 4e93dfbe663..d1fb7f210c7 100644 --- a/DNN Platform/Website/admin/Skins/Logo.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Logo.ascx.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.UI.Skins.Controls { using System; + using System.Globalization; using System.Linq; using System.Web.UI.WebControls; using System.Xml; @@ -121,7 +122,7 @@ protected override void OnLoad(EventArgs e) private IFileInfo GetLogoFileInfo() { - string cacheKey = string.Format(DataCache.PortalCacheKey, this.PortalSettings.PortalId, this.PortalSettings.CultureCode) + "LogoFile"; + string cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PortalCacheKey, this.PortalSettings.PortalId, this.PortalSettings.CultureCode) + "LogoFile"; return CBO.GetCachedObject( this.hostSettings, @@ -136,7 +137,7 @@ private IFileInfo GetLogoFileInfoCallBack(CacheItemArgs itemArgs) private string GetSvgContent(IFileInfo svgFile) { - var cacheKey = string.Format(DataCache.PortalCacheKey, this.PortalSettings.PortalId, this.PortalSettings.CultureCode) + "LogoSvg"; + var cacheKey = string.Format(CultureInfo.InvariantCulture, DataCache.PortalCacheKey, this.PortalSettings.PortalId, this.PortalSettings.CultureCode) + "LogoSvg"; return CBO.GetCachedObject( this.hostSettings, new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, svgFile), diff --git a/DNN Platform/Website/admin/Skins/User.ascx.cs b/DNN Platform/Website/admin/Skins/User.ascx.cs index 26f8897c11f..27782a46553 100644 --- a/DNN Platform/Website/admin/Skins/User.ascx.cs +++ b/DNN Platform/Website/admin/Skins/User.ascx.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.UI.Skins.Controls { using System; using System.Collections.Generic; + using System.Globalization; using System.Web; using DotNetNuke.Abstractions; @@ -180,8 +181,8 @@ protected override void OnLoad(EventArgs e) var unreadMessages = InternalMessagingController.Instance.CountUnreadMessages(userInfo.UserID, PortalController.GetEffectivePortalId(this.portalController, this.appStatus, this.portalGroupController, userInfo.PortalID)); var unreadAlerts = NotificationsController.Instance.CountNotifications(userInfo.UserID, PortalController.GetEffectivePortalId(this.portalController, this.appStatus, this.portalGroupController, userInfo.PortalID)); - this.messageLink.Text = unreadMessages > 0 ? string.Format(Localization.GetString("Messages", Localization.GetResourceFile(this, MyFileName)), unreadMessages) : Localization.GetString("NoMessages", Localization.GetResourceFile(this, MyFileName)); - this.notificationLink.Text = unreadAlerts > 0 ? string.Format(Localization.GetString("Notifications", Localization.GetResourceFile(this, MyFileName)), unreadAlerts) : Localization.GetString("NoNotifications", Localization.GetResourceFile(this, MyFileName)); + this.messageLink.Text = unreadMessages > 0 ? string.Format(CultureInfo.CurrentCulture, Localization.GetString("Messages", Localization.GetResourceFile(this, MyFileName)), unreadMessages) : Localization.GetString("NoMessages", Localization.GetResourceFile(this, MyFileName)); + this.notificationLink.Text = unreadAlerts > 0 ? string.Format(CultureInfo.CurrentCulture, Localization.GetString("Notifications", Localization.GetResourceFile(this, MyFileName)), unreadAlerts) : Localization.GetString("NoNotifications", Localization.GetResourceFile(this, MyFileName)); this.messageLink.NavigateUrl = this.navigationManager.NavigateURL(this.GetMessageTab(), string.Empty, $"userId={userInfo.UserID}"); this.notificationLink.NavigateUrl = this.navigationManager.NavigateURL(this.GetMessageTab(), string.Empty, $"userId={userInfo.UserID}", "view=notifications", "action=notifications"); @@ -192,7 +193,7 @@ protected override void OnLoad(EventArgs e) if (this.LegacyMode && unreadMessages > 0) { - this.registerLink.Text = this.registerLink.Text + string.Format(Localization.GetString("NewMessages", Localization.GetResourceFile(this, MyFileName)), unreadMessages); + this.registerLink.Text = this.registerLink.Text + string.Format(CultureInfo.CurrentCulture, Localization.GetString("NewMessages", Localization.GetResourceFile(this, MyFileName)), unreadMessages); } } else diff --git a/DNN Platform/Website/admin/Tabs/Export.ascx.cs b/DNN Platform/Website/admin/Tabs/Export.ascx.cs index 142aced09c8..25bfda3751f 100644 --- a/DNN Platform/Website/admin/Tabs/Export.ascx.cs +++ b/DNN Platform/Website/admin/Tabs/Export.ascx.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Modules.Admin.Tabs { using System; + using System.Globalization; using System.IO; using System.Text; using System.Xml; @@ -118,7 +119,7 @@ protected void OnExportClick(object sender, EventArgs e) if (folder != null) { var filename = folder.FolderPath + this.txtFile.Text + ".page.template"; - filename = filename.Replace("/", "\\"); + filename = filename.Replace("/", @"\"); var xmlTemplate = new XmlDocument { XmlResolver = null }; XmlNode nodePortal = xmlTemplate.AppendChild(xmlTemplate.CreateElement("portal")); @@ -136,7 +137,7 @@ protected void OnExportClick(object sender, EventArgs e) XmlNode nodeTabs = nodePortal.AppendChild(xmlTemplate.CreateElement("tabs")); this.SerializeTab(xmlTemplate, nodeTabs); - UI.Skins.Skin.AddModuleMessage(this, string.Empty, string.Format(Localization.GetString("ExportedMessage", this.LocalResourceFile), filename), ModuleMessage.ModuleMessageType.BlueInfo); + UI.Skins.Skin.AddModuleMessage(this, string.Empty, string.Format(CultureInfo.CurrentCulture, Localization.GetString("ExportedMessage", this.LocalResourceFile), filename), ModuleMessage.ModuleMessageType.BlueInfo); // add file to Files table using (var fileContent = new MemoryStream(Encoding.UTF8.GetBytes(xmlTemplate.OuterXml))) diff --git a/DNN Platform/Website/admin/Tabs/Import.ascx.cs b/DNN Platform/Website/admin/Tabs/Import.ascx.cs index ac31f2edb68..62b8788a901 100644 --- a/DNN Platform/Website/admin/Tabs/Import.ascx.cs +++ b/DNN Platform/Website/admin/Tabs/Import.ascx.cs @@ -179,7 +179,7 @@ protected void OnImportClick(object sender, EventArgs e) string invalidType; if (!TabController.IsValidTabName(this.txtTabName.Text, out invalidType)) { - var warningMessage = string.Format(Localization.GetString(invalidType, this.LocalResourceFile), this.txtTabName.Text); + var warningMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString(invalidType, this.LocalResourceFile), this.txtTabName.Text); UI.Skins.Skin.AddModuleMessage(this, warningMessage, ModuleMessage.ModuleMessageType.RedError); return; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs index 97c9d0af7e7..ed5e36ae975 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs @@ -267,7 +267,7 @@ public string EmailLogItems(string subject, string fromEmailAddress, string toEm } else { - returnMsg = string.Format(Localization.GetString("InavlidEmailAddress", Constants.LocalResourcesFile), fromEmailAddress); + returnMsg = string.Format(CultureInfo.CurrentCulture, Localization.GetString("InavlidEmailAddress", Constants.LocalResourcesFile), fromEmailAddress); error = Localization.GetString("EmailFailure", Constants.LocalResourcesFile); } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs index ab01784aa59..09271a8240e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs @@ -6,6 +6,7 @@ namespace Dnn.PersonaBar.Extensions.Components { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -60,7 +61,7 @@ private static string UpdateTelerikEncryptionKey(string keyName) Config.AddAppSetting(xmlConfig, keyName, newKey); // save a copy of the existing web.config - var backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); + var backupFolder = $@"{Globals.glbConfigFolder}Backup_{DateTime.Now.ToString("yyyyMMddHHmm", CultureInfo.InvariantCulture)}\"; strError += Config.Save(xmlConfig, backupFolder + "web_.config") + Environment.NewLine; // save the web.config diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Constants.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Constants.cs index 875b2b85aec..c26c443ac41 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Constants.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Constants.cs @@ -4,6 +4,8 @@ namespace Dnn.PersonaBar.Extensions.Components { + using System.Diagnostics.CodeAnalysis; + public enum PackageTypes { /// A generic package. @@ -16,6 +18,7 @@ public enum PackageTypes AuthenticationSystem = AuthSystem, /// An authentication system. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] Auth_System = AuthSystem, /// A container pack. @@ -34,6 +37,7 @@ public enum PackageTypes JavascriptLibrary = 6, /// A JavaScript library. + [SuppressMessage("Microsoft.Design", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Breaking change")] Javascript_Library = JavascriptLibrary, /// A language pack. diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs index 79a57dfbbd0..1dc68c2124e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs @@ -4,6 +4,7 @@ namespace Dnn.PersonaBar.Extensions.Components { using System; + using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; @@ -75,10 +76,10 @@ private static string CreateControl(CreateModuleDto createModuleDto) { var folder = PathUtils.Instance.RemoveTrailingSlash(GetSourceFolder(createModuleDto)); var className = GetClassName(createModuleDto); - var moduleControlPath = Path.Combine(Globals.ApplicationMapPath, "DesktopModules/" + folder + "/" + createModuleDto.FileName); + var moduleControlPath = Path.Combine(Globals.ApplicationMapPath, $"DesktopModules/{folder}/{createModuleDto.FileName}"); var message = Null.NullString; - var source = string.Format(LoadControlTemplate(), createModuleDto.Language, className); + var source = string.Format(CultureInfo.InvariantCulture, LoadControlTemplate(), createModuleDto.Language, className); // reset attributes if (File.Exists(moduleControlPath)) @@ -170,7 +171,7 @@ private int CreateNewModule(CreateModuleDto createModuleDto, out string newPageU return Null.NullInteger; } - if (!controlSrc.EndsWith(".ascx")) + if (!controlSrc.EndsWith(".ascx", StringComparison.Ordinal)) { controlSrc += ".ascx"; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs index b8b32c56fa9..14073fa389b 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs @@ -5,6 +5,7 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors { using System; + using System.Globalization; using Dnn.PersonaBar.Extensions.Components.Dto; using Dnn.PersonaBar.Extensions.Components.Dto.Editors; @@ -57,13 +58,12 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e try { - string value; var changed = false; var languagePack = LanguagePackController.GetLanguagePackByPackage(packageSettings.PackageId); - if (packageSettings.EditorActions.TryGetValue("languageId", out value) - && !string.IsNullOrEmpty(value) && value != languagePack.LanguageID.ToString()) + if (packageSettings.EditorActions.TryGetValue("languageId", out var value) + && !string.IsNullOrEmpty(value) && value != languagePack.LanguageID.ToString(CultureInfo.InvariantCulture)) { - languagePack.LanguageID = Convert.ToInt32(value); + languagePack.LanguageID = Convert.ToInt32(value, CultureInfo.InvariantCulture); changed = true; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs index f4262cf662e..3d5e7a2bc69 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs @@ -5,6 +5,7 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors { using System; + using System.Globalization; using Dnn.PersonaBar.Extensions.Components.Dto; using Dnn.PersonaBar.Extensions.Components.Dto.Editors; @@ -59,20 +60,19 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e try { - string value; var changed = false; var languagePack = LanguagePackController.GetLanguagePackByPackage(packageSettings.PackageId); - if (packageSettings.EditorActions.TryGetValue("languageId", out value) - && !string.IsNullOrEmpty(value) && value != languagePack.LanguageID.ToString()) + if (packageSettings.EditorActions.TryGetValue("languageId", out var value) + && !string.IsNullOrEmpty(value) && value != languagePack.LanguageID.ToString(CultureInfo.InvariantCulture)) { - languagePack.LanguageID = Convert.ToInt32(value); + languagePack.LanguageID = Convert.ToInt32(value, CultureInfo.InvariantCulture); changed = true; } if (packageSettings.EditorActions.TryGetValue("dependentPackageId", out value) - && !string.IsNullOrEmpty(value) && value != languagePack.DependentPackageID.ToString()) + && !string.IsNullOrEmpty(value) && value != languagePack.DependentPackageID.ToString(CultureInfo.InvariantCulture)) { - languagePack.DependentPackageID = Convert.ToInt32(value); + languagePack.DependentPackageID = Convert.ToInt32(value, CultureInfo.InvariantCulture); changed = true; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs index 5c6d2f79787..63fa549d7fa 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs @@ -6,6 +6,7 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors { using System; using System.Collections.Generic; + using System.Globalization; using System.Linq; using Dnn.PersonaBar.Extensions.Components.Dto; @@ -149,7 +150,7 @@ private static void UpdateModuleProperties(DesktopModuleInfo desktopModule, IDic desktopModule.IsPremium = Convert.ToBoolean(settingValue); break; case "shareable": - desktopModule.Shareable = (ModuleSharing)Convert.ToInt32(settingValue); + desktopModule.Shareable = (ModuleSharing)Convert.ToInt32(settingValue, CultureInfo.InvariantCulture); break; case "assignportal": AssignPortals(desktopModule, JsonConvert.DeserializeObject>(settingValue)); @@ -162,14 +163,14 @@ private static void UpdateModuleProperties(DesktopModuleInfo desktopModule, IDic SaveModuleDefinition(definition); break; case "deletedefinition": - DeleteModuleDefinition(Convert.ToInt32(settingValue)); + DeleteModuleDefinition(Convert.ToInt32(settingValue, CultureInfo.InvariantCulture)); break; case "savemodulecontrol": var moduleControl = JsonConvert.DeserializeObject(settingValue); SaveModuleControl(moduleControl); break; case "deletemodulecontrol": - DeleteModuleControl(Convert.ToInt32(settingValue)); + DeleteModuleControl(Convert.ToInt32(settingValue, CultureInfo.InvariantCulture)); break; case "friendlyname": desktopModule.FriendlyName = settingValue; @@ -306,7 +307,7 @@ private static void UpdatePermissions(DesktopModuleInfo desktopModule, PackageSe } } - DataCache.RemoveCache(string.Format(DataCache.PortalDesktopModuleCacheKey, portalSettings.PortalId)); + DataCache.RemoveCache(string.Format(CultureInfo.InvariantCulture, DataCache.PortalDesktopModuleCacheKey, portalSettings.PortalId)); } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs index e14b1a2e26d..e2851488a30 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs @@ -220,7 +220,7 @@ public string GetFormattedTabLink(int portalId, TabInfo tab) if (index < tab.BreadCrumbs.Count - 1) { - returnValue.AppendFormat("{0}", t.LocalizedTabName); + returnValue.Append(t.LocalizedTabName); } else { @@ -231,7 +231,7 @@ public string GetFormattedTabLink(int portalId, TabInfo tab) .OrderBy(pa => pa.IsPrimary ? 0 : 1) .First(); var url = this.NavigationManager.NavigateURL(t.TabID, new PortalSettings(t.PortalID, alias), string.Empty); - returnValue.AppendFormat("{1}", url, t.LocalizedTabName); + returnValue.AppendFormat(CultureInfo.InvariantCulture, "{1}", url, t.LocalizedTabName); } index = index + 1; diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs index 4492397d944..851e4aada5e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs @@ -6,6 +6,7 @@ namespace Dnn.PersonaBar.Extensions.Components { using System; using System.Data; + using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Xml; @@ -26,6 +27,7 @@ public class InstallController : ServiceLocator + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public ParseResultDto ParsePackage(PortalSettings portalSettings, UserInfo user, string filePath, Stream stream) { var parseResult = new ParseResultDto(); @@ -90,6 +92,7 @@ public ParseResultDto ParsePackage(PortalSettings portalSettings, UserInfo user, } /// + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] public InstallResultDto InstallPackage(PortalSettings portalSettings, UserInfo user, string legacySkin, string filePath, Stream stream, bool isPortalPackage = false) { var installResult = new InstallResultDto(); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs index 4a52e21c57c..12460b0a141 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs @@ -6,6 +6,7 @@ namespace Dnn.PersonaBar.Pages.Components using System; using System.Collections; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; @@ -14,6 +15,7 @@ namespace Dnn.PersonaBar.Pages.Components using Dnn.PersonaBar.Pages.Components.Exceptions; using Dnn.PersonaBar.Pages.Services.Dto; using DotNetNuke.Abstractions.Modules; + using DotNetNuke.Abstractions.Portals; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; @@ -49,7 +51,7 @@ public BulkPagesController(IBusinessControllerProvider businessControllerProvide /// public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var portalSettings = PortalController.Instance.GetCurrentSettings(); var portalId = portalSettings.PortalId; var response = new BulkPageResponse(); var parentId = page.ParentId; @@ -58,10 +60,9 @@ public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) var strValue = page.BulkPages; strValue = strValue.Replace("\r", "\n").Replace("\n\n", "\n").Trim(); - string invalidType; - if (!TabController.IsValidTabName(strValue, out invalidType)) + if (!TabController.IsValidTabName(strValue, out var invalidType)) { - throw new BulkPagesException("bulkPages", string.Format(Localization.GetString(invalidType), strValue)); + throw new BulkPagesException("bulkPages", string.Format(CultureInfo.CurrentCulture, Localization.GetString(invalidType), strValue)); } if (page.StartDate.HasValue && page.EndDate.HasValue && page.StartDate > page.EndDate) @@ -113,7 +114,7 @@ public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) { if (string.IsNullOrWhiteSpace(oTab.TabName)) { - errorMessage = string.Format(Localization.GetString("EmptyTabName"), oTab.TabName); + errorMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString("EmptyTabName"), oTab.TabName); } else { @@ -240,7 +241,7 @@ private static bool IsValidTabPath(TabInfo tab, string newTabPath, out string er var cultureCode = tab.CultureCode; if (string.IsNullOrEmpty(cultureCode)) { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var portalSettings = PortalController.Instance.GetCurrentSettings(); cultureCode = portalSettings.DefaultLanguage; } @@ -249,7 +250,7 @@ private static bool IsValidTabPath(TabInfo tab, string newTabPath, out string er if (tabId != Null.NullInteger && tabId != tab.TabID) { var existingTab = TabController.Instance.GetTab(tabId, tab.PortalID, false); - if (existingTab != null && existingTab.IsDeleted) + if (existingTab is { IsDeleted: true, }) { errorMessage = Localization.GetString("TabRecycled"); } @@ -261,17 +262,17 @@ private static bool IsValidTabPath(TabInfo tab, string newTabPath, out string er valid = false; } - // check whether have conflict between tab path and portal alias. + // check whether there are conflicts between tab path and portal alias. if (TabController.IsDuplicateWithPortalAlias(tab.PortalID, newTabPath)) { - errorMessage = string.Format(Localization.GetString("PathDuplicateWithAlias"), tab.TabName, newTabPath); + errorMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString("PathDuplicateWithAlias"), tab.TabName, newTabPath); valid = false; } return valid; } - private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, TabInfo oTab, int parentId, bool validateOnly, out string errorMessage) + private int CreateTabFromParent(IPortalSettings portalSettings, TabInfo objRoot, TabInfo oTab, int parentId, bool validateOnly, out string errorMessage) { var tab = new TabInfo { @@ -327,10 +328,9 @@ private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, tab.TabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); // Check for invalid - string invalidType; - if (!TabController.IsValidTabName(tab.TabName, out invalidType)) + if (!TabController.IsValidTabName(tab.TabName, out var invalidType)) { - errorMessage = string.Format(Localization.GetString(invalidType), tab.TabName); + errorMessage = string.Format(CultureInfo.CurrentCulture, Localization.GetString(invalidType), tab.TabName); return Null.NullInteger; } @@ -398,8 +398,8 @@ private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, private void ApplyDefaultTabTemplate(TabInfo tab) { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var templateFile = Path.Combine(portalSettings.HomeDirectoryMapPath, "Templates\\" + DefaultPageTemplate); + var portalSettings = PortalController.Instance.GetCurrentSettings(); + var templateFile = Path.Combine(portalSettings.HomeDirectoryMapPath, $@"Templates\{DefaultPageTemplate}"); if (!File.Exists(templateFile)) { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs index 3c96152f5b3..98075b5e053 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs @@ -52,7 +52,7 @@ public static T ConvertToPageItem(TabInfo tab, IEnumerable portalTab CanAddContentToPage = TabPermissionController.CanAddContentToPage(tab), CanNavigateToPage = TabPermissionController.CanNavigateToPage(tab), LastModifiedOnDate = tab.LastModifiedOnDate.ToString("MM/dd/yyyy h:mm:ss tt", CultureInfo.CreateSpecificCulture(tab.CultureCode ?? "en-US")), - FriendlyLastModifiedOnDate = tab.LastModifiedOnDate.ToString("MM/dd/yyyy h:mm:ss tt"), + FriendlyLastModifiedOnDate = tab.LastModifiedOnDate.ToString("MM/dd/yyyy h:mm:ss tt", CultureInfo.CurrentCulture), PublishDate = tab.HasBeenPublished ? WorkflowHelper.GetTabLastPublishedOn(tab).ToString("MM/dd/yyyy h:mm:ss tt", CultureInfo.CreateSpecificCulture(tab.CultureCode ?? "en-US")) : string.Empty, PublishStatus = GetTabPublishStatus(tab), Tags = tab.Terms.Select(t => t.Name).ToArray(), @@ -178,13 +178,12 @@ private static ThemeFileInfo GetThemeFileFromSkinSrc(string skinSrc) private static IFileInfo GetFileRedirection(string tabUrl) { - if (tabUrl == null || !tabUrl.StartsWith("FileId=")) + if (tabUrl == null || !tabUrl.StartsWith("FileId=", StringComparison.OrdinalIgnoreCase)) { return null; } - int fileRedirectionId; - if (int.TryParse(tabUrl.Substring(7), out fileRedirectionId)) + if (int.TryParse(tabUrl.Substring(7), out var fileRedirectionId)) { return FileManager.Instance.GetFile(fileRedirectionId); } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs index 5ee05a45bc0..c9ba2b0c148 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs @@ -2,23 +2,26 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace Dnn.PersonaBar.Pages.Components -{ - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Urls; +namespace Dnn.PersonaBar.Pages.Components +{ + using System.Diagnostics.CodeAnalysis; - public class FriendlyUrlWrapper : IFriendlyUrlWrapper + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Urls; + + public class FriendlyUrlWrapper : IFriendlyUrlWrapper { /// - public string CleanNameForUrl(string urlPath, FriendlyUrlOptions options, out bool modified) - { - return FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); + public string CleanNameForUrl(string urlPath, FriendlyUrlOptions options, out bool modified) + { + return FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); } /// - public void ValidateUrl(string urlPath, int tabld, PortalSettings portalSettings, out bool modified) - { - FriendlyUrlController.ValidateUrl(urlPath, tabld, portalSettings, out modified); - } - } -} + [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", Justification = "Breaking change")] + public void ValidateUrl(string urlPath, int tabld, PortalSettings portalSettings, out bool modified) + { + FriendlyUrlController.ValidateUrl(urlPath, tabld, portalSettings, out modified); + } + } +} diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ITemplateController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ITemplateController.cs index 1e2b39e9bb9..6d7be0510fd 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ITemplateController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ITemplateController.cs @@ -2,22 +2,24 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace Dnn.PersonaBar.Pages.Components -{ - using System.Collections.Generic; +namespace Dnn.PersonaBar.Pages.Components +{ + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; - using Dnn.PersonaBar.Pages.Components.Dto; - using Dnn.PersonaBar.Pages.Services.Dto; - using DotNetNuke.Entities.Tabs; + using Dnn.PersonaBar.Pages.Components.Dto; + using Dnn.PersonaBar.Pages.Services.Dto; + using DotNetNuke.Entities.Tabs; - public interface ITemplateController - { - string SaveAsTemplate(PageTemplate template); - - IEnumerable