diff --git a/DNN Platform/Admin Modules/Dnn.Modules.Console/Settings.ascx.cs b/DNN Platform/Admin Modules/Dnn.Modules.Console/Settings.ascx.cs index cee4de7766d..b8f9dd8c1a6 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.Console/Settings.ascx.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.Console/Settings.ascx.cs @@ -25,82 +25,6 @@ public partial class Settings : ModuleSettingsBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Settings)); - private void BindTabs(int tabId, bool includeParent) - { - List tempTabs = TabController.GetTabsBySortOrder(this.PortalId).OrderBy(t => t.Level).ThenBy(t => t.HasChildren).ToList(); - - IList tabList = new List(); - - IList tabIdList = new List(); - tabIdList.Add(tabId); - - if (includeParent) - { - TabInfo consoleTab = TabController.Instance.GetTab(tabId, this.PortalId); - if (consoleTab != null) - { - tabList.Add(consoleTab); - } - } - - foreach (TabInfo tab in tempTabs) - { - bool canShowTab = TabPermissionController.CanViewPage(tab) && - !tab.IsDeleted && - (tab.StartDate < DateTime.Now || tab.StartDate == Null.NullDate); - - if (!canShowTab) - { - continue; - } - - if (tabIdList.Contains(tab.ParentId)) - { - if (!tabIdList.Contains(tab.TabID)) - { - tabIdList.Add(tab.TabID); - } - - tabList.Add(tab); - } - } - - this.tabs.DataSource = tabList; - this.tabs.DataBind(); - } - - private void SwitchMode() - { - int parentTabId = -1; - if (this.Settings.ContainsKey("ParentTabID") && !string.IsNullOrEmpty(Convert.ToString(this.Settings["ParentTabID"]))) - { - parentTabId = Convert.ToInt32(this.Settings["ParentTabID"]); - } - - switch (this.modeList.SelectedValue) - { - case "Normal": - this.parentTabRow.Visible = true; - this.includeParentRow.Visible = true; - this.tabVisibilityRow.Visible = false; - break; - case "Profile": - this.parentTabRow.Visible = false; - this.includeParentRow.Visible = false; - this.tabVisibilityRow.Visible = true; - parentTabId = this.PortalSettings.UserTabId; - break; - case "Group": - this.parentTabRow.Visible = true; - this.includeParentRow.Visible = true; - this.tabVisibilityRow.Visible = true; - break; - } - - this.ParentTab.SelectedPage = TabController.Instance.GetTab(parentTabId, this.PortalId); - this.BindTabs(parentTabId, this.IncludeParent.Checked); - } - public override void LoadSettings() { try @@ -232,6 +156,82 @@ public override void UpdateSettings() } } + private void BindTabs(int tabId, bool includeParent) + { + List tempTabs = TabController.GetTabsBySortOrder(this.PortalId).OrderBy(t => t.Level).ThenBy(t => t.HasChildren).ToList(); + + IList tabList = new List(); + + IList tabIdList = new List(); + tabIdList.Add(tabId); + + if (includeParent) + { + TabInfo consoleTab = TabController.Instance.GetTab(tabId, this.PortalId); + if (consoleTab != null) + { + tabList.Add(consoleTab); + } + } + + foreach (TabInfo tab in tempTabs) + { + bool canShowTab = TabPermissionController.CanViewPage(tab) && + !tab.IsDeleted && + (tab.StartDate < DateTime.Now || tab.StartDate == Null.NullDate); + + if (!canShowTab) + { + continue; + } + + if (tabIdList.Contains(tab.ParentId)) + { + if (!tabIdList.Contains(tab.TabID)) + { + tabIdList.Add(tab.TabID); + } + + tabList.Add(tab); + } + } + + this.tabs.DataSource = tabList; + this.tabs.DataBind(); + } + + private void SwitchMode() + { + int parentTabId = -1; + if (this.Settings.ContainsKey("ParentTabID") && !string.IsNullOrEmpty(Convert.ToString(this.Settings["ParentTabID"]))) + { + parentTabId = Convert.ToInt32(this.Settings["ParentTabID"]); + } + + switch (this.modeList.SelectedValue) + { + case "Normal": + this.parentTabRow.Visible = true; + this.includeParentRow.Visible = true; + this.tabVisibilityRow.Visible = false; + break; + case "Profile": + this.parentTabRow.Visible = false; + this.includeParentRow.Visible = false; + this.tabVisibilityRow.Visible = true; + parentTabId = this.PortalSettings.UserTabId; + break; + case "Group": + this.parentTabRow.Visible = true; + this.includeParentRow.Visible = true; + this.tabVisibilityRow.Visible = true; + break; + } + + this.ParentTab.SelectedPage = TabController.Instance.GetTab(parentTabId, this.PortalId); + this.BindTabs(parentTabId, this.IncludeParent.Checked); + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -242,14 +242,14 @@ protected override void OnInit(EventArgs e) this.ParentTab.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, string.Empty); } - private void modeList_SelectedIndexChanged(object sender, EventArgs e) + protected void parentTab_SelectedIndexChanged(object sender, EventArgs e) { - this.SwitchMode(); + this.BindTabs(this.ParentTab.SelectedItemValueAsInt, this.IncludeParent.Checked); } - protected void parentTab_SelectedIndexChanged(object sender, EventArgs e) + private void modeList_SelectedIndexChanged(object sender, EventArgs e) { - this.BindTabs(this.ParentTab.SelectedItemValueAsInt, this.IncludeParent.Checked); + this.SwitchMode(); } private void tabs_ItemDataBound(object Sender, RepeaterItemEventArgs e) diff --git a/DNN Platform/Admin Modules/Dnn.Modules.Console/ViewConsole.ascx.cs b/DNN Platform/Admin Modules/Dnn.Modules.Console/ViewConsole.ascx.cs index af8bc429c2c..c9eb81f52b2 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.Console/ViewConsole.ascx.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.Console/ViewConsole.ascx.cs @@ -29,8 +29,8 @@ namespace Dnn.Modules.Console public partial class ViewConsole : PortalModuleBase { - private readonly INavigationManager _navigationManager; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ViewConsole)); + private readonly INavigationManager _navigationManager; private ConsoleController _consoleCtrl; private string _defaultSize = string.Empty; private string _defaultView = string.Empty; @@ -191,6 +191,118 @@ public bool OrderTabsByHierarchy } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + try + { + JavaScript.RequestRegistration(CommonJs.jQuery); + + ClientResourceManager.RegisterScript(this.Page, "~/desktopmodules/admin/console/scripts/jquery.console.js"); + + this.DetailView.ItemDataBound += this.RepeaterItemDataBound; + + // Save User Preferences + this.SavePersonalizedSettings(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + try + { + this.IconSize.Visible = this.AllowSizeChange; + this.View.Visible = this.AllowViewChange; + + foreach (string val in ConsoleController.GetSizeValues()) + { + this.IconSize.Items.Add(new ListItem(Localization.GetString(val + ".Text", this.LocalResourceFile), val)); + } + + foreach (string val in ConsoleController.GetViewValues()) + { + this.View.Items.Add(new ListItem(Localization.GetString(val + ".Text", this.LocalResourceFile), val)); + } + + this.IconSize.SelectedValue = this.DefaultSize; + this.View.SelectedValue = this.DefaultView; + + if (!this.IsPostBack) + { + this.Console.Attributes["class"] = this.Console.Attributes["class"] + " " + this.Mode.ToLower(CultureInfo.InvariantCulture); + + this.SettingsBreak.Visible = this.AllowSizeChange && this.AllowViewChange; + + List tempTabs = this.IsHostTab() + ? TabController.GetTabsBySortOrder(Null.NullInteger).OrderBy(t => t.Level).ThenBy(t => t.LocalizedTabName).ToList() + : TabController.GetTabsBySortOrder(this.PortalId).OrderBy(t => t.Level).ThenBy(t => t.LocalizedTabName).ToList(); + + this._tabs = new List(); + + IList tabIdList = new List(); + tabIdList.Add(this.ConsoleTabID); + + if (this.IncludeParent) + { + TabInfo consoleTab = TabController.Instance.GetTab(this.ConsoleTabID, this.PortalId); + if (consoleTab != null) + { + this._tabs.Add(consoleTab); + } + } + + foreach (TabInfo tab in tempTabs) + { + if (!this.CanShowTab(tab)) + { + continue; + } + + if (tabIdList.Contains(tab.ParentId)) + { + if (!tabIdList.Contains(tab.TabID)) + { + tabIdList.Add(tab.TabID); + } + + this._tabs.Add(tab); + } + } + + // if OrderTabsByHierarchy set to true, we need reorder the tab list to move tabs which have child tabs to the end of list. + // so that the list display in UI can show tabs in same level in same area, and not break by child tabs. + if (this.OrderTabsByHierarchy) + { + this._tabs = this._tabs.OrderBy(t => t.HasChildren).ToList(); + } + + int minLevel = -1; + if (this._tabs.Count > 0) + { + minLevel = this._tabs.Min(t => t.Level); + } + + this.DetailView.DataSource = (minLevel > -1) ? this._tabs.Where(t => t.Level == minLevel) : this._tabs; + this.DetailView.DataBind(); + } + + if (this.ConsoleWidth != string.Empty) + { + this.Console.Attributes.Add("style", "width:" + this.ConsoleWidth); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private bool CanShowTab(TabInfo tab) { bool canShowTab = TabPermissionController.CanViewPage(tab) && @@ -324,132 +436,6 @@ private void SaveUserSetting(string key, object val) { Personalization.SetProfile(this.ModuleConfiguration.ModuleDefinition.FriendlyName, this.PersonalizationKey(key), val); } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - try - { - JavaScript.RequestRegistration(CommonJs.jQuery); - - ClientResourceManager.RegisterScript(this.Page, "~/desktopmodules/admin/console/scripts/jquery.console.js"); - - this.DetailView.ItemDataBound += this.RepeaterItemDataBound; - - // Save User Preferences - this.SavePersonalizedSettings(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - try - { - this.IconSize.Visible = this.AllowSizeChange; - this.View.Visible = this.AllowViewChange; - - foreach (string val in ConsoleController.GetSizeValues()) - { - this.IconSize.Items.Add(new ListItem(Localization.GetString(val + ".Text", this.LocalResourceFile), val)); - } - - foreach (string val in ConsoleController.GetViewValues()) - { - this.View.Items.Add(new ListItem(Localization.GetString(val + ".Text", this.LocalResourceFile), val)); - } - - this.IconSize.SelectedValue = this.DefaultSize; - this.View.SelectedValue = this.DefaultView; - - if (!this.IsPostBack) - { - this.Console.Attributes["class"] = this.Console.Attributes["class"] + " " + this.Mode.ToLower(CultureInfo.InvariantCulture); - - this.SettingsBreak.Visible = this.AllowSizeChange && this.AllowViewChange; - - List tempTabs = this.IsHostTab() - ? TabController.GetTabsBySortOrder(Null.NullInteger).OrderBy(t => t.Level).ThenBy(t => t.LocalizedTabName).ToList() - : TabController.GetTabsBySortOrder(this.PortalId).OrderBy(t => t.Level).ThenBy(t => t.LocalizedTabName).ToList(); - - this._tabs = new List(); - - IList tabIdList = new List(); - tabIdList.Add(this.ConsoleTabID); - - if (this.IncludeParent) - { - TabInfo consoleTab = TabController.Instance.GetTab(this.ConsoleTabID, this.PortalId); - if (consoleTab != null) - { - this._tabs.Add(consoleTab); - } - } - - foreach (TabInfo tab in tempTabs) - { - if (!this.CanShowTab(tab)) - { - continue; - } - - if (tabIdList.Contains(tab.ParentId)) - { - if (!tabIdList.Contains(tab.TabID)) - { - tabIdList.Add(tab.TabID); - } - - this._tabs.Add(tab); - } - } - - // if OrderTabsByHierarchy set to true, we need reorder the tab list to move tabs which have child tabs to the end of list. - // so that the list display in UI can show tabs in same level in same area, and not break by child tabs. - if (this.OrderTabsByHierarchy) - { - this._tabs = this._tabs.OrderBy(t => t.HasChildren).ToList(); - } - - int minLevel = -1; - if (this._tabs.Count > 0) - { - minLevel = this._tabs.Min(t => t.Level); - } - - this.DetailView.DataSource = (minLevel > -1) ? this._tabs.Where(t => t.Level == minLevel) : this._tabs; - this.DetailView.DataBind(); - } - - if (this.ConsoleWidth != string.Empty) - { - this.Console.Attributes.Add("style", "width:" + this.ConsoleWidth); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - private void RepeaterItemDataBound(object sender, RepeaterItemEventArgs e) - { - var tab = e.Item.DataItem as TabInfo; - e.Item.Controls.Add(new Literal() { Text = this.GetHtml(tab) }); - if (this._tabs.Any(t => t.ParentId == tab.TabID)) - { - var repeater = new Repeater(); - repeater.ItemDataBound += this.RepeaterItemDataBound; - e.Item.Controls.Add(repeater); - repeater.DataSource = this._tabs.Where(t => t.ParentId == tab.TabID); - repeater.DataBind(); - } - } protected string GetHtml(TabInfo tab) { @@ -535,5 +521,19 @@ protected string GetClientSideSettings() tmid, this.ShowTooltip.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); } + + private void RepeaterItemDataBound(object sender, RepeaterItemEventArgs e) + { + var tab = e.Item.DataItem as TabInfo; + e.Item.Controls.Add(new Literal() { Text = this.GetHtml(tab) }); + if (this._tabs.Any(t => t.ParentId == tab.TabID)) + { + var repeater = new Repeater(); + repeater.ItemDataBound += this.RepeaterItemDataBound; + e.Item.Controls.Add(repeater); + repeater.DataSource = this._tabs.Where(t => t.ParentId == tab.TabID); + repeater.DataBind(); + } + } } } diff --git a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/CreateModule.ascx.cs b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/CreateModule.ascx.cs index cc9d0ce2bfb..6ad015b98f7 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/CreateModule.ascx.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/CreateModule.ascx.cs @@ -32,6 +32,40 @@ public CreateModule() this._navigationManager = this.DependencyProvider.GetRequiredService(); } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.optLanguage.SelectedIndexChanged += this.optLanguage_SelectedIndexChanged; + this.cboTemplate.SelectedIndexChanged += this.cboTemplate_SelectedIndexChanged; + this.cmdCreate.Click += this.cmdCreate_Click; + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + if (this.UserInfo.IsSuperUser) + { + if (!this.Page.IsPostBack) + { + Dictionary HostSettings = HostController.Instance.GetSettingsDictionary(); + if (HostSettings.ContainsKey("Owner")) + { + this.txtOwner.Text = HostSettings["Owner"]; + } + + this.LoadLanguages(); + this.LoadModuleTemplates(); + this.txtControl.Text = "View"; + } + } + else + { + DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SuperUser.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); + this.createForm.Visible = false; + } + } + private void LoadReadMe() { var readMePath = this.Server.MapPath(this.ControlPath) + "Templates\\" + this.optLanguage.SelectedValue + "\\" + this.cboTemplate.SelectedItem.Value + "\\readme.txt"; @@ -369,40 +403,6 @@ private bool CreateModuleDefinition() return false; } } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.optLanguage.SelectedIndexChanged += this.optLanguage_SelectedIndexChanged; - this.cboTemplate.SelectedIndexChanged += this.cboTemplate_SelectedIndexChanged; - this.cmdCreate.Click += this.cmdCreate_Click; - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - if (this.UserInfo.IsSuperUser) - { - if (!this.Page.IsPostBack) - { - Dictionary HostSettings = HostController.Instance.GetSettingsDictionary(); - if (HostSettings.ContainsKey("Owner")) - { - this.txtOwner.Text = HostSettings["Owner"]; - } - - this.LoadLanguages(); - this.LoadModuleTemplates(); - this.txtControl.Text = "View"; - } - } - else - { - DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SuperUser.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); - this.createForm.Visible = false; - } - } protected void optLanguage_SelectedIndexChanged(object sender, EventArgs e) { diff --git a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/viewsource.ascx.cs b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/viewsource.ascx.cs index 417f36fe058..24579a9b814 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/viewsource.ascx.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/viewsource.ascx.cs @@ -53,6 +53,56 @@ private string ReturnURL } } + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + + this.cboFile.SelectedIndexChanged += this.OnFileIndexChanged; + this.optLanguage.SelectedIndexChanged += this.OnLanguageSelectedIndexChanged; + this.cboTemplate.SelectedIndexChanged += this.cboTemplate_SelectedIndexChanged; + this.cmdUpdate.Click += this.OnUpdateClick; + this.cmdPackage.Click += this.OnPackageClick; + this.cmdConfigure.Click += this.OnConfigureClick; + this.cmdCreate.Click += this.OnCreateClick; + + if (this.Page.IsPostBack == false) + { + this.cmdCancel1.NavigateUrl = this.ReturnURL; + this.cmdCancel2.NavigateUrl = this.ReturnURL; + + var objModuleControl = ModuleControlController.GetModuleControl(this.ModuleControlId); + if (objModuleControl != null) + { + this.BindFiles(objModuleControl.ControlSrc); + this.LoadFile(); + } + + if (this.Request.UrlReferrer != null) + { + this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); + } + else + { + this.ViewState["UrlReferrer"] = string.Empty; + } + + this.LoadLanguages(); + this.LoadModuleTemplates(); + if (this.cboTemplate.Items.FindByText("Module - User Control") != null) + { + this.cboTemplate.Items.FindByText("Module - User Control").Selected = true; + } + + this.LoadReadMe(); + } + } + + protected void OnFileIndexChanged(object sender, EventArgs e) + { + this.LoadFile(); + } + private void BindFiles(string controlSrc) { string[] fileList; @@ -425,56 +475,6 @@ private string GetControl() { return this.txtControl.Text.Replace(" ", string.Empty); } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - - this.cboFile.SelectedIndexChanged += this.OnFileIndexChanged; - this.optLanguage.SelectedIndexChanged += this.OnLanguageSelectedIndexChanged; - this.cboTemplate.SelectedIndexChanged += this.cboTemplate_SelectedIndexChanged; - this.cmdUpdate.Click += this.OnUpdateClick; - this.cmdPackage.Click += this.OnPackageClick; - this.cmdConfigure.Click += this.OnConfigureClick; - this.cmdCreate.Click += this.OnCreateClick; - - if (this.Page.IsPostBack == false) - { - this.cmdCancel1.NavigateUrl = this.ReturnURL; - this.cmdCancel2.NavigateUrl = this.ReturnURL; - - var objModuleControl = ModuleControlController.GetModuleControl(this.ModuleControlId); - if (objModuleControl != null) - { - this.BindFiles(objModuleControl.ControlSrc); - this.LoadFile(); - } - - if (this.Request.UrlReferrer != null) - { - this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); - } - else - { - this.ViewState["UrlReferrer"] = string.Empty; - } - - this.LoadLanguages(); - this.LoadModuleTemplates(); - if (this.cboTemplate.Items.FindByText("Module - User Control") != null) - { - this.cboTemplate.Items.FindByText("Module - User Control").Selected = true; - } - - this.LoadReadMe(); - } - } - - protected void OnFileIndexChanged(object sender, EventArgs e) - { - this.LoadFile(); - } protected void OnLanguageSelectedIndexChanged(object sender, EventArgs e) { diff --git a/DNN Platform/Connectors/Azure/Components/AzureConnector.cs b/DNN Platform/Connectors/Azure/Components/AzureConnector.cs index 668ee71105f..40bab23156f 100644 --- a/DNN Platform/Connectors/Azure/Components/AzureConnector.cs +++ b/DNN Platform/Connectors/Azure/Components/AzureConnector.cs @@ -22,15 +22,15 @@ namespace Dnn.AzureConnector.Components public class AzureConnector : IConnector { - private static readonly DataProvider dataProvider = DataProvider.Instance(); private const string DefaultDisplayName = "Azure Storage"; + private static readonly DataProvider dataProvider = DataProvider.Instance(); + + private string _displayName; public string Name { get { return "Azure"; } } - - private string _displayName; public string DisplayName { @@ -234,6 +234,45 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo return false; } } + + internal static FolderMappingInfo FindAzureFolderMappingStatic(int portalId, int? folderMappingId = null, + bool autoCreate = true) + { + var folderMappings = FolderMappingController.Instance.GetFolderMappings(portalId) + .Where(f => f.FolderProviderType == Constants.FolderProviderType); + + if (folderMappingId != null) + { + return folderMappings.FirstOrDefault(x => x.FolderMappingID == folderMappingId); + } + + if (!folderMappings.Any() && autoCreate) + { + return CreateAzureFolderMappingStatic(portalId); + } + + return folderMappings.FirstOrDefault(); + } + + private static FolderMappingInfo CreateAzureFolderMappingStatic(int portalId, string mappingName = "") + { + var folderMapping = new FolderMappingInfo + { + PortalID = portalId, + MappingName = + string.IsNullOrEmpty(mappingName) + ? $"{DefaultDisplayName}_{DateTime.Now.Ticks}" + : mappingName, + FolderProviderType = Constants.FolderProviderType, + }; + folderMapping.FolderMappingID = FolderMappingController.Instance.AddFolderMapping(folderMapping); + return folderMapping; + } + + private static void DeleteAzureFolderMapping(int portalId, int folderMappingId) + { + FolderMappingController.Instance.DeleteFolderMapping(portalId, folderMappingId); + } private bool Validation(string azureAccountName, string azureAccountKey, string azureContainerName) { @@ -342,25 +381,6 @@ private string GetSetting(Hashtable settings, string name, bool encrypt = false) return settings[name].ToString(); } - internal static FolderMappingInfo FindAzureFolderMappingStatic(int portalId, int? folderMappingId = null, - bool autoCreate = true) - { - var folderMappings = FolderMappingController.Instance.GetFolderMappings(portalId) - .Where(f => f.FolderProviderType == Constants.FolderProviderType); - - if (folderMappingId != null) - { - return folderMappings.FirstOrDefault(x => x.FolderMappingID == folderMappingId); - } - - if (!folderMappings.Any() && autoCreate) - { - return CreateAzureFolderMappingStatic(portalId); - } - - return folderMappings.FirstOrDefault(); - } - private FolderMappingInfo FindAzureFolderMapping(int portalId, bool autoCreate = true, bool checkId = false) { var folderMappings = FolderMappingController.Instance.GetFolderMappings(portalId) @@ -409,26 +429,6 @@ private FolderMappingInfo CreateAzureFolderMapping(int portalId, string mappingN return folderMapping; } - private static FolderMappingInfo CreateAzureFolderMappingStatic(int portalId, string mappingName = "") - { - var folderMapping = new FolderMappingInfo - { - PortalID = portalId, - MappingName = - string.IsNullOrEmpty(mappingName) - ? $"{DefaultDisplayName}_{DateTime.Now.Ticks}" - : mappingName, - FolderProviderType = Constants.FolderProviderType, - }; - folderMapping.FolderMappingID = FolderMappingController.Instance.AddFolderMapping(folderMapping); - return folderMapping; - } - - private static void DeleteAzureFolderMapping(int portalId, int folderMappingId) - { - FolderMappingController.Instance.DeleteFolderMapping(portalId, folderMappingId); - } - private static void DeleteAzureFolderMapping(int portalId) { var folderMapping = FolderMappingController.Instance.GetFolderMappings(portalId) diff --git a/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs b/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs index 934543164c9..94f4c297d43 100644 --- a/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs +++ b/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs @@ -17,13 +17,13 @@ public class GoogleAnalyticsConnector : IConnector { private const string DefaultDisplayName = "Google Analytics"; + private string _displayName; + public string Name { get { return "Core Google Analytics Connector"; } } - private string _displayName; - public string DisplayName { get @@ -134,22 +134,6 @@ public IDictionary GetConfig(int portalId) return configItems; } - /// - /// Handles custom conversion from "true" => "true" - /// Anything else to "" to support the strange knockout handling of string as booleans. - /// - /// - /// - private string HandleCustomBoolean(string value) - { - if (value.Trim().Equals("true", StringComparison.OrdinalIgnoreCase)) - { - return "true"; - } - - return string.Empty; - } - public bool SaveConfig(int portalId, IDictionary values, ref bool validated, out string customErrorMessage) { // Delete / Deactivation functionality added into SaveConfig because @@ -242,5 +226,21 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo return false; } } + + /// + /// Handles custom conversion from "true" => "true" + /// Anything else to "" to support the strange knockout handling of string as booleans. + /// + /// + /// + private string HandleCustomBoolean(string value) + { + if (value.Trim().Equals("true", StringComparison.OrdinalIgnoreCase)) + { + return "true"; + } + + return string.Empty; + } } } diff --git a/DNN Platform/Controls/CountryListBox/CountryLookup.cs b/DNN Platform/Controls/CountryListBox/CountryLookup.cs index 8b20248132a..41c676e5270 100644 --- a/DNN Platform/Controls/CountryListBox/CountryLookup.cs +++ b/DNN Platform/Controls/CountryListBox/CountryLookup.cs @@ -59,8 +59,6 @@ public class CountryLookup "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZR", "ZW", "A1", "A2", }; - public MemoryStream m_MemoryStream { get; } - public CountryLookup(MemoryStream ms) { this.m_MemoryStream = ms; @@ -84,29 +82,7 @@ public CountryLookup(string FileLocation) } } - private long ConvertIPAddressToNumber(IPAddress _IPAddress) - { - // Convert an IP Address, (e.g. 127.0.0.1), to the numeric equivalent - string[] _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])); - } - else - { - return 0; - } - } - - private 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; - } + public MemoryStream m_MemoryStream { get; } public static MemoryStream FileToMemory(string FileLocation) { @@ -141,6 +117,30 @@ public string LookupCountryCode(IPAddress _IPAddress) return CountryCode[Convert.ToInt32(this.SeekCountry(0, this.ConvertIPAddressToNumber(_IPAddress), 31))]; } + private long ConvertIPAddressToNumber(IPAddress _IPAddress) + { + // Convert an IP Address, (e.g. 127.0.0.1), to the numeric equivalent + string[] _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])); + } + else + { + return 0; + } + } + + private 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; + } + public string LookupCountryCode(string _IPAddress) { // Look up the country code, e.g. US, for the passed in IP Address diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Auth/JwtAuthMessageHandler.cs b/DNN Platform/Dnn.AuthServices.Jwt/Auth/JwtAuthMessageHandler.cs index a70d693e29f..465c0466e7b 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Auth/JwtAuthMessageHandler.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Auth/JwtAuthMessageHandler.cs @@ -23,12 +23,6 @@ namespace Dnn.AuthServices.Jwt.Auth public class JwtAuthMessageHandler : AuthMessageHandlerBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JwtAuthMessageHandler)); - - public override string AuthScheme => this._jwtController.SchemeType; - - public override bool BypassAntiForgeryToken => true; - - internal static bool IsEnabled { get; set; } private readonly IJwtController _jwtController = JwtController.Instance; @@ -40,6 +34,12 @@ public JwtAuthMessageHandler(bool includeByDefault, bool forceSsl) // this scheme gets marked as enabled. IsEnabled = true; } + + public override string AuthScheme => this._jwtController.SchemeType; + + public override bool BypassAntiForgeryToken => true; + + internal static bool IsEnabled { get; set; } public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) { diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/JwtController.cs b/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/JwtController.cs index cd821c9c0d1..b0f5754a8d6 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/JwtController.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/JwtController.cs @@ -27,25 +27,22 @@ namespace Dnn.AuthServices.Jwt.Components.Common.Controllers internal class JwtController : ServiceLocator, IJwtController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JwtController)); - private static readonly HashAlgorithm Hasher = SHA384.Create(); + public const string AuthScheme = "Bearer"; + public readonly IDataService DataProvider = DataService.Instance; + private const int ClockSkew = 5; // in minutes; default for clock skew private const int SessionTokenTtl = 60; // in minutes = 1 hour + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JwtController)); + private static readonly HashAlgorithm Hasher = SHA384.Create(); private const int RenewalTokenTtl = 14; // in days = 2 weeks private const string SessionClaimType = "sid"; private static readonly Encoding TextEncoder = Encoding.UTF8; - - public const string AuthScheme = "Bearer"; public string SchemeType => "JWT"; - protected override Func GetFactory() - { - return () => new JwtController(); - } - - public readonly IDataService DataProvider = DataService.Instance; + private static string NewSessionId => DateTime.UtcNow.Ticks.ToString("x16") + Guid.NewGuid().ToString("N").Substring(16); /// /// Validates the received JWT against the databas eand returns username when successful. @@ -92,6 +89,11 @@ public bool LogoutUser(HttpRequestMessage request) this.DataProvider.DeleteToken(sessionId); return true; } + + protected override Func GetFactory() + { + return () => new JwtController(); + } /// /// Validates user login credentials and returns result when successful. @@ -261,6 +263,30 @@ public LoginResultData RenewToken(HttpRequestMessage request, string renewalToke return this.UpdateToken(renewalToken, ptoken, userInfo); } + private static LoginResultData EmptyWithError(string error) + { + return new LoginResultData { Error = error }; + } + + private static JwtSecurityToken CreateJwtToken(byte[] symmetricKey, string issuer, PersistedToken ptoken, IEnumerable roles) + { + // var key = Convert.FromBase64String(symmetricKey); + var credentials = new SigningCredentials( + new InMemorySymmetricSecurityKey(symmetricKey), + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", + "http://www.w3.org/2001/04/xmlenc#sha256"); + + var claimsIdentity = new ClaimsIdentity(); + claimsIdentity.AddClaim(new Claim(SessionClaimType, ptoken.TokenId)); + claimsIdentity.AddClaims(roles.Select(r => new Claim(ClaimTypes.Role, r))); + + var notBefore = DateTime.UtcNow.AddMinutes(-ClockSkew); + var notAfter = ptoken.TokenExpiry; + var tokenHandler = new JwtSecurityTokenHandler(); + var token = tokenHandler.CreateToken(issuer, null, claimsIdentity, notBefore, notAfter, credentials); + return token; + } + private LoginResultData UpdateToken(string renewalToken, PersistedToken ptoken, UserInfo userInfo) { var expiry = DateTime.UtcNow.AddMinutes(SessionTokenTtl); @@ -289,31 +315,59 @@ private LoginResultData UpdateToken(string renewalToken, PersistedToken ptoken, RenewalToken = renewalToken, }; } - - private static string NewSessionId => DateTime.UtcNow.Ticks.ToString("x16") + Guid.NewGuid().ToString("N").Substring(16); - private static LoginResultData EmptyWithError(string error) + private static JwtSecurityToken GetAndValidateJwt(string rawToken, bool checkExpiry) { - return new LoginResultData { Error = error }; + JwtSecurityToken jwt; + try + { + jwt = new JwtSecurityToken(rawToken); + } + catch (Exception ex) + { + Logger.Error("Unable to construct JWT object from authorization value. " + ex.Message); + return null; + } + + if (checkExpiry) + { + var now = DateTime.UtcNow; + if (now < jwt.ValidFrom || now > jwt.ValidTo) + { + if (Logger.IsTraceEnabled) + { + Logger.Trace("Token is expired"); + } + + return null; + } + } + + var sessionId = GetJwtSessionValue(jwt); + if (string.IsNullOrEmpty(sessionId)) + { + if (Logger.IsTraceEnabled) + { + Logger.Trace("Invaid session ID claim"); + } + + return null; + } + + return jwt; } - private static JwtSecurityToken CreateJwtToken(byte[] symmetricKey, string issuer, PersistedToken ptoken, IEnumerable roles) + private static string GetJwtSessionValue(JwtSecurityToken jwt) { - // var key = Convert.FromBase64String(symmetricKey); - var credentials = new SigningCredentials( - new InMemorySymmetricSecurityKey(symmetricKey), - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", - "http://www.w3.org/2001/04/xmlenc#sha256"); - - var claimsIdentity = new ClaimsIdentity(); - claimsIdentity.AddClaim(new Claim(SessionClaimType, ptoken.TokenId)); - claimsIdentity.AddClaims(roles.Select(r => new Claim(ClaimTypes.Role, r))); + var sessionClaim = jwt?.Claims?.FirstOrDefault(claim => SessionClaimType.Equals(claim.Type)); + return sessionClaim?.Value; + } - var notBefore = DateTime.UtcNow.AddMinutes(-ClockSkew); - var notAfter = ptoken.TokenExpiry; - var tokenHandler = new JwtSecurityTokenHandler(); - var token = tokenHandler.CreateToken(issuer, null, claimsIdentity, notBefore, notAfter, credentials); - return token; + private static byte[] ObtainSecret(string sessionId, Guid portalGuid, DateTime userCreationDate) + { + // The secret should contain unpredictable components that can't be inferred from the JWT string. + var stext = string.Join(".", sessionId, portalGuid.ToString("N"), userCreationDate.ToUniversalTime().ToString("O")); + return TextEncoder.GetBytes(stext); } /// @@ -408,47 +462,6 @@ private bool IsValidSchemeType(JwtHeader header) return true; } - private static JwtSecurityToken GetAndValidateJwt(string rawToken, bool checkExpiry) - { - JwtSecurityToken jwt; - try - { - jwt = new JwtSecurityToken(rawToken); - } - catch (Exception ex) - { - Logger.Error("Unable to construct JWT object from authorization value. " + ex.Message); - return null; - } - - if (checkExpiry) - { - var now = DateTime.UtcNow; - if (now < jwt.ValidFrom || now > jwt.ValidTo) - { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Token is expired"); - } - - return null; - } - } - - var sessionId = GetJwtSessionValue(jwt); - if (string.IsNullOrEmpty(sessionId)) - { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Invaid session ID claim"); - } - - return null; - } - - return jwt; - } - private UserInfo TryGetUser(JwtSecurityToken jwt, bool checkExpiry) { // validate against DB saved data @@ -521,19 +534,6 @@ private UserInfo TryGetUser(JwtSecurityToken jwt, bool checkExpiry) return userInfo; } - private static string GetJwtSessionValue(JwtSecurityToken jwt) - { - var sessionClaim = jwt?.Claims?.FirstOrDefault(claim => SessionClaimType.Equals(claim.Type)); - return sessionClaim?.Value; - } - - private static byte[] ObtainSecret(string sessionId, Guid portalGuid, DateTime userCreationDate) - { - // The secret should contain unpredictable components that can't be inferred from the JWT string. - var stext = string.Join(".", sessionId, portalGuid.ToString("N"), userCreationDate.ToUniversalTime().ToString("O")); - return TextEncoder.GetBytes(stext); - } - private static string DecodeBase64(string b64Str) { // fix Base64 string padding diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Services/MobileController.cs b/DNN Platform/Dnn.AuthServices.Jwt/Services/MobileController.cs index 27703e25c2f..86e7be10c57 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Services/MobileController.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Services/MobileController.cs @@ -59,22 +59,6 @@ public IHttpActionResult ExtendToken(RenewalDto rtoken) return this.ReplyWith(result); } - private IHttpActionResult ReplyWith(LoginResultData result) - { - if (result == null) - { - return this.Unauthorized(); - } - - if (!string.IsNullOrEmpty(result.Error)) - { - // HACK: this will return the scheme with the error message as a challenge; non-standard method - return this.Unauthorized(new AuthenticationHeaderValue(JwtController.AuthScheme, result.Error)); - } - - return this.Ok(result); - } - // Test API Method 1 [HttpGet] public IHttpActionResult TestGet() @@ -94,6 +78,22 @@ public IHttpActionResult TestPost(TestPostData something) $" You said: ({something.Text})"; return this.Ok(new { reply }); } + + private IHttpActionResult ReplyWith(LoginResultData result) + { + if (result == null) + { + return this.Unauthorized(); + } + + if (!string.IsNullOrEmpty(result.Error)) + { + // HACK: this will return the scheme with the error message as a challenge; non-standard method + return this.Unauthorized(new AuthenticationHeaderValue(JwtController.AuthScheme, result.Error)); + } + + return this.Ok(result); + } [JsonObject] public class TestPostData diff --git a/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs b/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs index 0a72b0bf847..fd2afe204f7 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs @@ -55,32 +55,6 @@ private static Type CallingType } } - private static void EnsureConfig() - { - if (!_configured) - { - lock (ConfigLock) - { - if (!_configured) - { - var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFile); - var originalPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config\\" + ConfigFile); - if (!File.Exists(configPath) && File.Exists(originalPath)) - { - File.Copy(originalPath, configPath); - } - - if (File.Exists(configPath)) - { - XmlConfigurator.ConfigureAndWatch(new FileInfo(configPath)); - } - - _configured = true; - } - } - } - } - /// /// Standard method to use on method entry. /// @@ -112,6 +86,32 @@ public static void MethodExit(object returnObject) } } + private static void EnsureConfig() + { + if (!_configured) + { + lock (ConfigLock) + { + if (!_configured) + { + var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFile); + var originalPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config\\" + ConfigFile); + if (!File.Exists(configPath) && File.Exists(originalPath)) + { + File.Copy(originalPath, configPath); + } + + if (File.Exists(configPath)) + { + XmlConfigurator.ConfigureAndWatch(new FileInfo(configPath)); + } + + _configured = true; + } + } + } + } + /// /// Standard method to use on method exit. /// diff --git a/DNN Platform/DotNetNuke.Instrumentation/DnnLogger.cs b/DNN Platform/DotNetNuke.Instrumentation/DnnLogger.cs index abc172d45b8..8bf8fa91c3c 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/DnnLogger.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/DnnLogger.cs @@ -41,10 +41,10 @@ private DnnLogger(ILogger logger) if (stack != null) { int frameDepth = 0; - Type methodType = stack[frameDepth].GetMethod().ReflectedType; - #pragma warning disable 612,618 - while (methodType == this._dnnExceptionType || methodType == typeof(DnnLogger) || methodType == typeof(DnnLog) || methodType == typeof(Control)) - #pragma warning restore 612,618 + Type methodType = stack[frameDepth].GetMethod().ReflectedType; +#pragma warning disable 612, 618 + while (methodType == this._dnnExceptionType || methodType == typeof(DnnLogger) || methodType == typeof(DnnLog) || methodType == typeof(Control)) +#pragma warning restore 612, 618 { frameDepth++; methodType = stack[frameDepth].GetMethod().ReflectedType; @@ -60,6 +60,16 @@ private DnnLogger(ILogger logger) ReloadLevels(logger.Repository); } + public static DnnLogger GetClassLogger(Type type) + { + return new DnnLogger(LogManager.GetLogger(Assembly.GetCallingAssembly(), type).Logger); + } + + public static DnnLogger GetLogger(string name) + { + return new DnnLogger(LogManager.GetLogger(name).Logger); + } + /// /// Virtual method called when the configuration of the repository changes. /// @@ -86,16 +96,6 @@ private static void ReloadLevels(ILoggerRepository repository) LogManager.GetRepository().LevelMap.Add(LevelLogInfo); LogManager.GetRepository().LevelMap.Add(LevelLogError); } - - public static DnnLogger GetClassLogger(Type type) - { - return new DnnLogger(LogManager.GetLogger(Assembly.GetCallingAssembly(), type).Logger); - } - - public static DnnLogger GetLogger(string name) - { - return new DnnLogger(LogManager.GetLogger(name).Logger); - } /// /// Logs a message object with the DEBUG level. @@ -252,21 +252,6 @@ public void InfoFormat(IFormatProvider provider, string format, params object[] { this.Logger.Log(this._stackBoundary, LevelInfo, new SystemStringFormat(provider, format, args), null); } - - internal void TraceFormat(string format, params object[] args) - { - this.Logger.Log(this._stackBoundary, LevelTrace, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - - internal void Trace(string message) - { - this.Logger.Log(this._stackBoundary, LevelTrace, message, null); - } - - internal void TraceFormat(IFormatProvider provider, string format, params object[] args) - { - this.Logger.Log(this._stackBoundary, LevelTrace, new SystemStringFormat(provider, format, args), null); - } /// /// Logs a message object with the WARN level. @@ -317,6 +302,21 @@ public void Warn(object message, Exception exception) this.Logger.Log(this._stackBoundary, LevelWarn, message, exception); } + internal void TraceFormat(string format, params object[] args) + { + this.Logger.Log(this._stackBoundary, LevelTrace, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + + internal void Trace(string message) + { + this.Logger.Log(this._stackBoundary, LevelTrace, message, null); + } + + internal void TraceFormat(IFormatProvider provider, string format, params object[] args) + { + this.Logger.Log(this._stackBoundary, LevelTrace, new SystemStringFormat(provider, format, args), null); + } + /// /// Logs a formatted message string with the WARN level. /// diff --git a/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs b/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs index f1404cb0ccd..e9f384f9b35 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs @@ -31,19 +31,19 @@ public ILog GetLogger(string name) private class Logger : LoggerWrapperImpl, ILog { + private const string ConfigFile = "DotNetNuke.log4net.config"; private static Level _levelTrace; private static Level _levelDebug; private static Level _levelInfo; private static Level _levelWarn; private static Level _levelError; - private static Level _levelFatal; + private static Level _levelFatal; + private static bool _configured; - // add custom logging levels (below trace value of 20000) -// internal static Level LevelLogInfo = new Level(10001, "LogInfo"); -// internal static Level LevelLogError = new Level(10002, "LogError"); + // add custom logging levels (below trace value of 20000) + // internal static Level LevelLogInfo = new Level(10001, "LogInfo"); + // internal static Level LevelLogError = new Level(10002, "LogError"); private readonly Type _stackBoundary = typeof(DnnLogger); - private const string ConfigFile = "DotNetNuke.log4net.config"; - private static bool _configured; private static readonly object ConfigLock = new object(); internal Logger(ILogger logger, Type type) @@ -54,6 +54,21 @@ internal Logger(ILogger logger, Type type) ReloadLevels(logger.Repository); } + public bool IsDebugEnabled + { + get { return this.Logger.IsEnabledFor(_levelDebug); } + } + + public bool IsInfoEnabled + { + get { return this.Logger.IsEnabledFor(_levelInfo); } + } + + public bool IsTraceEnabled + { + get { return this.Logger.IsEnabledFor(_levelTrace); } + } + private static void EnsureConfig() { if (!_configured) @@ -90,14 +105,14 @@ private static void ReloadLevels(ILoggerRepository repository) _levelInfo = levelMap.LookupWithDefault(Level.Info); _levelWarn = levelMap.LookupWithDefault(Level.Warn); _levelError = levelMap.LookupWithDefault(Level.Error); - _levelFatal = levelMap.LookupWithDefault(Level.Fatal); + _levelFatal = levelMap.LookupWithDefault(Level.Fatal); -// LevelLogError = levelMap.LookupWithDefault(LevelLogError); -// LevelLogInfo = levelMap.LookupWithDefault(LevelLogInfo); - - //// Register custom logging levels with the default LoggerRepository -// LogManager.GetRepository().LevelMap.Add(LevelLogInfo); -// LogManager.GetRepository().LevelMap.Add(LevelLogError); + // LevelLogError = levelMap.LookupWithDefault(LevelLogError); + // LevelLogInfo = levelMap.LookupWithDefault(LevelLogInfo); + + //// Register custom logging levels with the default LoggerRepository + // LogManager.GetRepository().LevelMap.Add(LevelLogInfo); + // LogManager.GetRepository().LevelMap.Add(LevelLogError); } private static void AddGlobalContext() @@ -122,31 +137,16 @@ private static void AddGlobalContext() // { // GlobalContext.Properties["processid"] = Process.GetCurrentProcess().Id.ToString("D"); // } - } + } -// ReSharper disable EmptyGeneralCatchClause - catch + // ReSharper disable EmptyGeneralCatchClause + catch -// ReSharper restore EmptyGeneralCatchClause + // ReSharper restore EmptyGeneralCatchClause { // do nothing but just make sure no exception here. } } - - public bool IsDebugEnabled - { - get { return this.Logger.IsEnabledFor(_levelDebug); } - } - - public bool IsInfoEnabled - { - get { return this.Logger.IsEnabledFor(_levelInfo); } - } - - public bool IsTraceEnabled - { - get { return this.Logger.IsEnabledFor(_levelTrace); } - } public bool IsWarnEnabled { diff --git a/DNN Platform/DotNetNuke.Log4net/DotNetNuke.Log4Net.csproj b/DNN Platform/DotNetNuke.Log4net/DotNetNuke.Log4Net.csproj index 16862a45a93..09a2d961042 100644 --- a/DNN Platform/DotNetNuke.Log4net/DotNetNuke.Log4Net.csproj +++ b/DNN Platform/DotNetNuke.Log4net/DotNetNuke.Log4Net.csproj @@ -727,18 +727,6 @@ - - - stylecop.json - - - - - - - - - $(MSBuildProjectDirectory)\..\.. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs index a75f8852977..f54b7c1b57a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs @@ -176,7 +176,7 @@ public enum AnsiColor : int /// /// color is black /// - Black = 0, + Black = 0, /// /// color is red @@ -186,17 +186,17 @@ public enum AnsiColor : int /// /// color is green /// - Green = 2, + Green = 2, /// /// color is yellow /// - Yellow = 3, + Yellow = 3, /// /// color is blue /// - Blue = 4, + Blue = 4, /// /// color is magenta @@ -206,12 +206,12 @@ public enum AnsiColor : int /// /// color is cyan /// - Cyan = 6, + Cyan = 6, /// /// color is white /// - White = 7, + White = 7, } /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs index b140bdeede3..030f4b925c3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs @@ -627,7 +627,7 @@ void IList.RemoveAt(int pos) IEnumerator IEnumerable.GetEnumerator() { - return (IEnumerator) this.GetEnumerator(); + return (IEnumerator)this.GetEnumerator(); } /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs index 7b3d7962ea3..1dde3bb4374 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs @@ -759,10 +759,10 @@ protected virtual bool RequiresLayout /// This implementation doesn't flush anything and always returns true. /// /// True if all logging events were flushed successfully, else false. - public virtual bool Flush(int millisecondsTimeout) - { - return true; - } + public virtual bool Flush(int millisecondsTimeout) + { + return true; + } /// /// The layout of this appender. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs index d95ca3a8490..8718d701349 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs @@ -412,8 +412,8 @@ protected override void Append(log4net.Core.LoggingEvent loggingEvent) protected override bool RequiresLayout { get { return true; } - } - + } + /// /// Initialize the options for this appender. /// @@ -425,7 +425,7 @@ protected override bool RequiresLayout #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)] + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] public override void ActivateOptions() { base.ActivateOptions(); @@ -504,32 +504,32 @@ public override void ActivateOptions() /// private System.IO.StreamWriter m_consoleOutputWriter = null; - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern int GetConsoleOutputCP(); - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern bool SetConsoleTextAttribute( IntPtr consoleHandle, ushort attributes); - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern bool GetConsoleScreenBufferInfo( IntPtr consoleHandle, - out CONSOLE_SCREEN_BUFFER_INFO bufferInfo); - -// [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] -// private static extern bool WriteConsoleW( -// IntPtr hConsoleHandle, -// [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, -// UInt32 bufferLen, -// out UInt32 written, -// IntPtr reserved); - - // private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); + out CONSOLE_SCREEN_BUFFER_INFO bufferInfo); + + // [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] + // private static extern bool WriteConsoleW( + // IntPtr hConsoleHandle, + // [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, + // UInt32 bufferLen, + // out UInt32 written, + // IntPtr reserved); + + // private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); private const uint STD_OUTPUT_HANDLE = unchecked((uint)(-11)); private const uint STD_ERROR_HANDLE = unchecked((uint)(-12)); - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern IntPtr GetStdHandle( uint type); diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs index a10a0d6eb20..6057b28034c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs @@ -103,19 +103,19 @@ public bool ImmediateFlush /// /// The maximum time to wait for logging events to be flushed. /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) - { - // Nothing to do if ImmediateFlush is true - if (this.m_immediateFlush) + public override bool Flush(int millisecondsTimeout) + { + // Nothing to do if ImmediateFlush is true + if (this.m_immediateFlush) { return true; } // System.Diagnostics.Debug is thread-safe, so no need for lock(this). - System.Diagnostics.Debug.Flush(); - - return true; - } + System.Diagnostics.Debug.Flush(); + + return true; + } #endif /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs index c130cb1c054..e217d769526 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs @@ -98,7 +98,7 @@ public class EventLogAppender : AppenderSkeleton /// public EventLogAppender() { - this.m_applicationName = System.Threading.Thread.GetDomain().FriendlyName; + this.m_applicationName = System.Threading.Thread.GetDomain().FriendlyName; this.m_logName = "Application"; // Defaults to application log this.m_machineName = "."; // Only log on the local machine } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs index 03aaae81953..373a9e4bb57 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs @@ -33,7 +33,7 @@ namespace log4net.Appender using log4net.Core; using log4net.Layout; - using log4net.Util; + using log4net.Util; #if !NETCF /// @@ -732,8 +732,8 @@ public class InterProcessLock : LockingModelBase { private Mutex m_mutex = null; private Stream m_stream = null; - private int m_recursiveWatch = 0; - + private int m_recursiveWatch = 0; + /// /// Open the file specified and prepare for logging. /// @@ -1011,8 +1011,8 @@ public SecurityContext SecurityContext { get { return this.m_securityContext; } set { this.m_securityContext = value; } - } - + } + #if NETCF /// /// Gets or sets the used to handle locking of the file. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs index 30df143fbd4..ca2e165de88 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs @@ -376,8 +376,8 @@ protected override void Append(LoggingEvent loggingEvent) // Call the local libc syslog method // The second argument is a printf style format string syslog(priority, "%s", message); - } - + } + /// /// Close the syslog when the appender is closed. /// @@ -523,7 +523,7 @@ private static int GeneratePriority(SyslogFacility facility, SyslogSeverity seve /// string to "%s". /// /// - [DllImport("libc", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] + [DllImport("libc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] private static extern void syslog(int priority, string format, string message); /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs index eca5fa65175..bcb00acef4b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs @@ -389,7 +389,7 @@ protected override bool RequiresLayout /// If the function succeeds, the return value is zero. /// /// - [DllImport("netapi32.dll", SetLastError=true)] + [DllImport("netapi32.dll", SetLastError = true)] protected static extern int NetMessageBufferSend( [MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string msgName, diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs index f99dca5322e..20ba3e6e683 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs @@ -166,7 +166,7 @@ public enum RollingMode /// /// Roll files based on both the size and date of the file /// - Composite = 3, + Composite = 3, } /// @@ -182,7 +182,7 @@ protected enum RollPoint /// /// Roll the log not based on the date /// - InvalidRollPoint = -1, + InvalidRollPoint = -1, /// /// Roll the log for each minute @@ -831,7 +831,7 @@ private void RollOverIfDateBoundaryCrossing() LogLog.Debug(declaringType, "[" + last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo) + "] vs. [" + this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo) + "]"); - if (! last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo).Equals(this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo))) + if (!last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo).Equals(this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo))) { this.m_scheduledFilename = this.CombinePath(this.m_baseFileName, last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); LogLog.Debug(declaringType, "Initial roll over to [" + this.m_scheduledFilename + "]"); diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs index 5619512b9e3..724d7d4c3c5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs @@ -627,20 +627,20 @@ public enum SmtpAuthentication Ntlm, } - private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' }; - - /// - /// trims leading and trailing commas or semicolons. - /// + private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' }; + + /// + /// trims leading and trailing commas or semicolons. + /// private static string MaybeTrimSeparators(string s) - { + { #if NET_2_0 || MONO_2_0 - return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS); + return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS); #else return s != null && s.Length > 0 ? s : s.Trim(ADDRESS_DELIMITERS); #endif - } - } + } + } } #endif // !NETCF && !SSCLI diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs index 534578f2a01..d3618911844 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs @@ -469,21 +469,21 @@ protected QuietTextWriter QuietWriter /// /// The maximum time to wait for logging events to be flushed. /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) - { - // Nothing to do if ImmediateFlush is true - if (this.m_immediateFlush) + public override bool Flush(int millisecondsTimeout) + { + // Nothing to do if ImmediateFlush is true + if (this.m_immediateFlush) { return true; } // lock(this) will block any Appends while the buffer is flushed. - lock (this) - { - this.m_qtw.Flush(); - } - - return true; - } + lock (this) + { + this.m_qtw.Flush(); + } + + return true; + } } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs index 913a89ac458..313f9a09ea8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs @@ -512,8 +512,8 @@ protected virtual void InitializeClientConnection() /// The instance that will be used for sending the /// logging events. /// - private UdpClient m_client; - + private UdpClient m_client; + /// /// The encoding to use for the packet. /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs index e64006de0a5..452262e289b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs @@ -48,7 +48,7 @@ namespace log4net.Config /// /// Nicko Cadell. /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)] + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Serializable] [Obsolete("Use AliasRepositoryAttribute instead of AliasDomainAttribute. Scheduled removal in v10.0.0.")] public sealed class AliasDomainAttribute : AliasRepositoryAttribute diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs index 1882bc0ceb9..1ae747522ad 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs @@ -45,7 +45,7 @@ namespace log4net.Config /// /// Nicko Cadell. /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)] + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Serializable] public /*sealed*/ class AliasRepositoryAttribute : Attribute { diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs index 4a445f9a90f..4619efa162d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs @@ -45,7 +45,7 @@ namespace log4net.Config /// /// Nicko Cadell. /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)] + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [Serializable] public sealed class PluginAttribute : Attribute, IPluginFactory { @@ -143,7 +143,7 @@ public IPlugin CreatePlugin() #endif // Check that the type is a plugin - if (! typeof(IPlugin).IsAssignableFrom(pluginType)) + if (!typeof(IPlugin).IsAssignableFrom(pluginType)) { throw new LogException("Plugin type [" + pluginType.FullName + "] does not implement the log4net.IPlugin interface"); } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs index e0f9e58edde..5c9dc3015ce 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs @@ -959,8 +959,8 @@ private sealed class ConfigureAndWatchHandler : IDisposable /// Watches file for changes. This object should be disposed when no longer /// needed to free system handles on the watched resources. /// - private FileSystemWatcher m_watcher; - + private FileSystemWatcher m_watcher; + /// /// Initializes a new instance of the class to /// watch a specified config file used to configure a repository. @@ -1047,8 +1047,8 @@ private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs private void OnWatchedFileChange(object state) { XmlConfigurator.InternalConfigure(this.m_repository, this.m_configFile); - } - + } + /// /// Release the handles held by the watcher and timer. /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs index 9732bdb6f86..38080144f88 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs @@ -76,7 +76,7 @@ public CompactRepositorySelector(Type defaultRepositoryType) } // Check that the type is a repository - if (! typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) + if (!typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", (object)defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs index ce19e7f934e..be3f8d6bcfe 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs @@ -96,7 +96,7 @@ public DefaultRepositorySelector(Type defaultRepositoryType) } // Check that the type is a repository - if (! typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) + if (!typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); } @@ -512,9 +512,9 @@ public void AliasRepository(string repositoryAlias, ILoggerRepository repository // Cannot redefine existing alias throw new InvalidOperationException("Repository [" + repositoryAlias + "] is already aliased to repository [" + ((ILoggerRepository)this.m_alias2repositoryMap[repositoryAlias]).Name + "]. Aliases cannot be redefined."); } - } + } - // Check if the alias is already mapped to a repository + // Check if the alias is already mapped to a repository else if (this.m_name2repositoryMap.Contains(repositoryAlias)) { // Check if this is a duplicate of the current mapping @@ -751,34 +751,34 @@ private void ConfigureRepository(Assembly assembly, ILoggerRepository repository } } else - { - // As we are not going to watch the config file it is easiest to just resolve it as a - // URI and pass that to the Configurator - Uri repositoryConfigUri = null; - try - { - repositoryConfigUri = new Uri(repositoryConfigFilePath); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex); - } - - if (repositoryConfigUri != null) - { - LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]"); - - try - { - // TODO: Support other types of configurator - XmlConfigurator.Configure(repository, repositoryConfigUri); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex); + { + // As we are not going to watch the config file it is easiest to just resolve it as a + // URI and pass that to the Configurator + Uri repositoryConfigUri = null; + try + { + repositoryConfigUri = new Uri(repositoryConfigFilePath); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex); + } + + if (repositoryConfigUri != null) + { + LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]"); + + try + { + // TODO: Support other types of configurator + XmlConfigurator.Configure(repository, repositoryConfigUri); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex); + } } } - } } } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs index 7bad6d43561..f9c87deb74f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs @@ -21,7 +21,7 @@ namespace log4net.Core // limitations under the License. // using System; - using System.Collections; + using System.Collections; /// /// Defines the default set of levels recognized by the system. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs index 0da4132a398..d60a3478db0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs @@ -601,7 +601,7 @@ void IList.RemoveAt(int pos) IEnumerator IEnumerable.GetEnumerator() { - return (IEnumerator) this.GetEnumerator(); + return (IEnumerator)this.GetEnumerator(); } /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs index 61e0c41976c..a8dcbd54241 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs @@ -24,7 +24,7 @@ namespace log4net.Core using System.Collections; using System.Diagnostics; - using log4net.Util; + using log4net.Util; /// /// The internal representation of caller location information. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs index 0b6856607e8..9434a383bf1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs @@ -25,7 +25,7 @@ namespace log4net.Core // See the License for the specific language governing permissions and // limitations under the License. // - using System; + using System; /// /// Exception base type for log4net. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs index 65bc0ca9333..aefb3364c95 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs @@ -99,8 +99,8 @@ public struct LoggingEventData /// /// [Obsolete("Prefer using TimeStampUtc, since local time can be ambiguous in time zones with daylight savings time.. Scheduled removal in v11.0.0.")] - public DateTime TimeStamp; - + public DateTime TimeStamp; + /// /// Gets or sets the UTC time the event was logged. /// @@ -299,8 +299,8 @@ public enum FixFlags /// /// Partial = Message | ThreadName | Exception | Domain | Properties, - } - + } + /// /// The internal representation of logging events. /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs index ef3648db6f8..d258747cb83 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs @@ -24,7 +24,7 @@ namespace log4net.Core using System.Collections; using System.Text; - using log4net.Util; + using log4net.Util; /// /// provides method information without actually referencing a System.Reflection.MethodBase diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs index ed8b256b5f2..f65ea592b69 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs @@ -98,77 +98,77 @@ protected virtual void FormatDateWithoutMillis(DateTime dateToFormat, StringBuil /// /// public virtual void FormatDate(DateTime dateToFormat, TextWriter writer) - { - lock (s_lastTimeStrings) - { - // Calculate the current time precise only to the second - long currentTimeToTheSecond = dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond); - - string timeString = null; - - // Compare this time with the stored last time - // If we are in the same second then append - // the previously calculated time string - if (s_lastTimeToTheSecond != currentTimeToTheSecond) - { - s_lastTimeStrings.Clear(); - } - else - { - timeString = (string)s_lastTimeStrings[this.GetType()]; - } - - if (timeString == null) - { - // lock so that only one thread can use the buffer and - // update the s_lastTimeToTheSecond and s_lastTimeStrings - - // PERF: Try removing this lock and using a new StringBuilder each time - lock (s_lastTimeBuf) - { - timeString = (string)s_lastTimeStrings[this.GetType()]; - - if (timeString == null) - { - // We are in a new second. - s_lastTimeBuf.Length = 0; - - // Calculate the new string for this second - this.FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf); - - // Render the string buffer to a string - timeString = s_lastTimeBuf.ToString(); - + { + lock (s_lastTimeStrings) + { + // Calculate the current time precise only to the second + long currentTimeToTheSecond = dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond); + + string timeString = null; + + // Compare this time with the stored last time + // If we are in the same second then append + // the previously calculated time string + if (s_lastTimeToTheSecond != currentTimeToTheSecond) + { + s_lastTimeStrings.Clear(); + } + else + { + timeString = (string)s_lastTimeStrings[this.GetType()]; + } + + if (timeString == null) + { + // lock so that only one thread can use the buffer and + // update the s_lastTimeToTheSecond and s_lastTimeStrings + + // PERF: Try removing this lock and using a new StringBuilder each time + lock (s_lastTimeBuf) + { + timeString = (string)s_lastTimeStrings[this.GetType()]; + + if (timeString == null) + { + // We are in a new second. + s_lastTimeBuf.Length = 0; + + // Calculate the new string for this second + this.FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf); + + // Render the string buffer to a string + timeString = s_lastTimeBuf.ToString(); + #if NET_1_1 // Ensure that the above string is written into the variable NOW on all threads. // This is only required on multiprocessor machines with weak memeory models System.Threading.Thread.MemoryBarrier(); #endif - // Store the time as a string (we only have to do this once per second) - s_lastTimeStrings[this.GetType()] = timeString; - s_lastTimeToTheSecond = currentTimeToTheSecond; - } - } - } + // Store the time as a string (we only have to do this once per second) + s_lastTimeStrings[this.GetType()] = timeString; + s_lastTimeToTheSecond = currentTimeToTheSecond; + } + } + } - writer.Write(timeString); - - // Append the current millisecond info - writer.Write(','); - int millis = dateToFormat.Millisecond; - if (millis < 100) - { - writer.Write('0'); - } + writer.Write(timeString); - if (millis < 10) - { - writer.Write('0'); - } + // Append the current millisecond info + writer.Write(','); + int millis = dateToFormat.Millisecond; + if (millis < 100) + { + writer.Write('0'); + } + + if (millis < 10) + { + writer.Write('0'); + } - writer.Write(millis); - } + writer.Write(millis); + } } /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs index ee4f3d696a6..47e9e445d1b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs @@ -59,15 +59,15 @@ protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, Ht { HttpRequest request = null; try - { - request = httpContext.Request; + { + request = httpContext.Request; } catch (HttpException) - { - // likely a case of running in IIS integrated mode - // when inside an Application_Start event. - // treat it like a case of the Request - // property returning null + { + // likely a case of running in IIS integrated mode + // when inside an Application_Start event. + // treat it like a case of the Request + // property returning null } if (request != null) diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs index 33102f869b0..cbf7a1339dd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs @@ -125,9 +125,9 @@ protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) stackFrameIndex--; } - } - - /// + } + + /// /// Returns the Name of the method. /// /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs index 369358aa966..cec1ccf6230 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs @@ -11,12 +11,12 @@ using log4net.Util; using log4net.Util.PatternStringConverters; -using AppDomainPatternConverter=log4net.Layout.Pattern.AppDomainPatternConverter; -using DatePatternConverter=log4net.Layout.Pattern.DatePatternConverter; -using IdentityPatternConverter=log4net.Layout.Pattern.IdentityPatternConverter; -using PropertyPatternConverter=log4net.Layout.Pattern.PropertyPatternConverter; -using UserNamePatternConverter=log4net.Layout.Pattern.UserNamePatternConverter; -using UtcDatePatternConverter=log4net.Layout.Pattern.UtcDatePatternConverter; +using AppDomainPatternConverter = log4net.Layout.Pattern.AppDomainPatternConverter; +using DatePatternConverter = log4net.Layout.Pattern.DatePatternConverter; +using IdentityPatternConverter = log4net.Layout.Pattern.IdentityPatternConverter; +using PropertyPatternConverter = log4net.Layout.Pattern.PropertyPatternConverter; +using UserNamePatternConverter = log4net.Layout.Pattern.UserNamePatternConverter; +using UtcDatePatternConverter = log4net.Layout.Pattern.UtcDatePatternConverter; namespace log4net.Layout { @@ -850,10 +850,10 @@ static PatternLayout() s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); - s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter)); - -// .NET Compact Framework 1.0 has no support for ASP.NET -// SSCLI 1.0 has no support for ASP.NET + s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter)); + + // .NET Compact Framework 1.0 has no support for ASP.NET + // SSCLI 1.0 has no support for ASP.NET #if !NETCF && !SSCLI && !CLIENT_PROFILE && !NETSTANDARD1_3 s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter)); s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter)); @@ -994,7 +994,7 @@ public PatternLayout(string pattern) /// public string ConversionPattern { - get { return this.m_pattern; } + get { return this.m_pattern; } set { this.m_pattern = value; } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs b/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs index 4b6974ed62f..24e04f7697f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs @@ -741,29 +741,29 @@ public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Ty public static ILoggerRepository[] GetAllRepositories() { return LoggerManager.GetAllRepositories(); - } - - /// - /// Flushes logging events buffered in all configured appenders in the default repository. - /// - /// The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed. - /// True if all logging events were flushed successfully, else false. - public static bool Flush(int millisecondsTimeout) - { + } + + /// + /// Flushes logging events buffered in all configured appenders in the default repository. + /// + /// The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed. + /// True if all logging events were flushed successfully, else false. + public static bool Flush(int millisecondsTimeout) + { #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - Appender.IFlushable flushableRepository = LoggerManager.GetRepository(Assembly.GetCallingAssembly()) as Appender.IFlushable; - if (flushableRepository == null) - { - return false; - } - else - { - return flushableRepository.Flush(millisecondsTimeout); - } + Appender.IFlushable flushableRepository = LoggerManager.GetRepository(Assembly.GetCallingAssembly()) as Appender.IFlushable; + if (flushableRepository == null) + { + return false; + } + else + { + return flushableRepository.Flush(millisecondsTimeout); + } #else return false; #endif - } + } /// /// Looks up the wrapper object for the logger specified. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs index 4f6ff8289cf..2b55fd75742 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs @@ -613,7 +613,7 @@ void IList.RemoveAt(int pos) IEnumerator IEnumerable.GetEnumerator() { - return (IEnumerator) this.GetEnumerator(); + return (IEnumerator)this.GetEnumerator(); } /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs index 9e8009cf96f..ce75e250439 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs @@ -134,8 +134,8 @@ public override void Attach(ILoggerRepository repository) { LogLog.Error(declaringType, "Failed to Marshal remoting sink", ex); } - } - + } + /// /// Is called when the plugin is to shutdown. /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs index 8916970bbc9..45456f8f4de 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs @@ -637,8 +637,8 @@ protected void SetParameter(XmlElement element, object target) // Expand environment variables in the string. IDictionary environmentVariables = Environment.GetEnvironmentVariables(); if (this.HasCaseInsensitiveEnvironment) - { - environmentVariables = this.CreateCaseInsensitiveWrapper(environmentVariables); + { + environmentVariables = this.CreateCaseInsensitiveWrapper(environmentVariables); } propertyValue = OptionConverter.SubstituteVariables(propertyValue, environmentVariables); @@ -1062,10 +1062,10 @@ protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, } #if !(NETCF || NETSTANDARD1_3) // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6 - private bool HasCaseInsensitiveEnvironment - { + private bool HasCaseInsensitiveEnvironment + { get - { + { #if NET_1_0 || NET_1_1 || CLI_1_0 // actually there is no guarantee, but we don't know better return true; @@ -1073,23 +1073,23 @@ private bool HasCaseInsensitiveEnvironment // see above return false; #else - PlatformID platform = Environment.OSVersion.Platform; - return platform != PlatformID.Unix && platform != PlatformID.MacOSX; + PlatformID platform = Environment.OSVersion.Platform; + return platform != PlatformID.Unix && platform != PlatformID.MacOSX; #endif } } - private IDictionary CreateCaseInsensitiveWrapper(IDictionary dict) - { + private IDictionary CreateCaseInsensitiveWrapper(IDictionary dict) + { if (dict == null) - { - return dict; + { + return dict; } Hashtable hash = SystemInfo.CreateCaseInsensitiveHashtable(); foreach (DictionaryEntry entry in dict) - { - hash[entry.Key] = entry.Value; + { + hash[entry.Key] = entry.Value; } return hash; @@ -1121,7 +1121,7 @@ private IDictionary CreateCaseInsensitiveWrapper(IDictionary dict) private const string CONFIG_DEBUG_ATTR = "configDebug"; private const string INTERNAL_DEBUG_ATTR = "debug"; private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug"; - private const string CONFIG_UPDATE_MODE_ATTR = "update"; + private const string CONFIG_UPDATE_MODE_ATTR = "update"; private const string RENDERING_TYPE_ATTR = "renderingClass"; private const string RENDERED_TYPE_ATTR = "renderedClass"; diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs index 3caea607189..46ce13f4fe9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs @@ -21,7 +21,7 @@ namespace log4net.Util // limitations under the License. // using System; - using System.Collections; + using System.Collections; /// /// An always empty . diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs index 32c003d614c..50b34bf626d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs @@ -21,7 +21,7 @@ namespace log4net.Util // limitations under the License. // using System; - using System.Collections; + using System.Collections; /// /// An always empty . diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs index 81ceafa3bab..934659e380a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs @@ -588,7 +588,7 @@ private static void EmitErrorLine(string message) private const string PREFIX = "log4net: "; private const string ERR_PREFIX = "log4net:ERROR "; - private const string WARN_PREFIX = "log4net:WARN "; + private const string WARN_PREFIX = "log4net:WARN "; /// /// Subscribes to the LogLog.LogReceived event and stores messages diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs index 899f5767089..6d873d142a2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs @@ -211,8 +211,8 @@ private static PropertiesDictionary GetCallContextData() #else return CallContext.GetData(c_SlotName) as PropertiesDictionary; #endif - } - + } + /// /// Sets the call context data. /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs index af52896772c..2c9870c8388 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs @@ -25,17 +25,17 @@ using log4net.Core; namespace log4net.Util -{ - /// +{ + /// /// Delegate type used for LogicalThreadContextStack's callbacks. /// - #if NET_2_0 || MONO_2_0 - public delegate void TwoArgAction(T1 t1, T2 t2); - #else +#if NET_2_0 || MONO_2_0 + public delegate void TwoArgAction(T1 t1, T2 t2); +#else public delegate void TwoArgAction(string t1, LogicalThreadContextStack t2); - #endif - - /// +#endif + + /// /// Implementation of Stack for the . /// /// @@ -55,13 +55,13 @@ public sealed class LogicalThreadContextStack : IFixingRequired /// The name of this within the /// . /// - private string m_propertyKey; - + private string m_propertyKey; + /// /// The callback used to let the register a /// new instance of a . /// - #if NET_2_0 || MONO_2_0 +#if NET_2_0 || MONO_2_0 private TwoArgAction m_registerNew; #else private TwoArgAction m_registerNew; @@ -77,10 +77,10 @@ public sealed class LogicalThreadContextStack : IFixingRequired /// /// #if NET_2_0 || MONO_2_0 - internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) - #else + internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) +#else internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) - #endif +#endif { this.m_propertyKey = propertyKey; this.m_registerNew = registerNew; @@ -142,7 +142,7 @@ public string Pop() string result = string.Empty; if (stack.Count > 0) { - result = ((StackFrame) stack.Pop()).Message; + result = ((StackFrame)stack.Pop()).Message; } LogicalThreadContextStack ltcs = new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew); @@ -195,7 +195,7 @@ internal string GetFullMessage() Stack stack = this.m_stack; if (stack.Count > 0) { - return ((StackFrame) stack.Peek()).FullMessage; + return ((StackFrame)stack.Peek()).FullMessage; } return null; diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs index 2eef721a4bd..2e4c6e1ae57 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs @@ -135,8 +135,8 @@ public static NativeError GetLastError() public static NativeError GetError(int number) { return new NativeError(number, NativeError.GetErrorMessage(number)); - } - + } + /// /// Retrieves the message corresponding with a Win32 message identifier. /// @@ -248,7 +248,7 @@ public override string ToString() #if NETCF [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] #else - [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] #endif private static extern int FormatMessage( int dwFlags, diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs index bd6126af378..f3af76ea8d2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs @@ -154,37 +154,37 @@ public static bool ToBoolean(string argValue, bool defaultValue) } return defaultValue; - } - -// /// -// /// Converts a string to an integer. -// /// -// /// String to convert. -// /// The default value. -// /// The value of . -// /// -// /// -// /// is returned when -// /// cannot be converted to a value. -// /// -// /// -// public static int ToInt(string argValue, int defaultValue) -// { -// if (argValue != null) -// { -// string s = argValue.Trim(); -// try -// { -// return int.Parse(s, NumberFormatInfo.InvariantInfo); -// } -// catch (Exception e) -// { -// LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e); -// } -// } -// return defaultValue; -// } - + } + + // /// + // /// Converts a string to an integer. + // /// + // /// String to convert. + // /// The default value. + // /// The value of . + // /// + // /// + // /// is returned when + // /// cannot be converted to a value. + // /// + // /// + // public static int ToInt(string argValue, int defaultValue) + // { + // if (argValue != null) + // { + // string s = argValue.Trim(); + // try + // { + // return int.Parse(s, NumberFormatInfo.InvariantInfo); + // } + // catch (Exception e) + // { + // LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e); + // } + // } + // return defaultValue; + // } + /// /// Parses a file size into a number. /// @@ -319,23 +319,23 @@ public static object ConvertStringTo(Type target, string txt) } return null; - } - -// /// -// /// Looks up the for the target type. -// /// -// /// The type to lookup the converter for. -// /// The converter for the specified type. -// public static IConvertFrom GetTypeConverter(Type target) -// { -// IConvertFrom converter = ConverterRegistry.GetConverter(target); -// if (converter == null) -// { -// throw new InvalidOperationException("No type converter defined for [" + target + "]"); -// } -// return converter; -// } - + } + + // /// + // /// Looks up the for the target type. + // /// + // /// The type to lookup the converter for. + // /// The converter for the specified type. + // public static IConvertFrom GetTypeConverter(Type target) + // { + // IConvertFrom converter = ConverterRegistry.GetConverter(target); + // if (converter == null) + // { + // throw new InvalidOperationException("No type converter defined for [" + target + "]"); + // } + // return converter; + // } + /// /// Checks if there is an appropriate type conversion from the source type to the target type. /// @@ -425,40 +425,40 @@ public static object ConvertTypeTo(object sourceInstance, Type targetType) } throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance"); - } - -// /// -// /// Finds the value corresponding to in -// /// and then perform variable substitution -// /// on the found value. -// /// -// /// The key to lookup. -// /// The association to use for lookups. -// /// The substituted result. -// public static string FindAndSubst(string key, System.Collections.IDictionary props) -// { -// if (props == null) -// { -// throw new ArgumentNullException("props"); -// } -// -// string v = props[key] as string; -// if (v == null) -// { -// return null; -// } -// -// try -// { -// return SubstituteVariables(v, props); -// } -// catch(Exception e) -// { -// LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e); -// return v; -// } -// } - + } + + // /// + // /// Finds the value corresponding to in + // /// and then perform variable substitution + // /// on the found value. + // /// + // /// The key to lookup. + // /// The association to use for lookups. + // /// The substituted result. + // public static string FindAndSubst(string key, System.Collections.IDictionary props) + // { + // if (props == null) + // { + // throw new ArgumentNullException("props"); + // } + // + // string v = props[key] as string; + // if (v == null) + // { + // return null; + // } + // + // try + // { + // return SubstituteVariables(v, props); + // } + // catch(Exception e) + // { + // LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e); + // return v; + // } + // } + /// /// Instantiates an object given a class name. /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs index e907b958358..42cba7675f9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs @@ -362,7 +362,7 @@ public PatternString(string pattern) /// public string ConversionPattern { - get { return this.m_pattern; } + get { return this.m_pattern; } set { this.m_pattern = value; } } diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs index a438c9bda50..ff48fbb6cf2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs @@ -36,7 +36,7 @@ namespace log4net.Util.PatternStringConverters /// /// Nicko Cadell. internal sealed class ProcessIdPatternConverter : PatternConverter - { + { /// /// Write the current process ID to the output. /// diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs index 8c7d202a807..6d30e123196 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs @@ -27,7 +27,7 @@ namespace log4net.Util // limitations under the License. // using System; - using System.Collections; + using System.Collections; /// /// String keyed object map. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs index 2f27cbdb8bd..c09d93af17c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs @@ -28,7 +28,7 @@ namespace log4net.Util // using System; using System.Collections; - using System.Reflection; + using System.Reflection; /// /// String keyed object map that is read only. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs index 0e1855bc08e..510550a3028 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs @@ -80,17 +80,17 @@ public ReaderWriterLock() /// /// public void AcquireReaderLock() - { + { #if HAS_READERWRITERLOCK #if HAS_READERWRITERLOCKSLIM - // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 - try - { - } - finally - { - this.m_lock.EnterReadLock(); - } + // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 + try + { + } + finally + { + this.m_lock.EnterReadLock(); + } #else m_lock.AcquireReaderLock(-1); #endif @@ -131,17 +131,17 @@ public void ReleaseReaderLock() /// /// public void AcquireWriterLock() - { + { #if HAS_READERWRITERLOCK #if HAS_READERWRITERLOCKSLIM - // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 - try - { - } - finally - { - this.m_lock.EnterWriteLock(); - } + // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 + try + { + } + finally + { + this.m_lock.EnterWriteLock(); + } #else m_lock.AcquireWriterLock(-1); #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs index cda4bce8b25..1bd60bcb5e3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs @@ -743,21 +743,21 @@ public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, { // Found type in loaded assembly LogLog.Debug(declaringType, "Loaded type [" + typeName + "] from assembly [" + assembly.FullName + "] by searching loaded assemblies."); - if (assembly.GlobalAssemblyCache) - { - fallback = t; - } - else - { - return t; - } + if (assembly.GlobalAssemblyCache) + { + fallback = t; + } + else + { + return t; + } } } - if (fallback != null) - { - return fallback; - } + if (fallback != null) + { + return fallback; + } } // Didn't find the type diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs index 73f677f20cd..1909a792872 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs @@ -113,7 +113,7 @@ public string Pop() Stack stack = this.m_stack; if (stack.Count > 0) { - return ((StackFrame) stack.Pop()).Message; + return ((StackFrame)stack.Pop()).Message; } return string.Empty; @@ -159,7 +159,7 @@ internal string GetFullMessage() Stack stack = this.m_stack; if (stack.Count > 0) { - return ((StackFrame) stack.Peek()).FullMessage; + return ((StackFrame)stack.Peek()).FullMessage; } return null; diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs index 36ffcda18c1..acd93e41879 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs @@ -176,8 +176,8 @@ private static int CountSubstrings(string text, string substring) return count; } - private const string CDATA_END = "]]>"; - private const string CDATA_UNESCAPABLE_TOKEN = "]]"; + private const string CDATA_END = "]]>"; + private const string CDATA_UNESCAPABLE_TOKEN = "]]"; /// /// Characters illegal in XML 1.0. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs index 35b94b506dc..3e3ac3ba5bb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs @@ -25,7 +25,7 @@ namespace log4net.Util.TypeConverters // See the License for the specific language governing permissions and // limitations under the License. // - using System; + using System; /// /// Exception base type for conversion errors. diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs index 0223753c622..7d9a6a341d8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs @@ -259,8 +259,8 @@ public override IDisposable Impersonate(object state) } return null; - } - + } + /// /// Create a given the userName, domainName and password. /// @@ -322,13 +322,13 @@ private static WindowsIdentity LogonUser(string userName, string domainName, str return identity; } - [DllImport("advapi32.dll", SetLastError=true)] + [DllImport("advapi32.dll", SetLastError = true)] private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); - [DllImport("kernel32.dll", CharSet=CharSet.Auto)] + [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private static extern bool CloseHandle(IntPtr handle); - [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] + [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); /// diff --git a/DNN Platform/DotNetNuke.Log4net/packages.config b/DNN Platform/DotNetNuke.Log4net/packages.config deleted file mode 100644 index e619441b462..00000000000 --- a/DNN Platform/DotNetNuke.Log4net/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.ModulePipeline/ModuleControlPipeline.cs b/DNN Platform/DotNetNuke.ModulePipeline/ModuleControlPipeline.cs index 81672e8b644..47091f0cda1 100644 --- a/DNN Platform/DotNetNuke.ModulePipeline/ModuleControlPipeline.cs +++ b/DNN Platform/DotNetNuke.ModulePipeline/ModuleControlPipeline.cs @@ -1,58 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. - -/* Unmerged change from project 'DotNetNuke.ModulePipeline (net472)' -Before: -// See the LICENSE file in the project root for more information - -using -After: -// See the LICENSE file in the project root for more information - - -#if NET472 -using -*/ -// See the LICENSE file in the project root for more information - -#if NET472 -using System.Web.UI; - -#endif - +// See the LICENSE file in the project root for more information namespace DotNetNuke.ModulePipeline { using System; - using System.Collections.Generic; - using System.IO; - - using -/* Unmerged change from project 'DotNetNuke.ModulePipeline(net472)' -Before: -using System.IO; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules.Html5; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Razor; -using System.Collections.Generic; -using DotNetNuke.Web.Mvc; -After: -using System.Collections.Generic; -using System.IO; + using System.Collections.Generic; + using System.IO; +#if NET472 + using System.Web.UI; +#endif -using DotNetNuke.Entities.Modules; -using DotNetNuke.Instrumentation; -using DotNetNuke.Services.Localization; -using DotNetNuke.UI.Modules; -using DotNetNuke.Web.Modules.Html5; -using DotNetNuke.Web.Mvc; -using DotNetNuke.Web.Razor; -*/ -DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules; using DotNetNuke.Instrumentation; - using DotNetNuke.Services.Localization; using DotNetNuke.UI.Modules; using DotNetNuke.UI.Modules.Html5; using DotNetNuke.Web.Mvc; @@ -62,15 +21,15 @@ namespace DotNetNuke.ModulePipeline /// The Module Pipeline that determines which Module pattern /// to invoke based on the input module type. /// - public class ModuleControlPipeline - - // MULTI-TARGETTING PIPELINE - // ------------------------- - // This file multi-targets .NET Framework and .NET Standard, - // which is needed as DNN migrates to .NET Core. The 'NET472' - // pre-processor directives are to fully support Legacy DNN. - // As the Pipeline is upgraded to be more complaint with - // .NET Standard 2.0 use the apprioprate pre-processor directives. + public class ModuleControlPipeline + + // MULTI-TARGETTING PIPELINE + // ------------------------- + // This file multi-targets .NET Framework and .NET Standard, + // which is needed as DNN migrates to .NET Core. The 'NET472' + // pre-processor directives are to fully support Legacy DNN. + // As the Pipeline is upgraded to be more complaint with + // .NET Standard 2.0 use the appropriate pre-processor directives. #if NET472 : IModuleControlPipeline #endif @@ -96,14 +55,7 @@ public ModuleControlPipeline( } #if NET472 - private IModuleControlFactory GetModuleControlFactory(string controlSrc) - { - string extension = Path.GetExtension(controlSrc); - this._controlFactories.TryGetValue(extension, out IModuleControlFactory factory); - - return factory ?? this._controlFactories["default"]; - } - + /// public Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlKey, string controlSrc) { if (TraceLogger.IsDebugEnabled) @@ -141,13 +93,14 @@ public Control LoadModuleControl(TemplateControl containerControl, ModuleInfo mo return control; } + /// public Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) { - if (TraceLogger.IsDebugEnabled) - { - TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - + if (TraceLogger.IsDebugEnabled) + { + TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; IModuleControlFactory controlFactory = this.GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); @@ -170,14 +123,15 @@ public Control LoadModuleControl(TemplateControl containerControl, ModuleInfo mo } } - if (TraceLogger.IsDebugEnabled) - { - TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - + if (TraceLogger.IsDebugEnabled) + { + TraceLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } + /// public Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) { if (TraceLogger.IsDebugEnabled) @@ -219,6 +173,7 @@ public Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo return control; } + /// public Control CreateCachedControl(string cachedContent, ModuleInfo moduleConfiguration) { var moduleControl = new CachedModuleControl(cachedContent); @@ -226,11 +181,20 @@ public Control CreateCachedControl(string cachedContent, ModuleInfo moduleConfig return moduleControl; } + /// public Control CreateModuleControl(ModuleInfo moduleConfiguration) { IModuleControlFactory factory = this.GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); return factory.CreateModuleControl(moduleConfiguration); } + + private IModuleControlFactory GetModuleControlFactory(string controlSrc) + { + string extension = Path.GetExtension(controlSrc); + this._controlFactories.TryGetValue(extension, out IModuleControlFactory factory); + + return factory ?? this._controlFactories["default"]; + } #endif } } diff --git a/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs b/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs index 0ad0795f3bc..5e320bec516 100644 --- a/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs +++ b/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs @@ -27,58 +27,13 @@ namespace DotNetNuke.Web.Client.ClientResourceManagement /// public class ClientResourceManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ClientResourceManager)); internal const string DefaultCssProvider = "DnnPageHeaderProvider"; internal const string DefaultJsProvider = "DnnBodyProvider"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ClientResourceManager)); private static Dictionary _fileExistsCache = new Dictionary(); private static ReaderWriterLockSlim _lockFileExistsCache = new ReaderWriterLockSlim(); - private static bool FileExists(Page page, string filePath) - { - // remove query string for the file exists check, won't impact the absoluteness, so just do it either way. - filePath = RemoveQueryString(filePath); - var cacheKey = filePath.ToLowerInvariant(); - - // cache css file paths - if (!_fileExistsCache.ContainsKey(cacheKey)) - { - // appply lock after IF, locking is more expensive than worst case scenario (check disk twice) - _lockFileExistsCache.EnterWriteLock(); - try - { - _fileExistsCache[cacheKey] = IsAbsoluteUrl(filePath) || File.Exists(page.Server.MapPath(filePath)); - } - finally - { - _lockFileExistsCache.ExitWriteLock(); - } - } - - // return if file exists from cache - _lockFileExistsCache.EnterReadLock(); - try - { - return _fileExistsCache[cacheKey]; - } - finally - { - _lockFileExistsCache.ExitReadLock(); - } - } - - private static bool IsAbsoluteUrl(string url) - { - Uri result; - return Uri.TryCreate(url, UriKind.Absolute, out result); - } - - private static string RemoveQueryString(string filePath) - { - var queryStringPosition = filePath.IndexOf("?", StringComparison.Ordinal); - return queryStringPosition != -1 ? filePath.Substring(0, queryStringPosition) : filePath; - } - /// /// Adds the neccessary configuration to website root web.config to use the Client Depenedecny componenet. /// @@ -209,6 +164,51 @@ public static bool IsInstalled() return installed; } + + private static bool FileExists(Page page, string filePath) + { + // remove query string for the file exists check, won't impact the absoluteness, so just do it either way. + filePath = RemoveQueryString(filePath); + var cacheKey = filePath.ToLowerInvariant(); + + // cache css file paths + if (!_fileExistsCache.ContainsKey(cacheKey)) + { + // appply lock after IF, locking is more expensive than worst case scenario (check disk twice) + _lockFileExistsCache.EnterWriteLock(); + try + { + _fileExistsCache[cacheKey] = IsAbsoluteUrl(filePath) || File.Exists(page.Server.MapPath(filePath)); + } + finally + { + _lockFileExistsCache.ExitWriteLock(); + } + } + + // return if file exists from cache + _lockFileExistsCache.EnterReadLock(); + try + { + return _fileExistsCache[cacheKey]; + } + finally + { + _lockFileExistsCache.ExitReadLock(); + } + } + + private static bool IsAbsoluteUrl(string url) + { + Uri result; + return Uri.TryCreate(url, UriKind.Absolute, out result); + } + + private static string RemoveQueryString(string filePath) + { + var queryStringPosition = filePath.IndexOf("?", StringComparison.Ordinal); + return queryStringPosition != -1 ? filePath.Substring(0, queryStringPosition) : filePath; + } public static void RegisterAdminStylesheet(Page page, string filePath) { diff --git a/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs b/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs index 41f526941c0..23a4d344f1d 100644 --- a/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs +++ b/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs @@ -28,6 +28,9 @@ public class ClientResourceSettings private static readonly Type _hostControllerType; private static readonly Type _commonGlobalsType; + private bool _statusChecked; + private UpgradeStatus _status; + static ClientResourceSettings() { try @@ -44,6 +47,35 @@ static ClientResourceSettings() } } + private enum UpgradeStatus + { + /// + /// The application need update to a higher version. + /// + Upgrade, + + /// + /// The application need to install itself. + /// + Install, + + /// + /// The application is normal running. + /// + None, + + /// + /// The application occur error when running. + /// + Error, + + /// + /// 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, + } + /// /// /// @@ -96,6 +128,33 @@ public bool IsOverridingDefaultSettingsEnabled() return this.IsBooleanSettingEnabled(MinifyJsKey); } + private static bool? GetBooleanSetting(string dictionaryKey, string settingKey) + { + var setting = GetSetting(dictionaryKey, settingKey); + bool result; + if (setting != null && bool.TryParse(setting, out result)) + { + return result; + } + + return null; + } + + private static int? GetIntegerSetting(string dictionaryKey, string settingKey) + { + var setting = GetSetting(dictionaryKey, settingKey); + int version; + if (setting != null && int.TryParse(setting, out version)) + { + if (version > -1) + { + return version; + } + } + + return null; + } + private bool? IsBooleanSettingEnabled(string settingKey) { if (this.Status != UpgradeStatus.None) @@ -124,33 +183,6 @@ public bool IsOverridingDefaultSettingsEnabled() return null; } - private static bool? GetBooleanSetting(string dictionaryKey, string settingKey) - { - var setting = GetSetting(dictionaryKey, settingKey); - bool result; - if (setting != null && bool.TryParse(setting, out result)) - { - return result; - } - - return null; - } - - private static int? GetIntegerSetting(string dictionaryKey, string settingKey) - { - var setting = GetSetting(dictionaryKey, settingKey); - int version; - if (setting != null && int.TryParse(setting, out version)) - { - if (version > -1) - { - return version; - } - } - - return null; - } - private static string GetSetting(string dictionaryKey, string settingKey) { bool isHttpContext = HttpContext.Current != null && HttpContext.Current.Items.Contains(dictionaryKey); @@ -242,9 +274,6 @@ private static string GetHostSettingThroughReflection(string settingKey) return null; } - private bool _statusChecked; - private UpgradeStatus _status; - private UpgradeStatus Status { get @@ -272,34 +301,5 @@ private UpgradeStatus GetStatusByReflection() return UpgradeStatus.Unknown; } } - - private enum UpgradeStatus - { - /// - /// The application need update to a higher version. - /// - Upgrade, - - /// - /// The application need to install itself. - /// - Install, - - /// - /// The application is normal running. - /// - None, - - /// - /// The application occur error when running. - /// - Error, - - /// - /// 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, - } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/FileOrder.cs b/DNN Platform/DotNetNuke.Web.Client/FileOrder.cs index 4d15e6af4ba..68ad8446e78 100644 --- a/DNN Platform/DotNetNuke.Web.Client/FileOrder.cs +++ b/DNN Platform/DotNetNuke.Web.Client/FileOrder.cs @@ -39,10 +39,10 @@ public enum Js /// jQuery UI (CDN or local file) has the priority of 10 /// // ReSharper disable InconsistentNaming - jQueryUI = 10, + jQueryUI = 10, + + // ReSharper restore InconsistentNaming -// ReSharper restore InconsistentNaming - /// /// /js/dnn.xml.js has the priority of 15 /// diff --git a/DNN Platform/DotNetNuke.Web.Client/Providers/DnnCompositeFileProcessingProvider.cs b/DNN Platform/DotNetNuke.Web.Client/Providers/DnnCompositeFileProcessingProvider.cs index fdcd0b1c049..505d1fe4b2f 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Providers/DnnCompositeFileProcessingProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Providers/DnnCompositeFileProcessingProvider.cs @@ -18,6 +18,24 @@ public class DnnCompositeFileProcessingProvider : CompositeFileProcessingProvide { private readonly ClientResourceSettings clientResourceSettings = new ClientResourceSettings(); + private bool MinifyCss + { + get + { + var enableCssMinification = this.clientResourceSettings.EnableCssMinification(); + return enableCssMinification.HasValue ? enableCssMinification.Value : this.EnableCssMinify; + } + } + + private bool MinifyJs + { + get + { + var enableJsMinification = this.clientResourceSettings.EnableJsMinification(); + return enableJsMinification.HasValue ? enableJsMinification.Value : this.EnableJsMinify; + } + } + public override string MinifyFile(Stream fileStream, ClientDependencyType type) { Func streamToString = stream => @@ -54,42 +72,24 @@ public override string MinifyFile(string fileContents, ClientDependencyType type case ClientDependencyType.Css: return this.MinifyCss ? CssHelper.MinifyCss(fileContents) : fileContents; case ClientDependencyType.Javascript: - { - if (!this.MinifyJs) + { + if (!this.MinifyJs) { return fileContents; } using (var ms = new MemoryStream()) - using (var writer = new StreamWriter(ms)) - { - writer.Write(fileContents); - writer.Flush(); - return JSMin.CompressJS(ms); + using (var writer = new StreamWriter(ms)) + { + writer.Write(fileContents); + writer.Flush(); + return JSMin.CompressJS(ms); + } } - } default: return fileContents; } } - - private bool MinifyCss - { - get - { - var enableCssMinification = this.clientResourceSettings.EnableCssMinification(); - return enableCssMinification.HasValue ? enableCssMinification.Value : this.EnableCssMinify; - } - } - - private bool MinifyJs - { - get - { - var enableJsMinification = this.clientResourceSettings.EnableJsMinification(); - return enableJsMinification.HasValue ? enableJsMinification.Value : this.EnableJsMinify; - } - } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBox.cs index 8b0ebaeb65a..5e472d0b53d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBox.cs @@ -11,6 +11,16 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnComboBox : RadComboBox { + public void AddItem(string text, string value) + { + this.Items.Add(new DnnComboBoxItem(text, value)); + } + + public void InsertItem(int index, string text, string value) + { + this.Items.Insert(index, new DnnComboBoxItem(text, value)); + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -35,16 +45,6 @@ protected override void OnPreRender(EventArgs e) base.OnPreRender(e); } - public void AddItem(string text, string value) - { - this.Items.Add(new DnnComboBoxItem(text, value)); - } - - public void InsertItem(int index, string text, string value) - { - this.Items.Insert(index, new DnnComboBoxItem(text, value)); - } - public void DataBind(string initialValue) { this.DataBind(initialValue, false); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormComboBoxItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormComboBoxItem.cs index 9d2af25dd78..0cb9c682e17 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormComboBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormComboBoxItem.cs @@ -17,16 +17,6 @@ public class DnnFormComboBoxItem : DnnFormListItemBase // public DropDownList ComboBox { get; set; } public DnnComboBox ComboBox { get; set; } - private void IndexChanged(object sender, EventArgs e) - { - this.UpdateDataSource(this.Value, this.ComboBox.SelectedValue, this.DataField); - } - - protected override void BindList() - { - BindListInternal(this.ComboBox, this.Value, this.ListSource, this.ListTextField, this.ListValueField); - } - // internal static void BindListInternal(DropDownList comboBox, object value, IEnumerable listSource, string textField, string valueField) internal static void BindListInternal(DnnComboBox comboBox, object value, IEnumerable listSource, string textField, string valueField) { @@ -62,6 +52,11 @@ internal static void BindListInternal(DnnComboBox comboBox, object value, IEnume } } + protected override void BindList() + { + BindListInternal(this.ComboBox, this.Value, this.ListSource, this.ListTextField, this.ListValueField); + } + protected override WebControl CreateControlInternal(Control container) { // ComboBox = new DropDownList { ID = ID + "_ComboBox" }; @@ -76,5 +71,10 @@ protected override WebControl CreateControlInternal(Control container) return this.ComboBox; } + + private void IndexChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this.ComboBox.SelectedValue, this.DataField); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormEnumItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormEnumItem.cs index 7f6f24ed384..c1986f46e07 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormEnumItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormEnumItem.cs @@ -25,8 +25,8 @@ public string EnumType this._enumType = value; // ReSharper disable AssignNullToNotNullAttribute - this.ListSource = (from object enumValue in Enum.GetValues(Type.GetType(this._enumType)) - select new { Name = Localization.GetString(Enum.GetName(Type.GetType(this._enumType), enumValue)) ?? Enum.GetName(Type.GetType(this._enumType), enumValue), Value = (int)enumValue }) + this.ListSource = (from object enumValue in Enum.GetValues(Type.GetType(this._enumType)) + select new { Name = Localization.GetString(Enum.GetName(Type.GetType(this._enumType), enumValue)) ?? Enum.GetName(Type.GetType(this._enumType), enumValue), Value = (int)enumValue }) .ToList(); // ReSharper restore AssignNullToNotNullAttribute diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormNumericTextBoxItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormNumericTextBoxItem.cs index 84a915393a6..43b346de621 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormNumericTextBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormNumericTextBoxItem.cs @@ -32,11 +32,6 @@ public DnnFormNumericTextBoxItem() public NumericType Type { get; set; } - private void TextChanged(object sender, EventArgs e) - { - this.UpdateDataSource(this.Value, this._textBox.Text, this.DataField); - } - protected override WebControl CreateControlInternal(Control container) { // _textBox = new DnnNumericTextBox {EmptyMessage = LocalizeString(ResourceKey + ".Hint"), ID = ID + "_TextBox", Width = TextBoxWidth }; @@ -68,5 +63,10 @@ protected override void OnInit(EventArgs e) this.FormMode = DnnFormMode.Short; } + + private void TextChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this._textBox.Text, this.DataField); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs index 6a10e60f504..74b67e78fe3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs @@ -30,35 +30,6 @@ public class DnnFormSkinsItem : DnnFormItemBase public string SkinDataField { get; set; } - private void ContainerIndexChanged(object sender, EventArgs e) - { - this.UpdateDataSource(this._containerValue, this._containerCombo.SelectedValue, this.ContainerDataField); - } - - private void SkinIndexChanged(object sender, EventArgs e) - { - this.UpdateDataSource(this._skinValue, this._skinCombo.SelectedValue, this.SkinDataField); - } - - private Dictionary GetSkins(string skinRoot) - { - // load host skins - var skins = SkinController.GetSkins(null, skinRoot, SkinScope.Host).ToDictionary(skin => skin.Key, skin => skin.Value); - - if (this.IncludePortalSkins) - { - // load portal skins - var portal = PortalController.Instance.GetPortal(this.PortalId); - - foreach (var skin in SkinController.GetSkins(portal, skinRoot, SkinScope.Site)) - { - skins.Add(skin.Key, skin.Value); - } - } - - return skins; - } - protected override WebControl CreateControlInternal(Control container) { var panel = new Panel(); @@ -101,6 +72,35 @@ protected override void DataBindInternal() this.Value = new Pair { First = this._skinValue, Second = this._containerValue }; } + private void ContainerIndexChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this._containerValue, this._containerCombo.SelectedValue, this.ContainerDataField); + } + + private void SkinIndexChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this._skinValue, this._skinCombo.SelectedValue, this.SkinDataField); + } + + private Dictionary GetSkins(string skinRoot) + { + // load host skins + var skins = SkinController.GetSkins(null, skinRoot, SkinScope.Host).ToDictionary(skin => skin.Key, skin => skin.Value); + + if (this.IncludePortalSkins) + { + // load portal skins + var portal = PortalController.Instance.GetPortal(this.PortalId); + + foreach (var skin in SkinController.GetSkins(portal, skinRoot, SkinScope.Site)) + { + skins.Add(skin.Key, skin.Value); + } + } + + return skins; + } + protected override void LoadControlState(object state) { base.LoadControlState(state); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs index 2edbff030f8..5411f9222b5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs @@ -11,13 +11,6 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnFormToggleButtonItem : DnnFormItemBase { - public enum CheckBoxMode - { - TrueFalse = 0, - YN = 1, - YesNo = 2, - } - // private DnnRadButton _checkBox; private CheckBox _checkBox; @@ -25,28 +18,16 @@ public DnnFormToggleButtonItem() { this.Mode = CheckBoxMode.TrueFalse; } + + public enum CheckBoxMode + { + TrueFalse = 0, + YN = 1, + YesNo = 2, + } public CheckBoxMode Mode { get; set; } - private void CheckedChanged(object sender, EventArgs e) - { - string newValue; - switch (this.Mode) - { - case CheckBoxMode.YN: - newValue = this._checkBox.Checked ? "Y" : "N"; - break; - case CheckBoxMode.YesNo: - newValue = this._checkBox.Checked ? "Yes" : "No"; - break; - default: - newValue = this._checkBox.Checked ? "true" : "false"; - break; - } - - this.UpdateDataSource(this.Value, newValue, this.DataField); - } - protected override WebControl CreateControlInternal(Control container) { // _checkBox = new DnnRadButton {ID = ID + "_CheckBox", ButtonType = RadButtonType.ToggleButton, ToggleType = ButtonToggleType.CheckBox, AutoPostBack = false}; @@ -85,5 +66,24 @@ protected override void OnInit(EventArgs e) this.FormMode = DnnFormMode.Short; } + + private void CheckedChanged(object sender, EventArgs e) + { + string newValue; + switch (this.Mode) + { + case CheckBoxMode.YN: + newValue = this._checkBox.Checked ? "Y" : "N"; + break; + case CheckBoxMode.YesNo: + newValue = this._checkBox.Checked ? "Yes" : "No"; + break; + default: + newValue = this._checkBox.Checked ? "true" : "false"; + break; + } + + this.UpdateDataSource(this.Value, newValue, this.DataField); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs index f243fbbeec7..6afbcd27d7f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs @@ -18,25 +18,6 @@ public string LocalResourceFile return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } } - - public override GridColumn Clone() - { - DnnGridButtonColumn dnnGridColumn = new DnnGridButtonColumn(); - - // you should override CopyBaseProperties if you have some column specific properties - dnnGridColumn.CopyBaseProperties(this); - - return dnnGridColumn; - } - - public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) - { - base.InitializeCell(cell, columnIndex, inItem); - if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) - { - cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); - } - } /// ----------------------------------------------------------------------------- /// @@ -61,6 +42,25 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in /// A String. /// ----------------------------------------------------------------------------- public string IconStyle { get; set; } + + public override GridColumn Clone() + { + DnnGridButtonColumn dnnGridColumn = new DnnGridButtonColumn(); + + // you should override CopyBaseProperties if you have some column specific properties + dnnGridColumn.CopyBaseProperties(this); + + return dnnGridColumn; + } + + public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem) + { + base.InitializeCell(cell, columnIndex, inItem); + if (inItem is GridHeaderItem && !string.IsNullOrEmpty(this.HeaderText)) + { + cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); + } + } public override string ImageUrl { diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs index 1a2c17c4935..c6ab0371be5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs @@ -11,6 +11,8 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnGridColumn : GridColumn { + private string _HeaderText; + public string LocalResourceFile { get @@ -18,16 +20,6 @@ public string LocalResourceFile return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } } - - public override GridColumn Clone() - { - var dnnGridColumn = new DnnGridColumn(); - dnnGridColumn.CopyBaseProperties(this); - dnnGridColumn.setHeaderText = this.HeaderText; - return dnnGridColumn; - } - - private string _HeaderText; public override string HeaderText { @@ -55,5 +47,13 @@ public string setHeaderText base.HeaderText = value; } } + + public override GridColumn Clone() + { + var dnnGridColumn = new DnnGridColumn(); + dnnGridColumn.CopyBaseProperties(this); + dnnGridColumn.setHeaderText = this.HeaderText; + return dnnGridColumn; + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs index 492770f765c..be0027ae8cf 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs @@ -117,6 +117,26 @@ public bool ShowImage /// /// A Boolean. public string VisibleField { get; set; } + + /// + /// Initialises the Column. + /// + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(GridItemType.Item); + this.EditItemTemplate = this.CreateTemplate(GridItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(GridItemType.Header); + + if (HttpContext.Current == null) + { + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + } + + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + } /// /// Creates a ImageCommandColumnTemplate. @@ -151,25 +171,5 @@ private DnnGridImageCommandColumnTemplate CreateTemplate(GridItemType type) return template; } - - /// - /// Initialises the Column. - /// - public override void Initialize() - { - this.ItemTemplate = this.CreateTemplate(GridItemType.Item); - this.EditItemTemplate = this.CreateTemplate(GridItemType.EditItem); - this.HeaderTemplate = this.CreateTemplate(GridItemType.Header); - - if (HttpContext.Current == null) - { - this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; - this.HeaderStyle.Font.Size = new FontUnit("10pt"); - this.HeaderStyle.Font.Bold = true; - } - - this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; - this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs index cdc339bc566..4a86cc60f9f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs @@ -164,8 +164,8 @@ public void InstantiateIn(Control container) { if (!string.IsNullOrEmpty(this.ImageURL) && this.ShowImage) { - var colIcon = new ImageButton - { ImageUrl = this.DesignMode ? this.ImageURL.Replace("~/", "../../") : this.ImageURL, ToolTip = this.Text }; + var colIcon = new ImageButton + { ImageUrl = this.DesignMode ? this.ImageURL.Replace("~/", "../../") : this.ImageURL, ToolTip = this.Text }; if (!string.IsNullOrEmpty(this.OnClickJs)) { ClientAPI.AddButtonConfirm(colIcon, this.OnClickJs); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs index a39afb9bd7d..a8581217a7f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs @@ -24,18 +24,6 @@ public class DnnLanguageComboBox : WebControl private DnnComboBox _nativeCombo; private string _originalValue; - - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - - public event EventHandler ItemChanged; - - public event EventHandler ModeChanged; public DnnLanguageComboBox() { @@ -48,6 +36,22 @@ public DnnLanguageComboBox() this._viewTypePersonalizationKey = "ViewType" + this.PortalId; } + public event EventHandler ItemChanged; + + public event EventHandler ModeChanged; + + public string FlagImageUrlFormatString { get; set; } + + public Dictionary HideLanguagesList { get; set; } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + private string DisplayMode { get @@ -62,10 +66,6 @@ private string DisplayMode } } - public string FlagImageUrlFormatString { get; set; } - - public Dictionary HideLanguagesList { get; set; } - public bool IncludeNoneSpecified { get; set; } public LanguagesListType LanguagesListType @@ -152,6 +152,25 @@ public void BindData(bool refresh) } } + public void SetLanguage(string code) + { + if (string.IsNullOrEmpty(code)) + { + this._nativeCombo.SelectedIndex = this._nativeCombo.FindItemIndexByValue("None"); + this._englishCombo.SelectedIndex = this._englishCombo.FindItemIndexByValue("None"); + } + else + { + this._nativeCombo.SelectedIndex = this._nativeCombo.FindItemIndexByValue(code); + this._englishCombo.SelectedIndex = this._englishCombo.FindItemIndexByValue(code); + } + } + + public override void DataBind() + { + this.BindData(!this.Page.IsPostBack); + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -244,25 +263,6 @@ protected override void OnPreRender(EventArgs e) base.OnPreRender(e); } - public void SetLanguage(string code) - { - if (string.IsNullOrEmpty(code)) - { - this._nativeCombo.SelectedIndex = this._nativeCombo.FindItemIndexByValue("None"); - this._englishCombo.SelectedIndex = this._englishCombo.FindItemIndexByValue("None"); - } - else - { - this._nativeCombo.SelectedIndex = this._nativeCombo.FindItemIndexByValue(code); - this._englishCombo.SelectedIndex = this._englishCombo.FindItemIndexByValue(code); - } - } - - public override void DataBind() - { - this.BindData(!this.Page.IsPostBack); - } - private void ModeChangedInternal(object sender, EventArgs e) { Personalization.SetProfile("LanguageDisplayMode", this._viewTypePersonalizationKey, this._modeRadioButtonList.SelectedValue); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs index 3c618eb1bce..fc92438e2ae 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs @@ -22,6 +22,9 @@ public class DnnModuleComboBox : WebControl { private const string DefaultExtensionImage = "icon_extensions_32px.png"; + private DnnComboBox _moduleCombo; + private string _originalValue; + public event EventHandler ItemChanged; public Func, bool> Filter { get; set; } @@ -63,25 +66,35 @@ public override bool Enabled } } - private Dictionary GetPortalDesktopModules() + public void BindAllPortalDesktopModules() { - IOrderedEnumerable> portalModulesList; - if (this.Filter == null) - { - portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) - .Where((kvp) => kvp.Value.DesktopModule.Category == "Uncategorised" || string.IsNullOrEmpty(kvp.Value.DesktopModule.Category)) - .OrderBy(c => c.Key); - } - else - { - portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) - .Where(this.Filter) - .OrderBy(c => c.Key); - } + this._moduleCombo.SelectedValue = null; + this._moduleCombo.DataSource = this.GetPortalDesktopModules(); + this._moduleCombo.DataBind(); + this.BindPortalDesktopModuleImages(); + } - return portalModulesList.ToDictionary( - portalModule => portalModule.Value.DesktopModuleID, - portalModule => portalModule.Key); + public void BindTabModulesByTabID(int tabID) + { + this._moduleCombo.SelectedValue = null; + this._moduleCombo.DataSource = GetTabModules(tabID); + this._moduleCombo.DataBind(); + this.BindTabModuleImages(tabID); + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this._moduleCombo = new DnnComboBox(); + this._moduleCombo.DataValueField = "key"; + this._moduleCombo.DataTextField = "value"; + this.Controls.Add(this._moduleCombo); + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this._originalValue = this.SelectedValue; } private static Dictionary GetTabModules(int tabID) @@ -107,6 +120,27 @@ private static bool ModuleSuportsSharing(ModuleInfo moduleInfo) return false; } } + + private Dictionary GetPortalDesktopModules() + { + IOrderedEnumerable> portalModulesList; + if (this.Filter == null) + { + portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) + .Where((kvp) => kvp.Value.DesktopModule.Category == "Uncategorised" || string.IsNullOrEmpty(kvp.Value.DesktopModule.Category)) + .OrderBy(c => c.Key); + } + else + { + portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) + .Where(this.Filter) + .OrderBy(c => c.Key); + } + + return portalModulesList.ToDictionary( + portalModule => portalModule.Value.DesktopModuleID, + portalModule => portalModule.Key); + } private void BindPortalDesktopModuleImages() { @@ -144,21 +178,6 @@ where tabMods.Value.ModuleID.ToString() == item.Value item.ImageUrl = string.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; } } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - this._moduleCombo = new DnnComboBox(); - this._moduleCombo.DataValueField = "key"; - this._moduleCombo.DataTextField = "value"; - this.Controls.Add(this._moduleCombo); - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - this._originalValue = this.SelectedValue; - } protected virtual void OnItemChanged() { @@ -178,29 +197,10 @@ protected override void OnPreRender(EventArgs e) this._moduleCombo.Width = this.Width; base.OnPreRender(e); } - - public void BindAllPortalDesktopModules() - { - this._moduleCombo.SelectedValue = null; - this._moduleCombo.DataSource = this.GetPortalDesktopModules(); - this._moduleCombo.DataBind(); - this.BindPortalDesktopModuleImages(); - } - - public void BindTabModulesByTabID(int tabID) - { - this._moduleCombo.SelectedValue = null; - this._moduleCombo.DataSource = GetTabModules(tabID); - this._moduleCombo.DataBind(); - this.BindTabModuleImages(tabID); - } public void SetModule(string code) { this._moduleCombo.SelectedIndex = this._moduleCombo.FindItemIndexByValue(code); } - - private DnnComboBox _moduleCombo; - private string _originalValue; } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs index c3af76e0c65..8f57e43f1dc 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs @@ -10,22 +10,10 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnRadButton : RadButton - { - private bool _Localize = true; + { + private bool _Localize = true; - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - this.LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - this.LocalizeStrings(); - base.Render(writer); - } - - public bool Localize + public bool Localize { get { @@ -41,11 +29,11 @@ public bool Localize { this._Localize = value; } - } - - public string LocalResourceFile { get; set; } - - public virtual void LocalizeStrings() + } + + public string LocalResourceFile { get; set; } + + public virtual void LocalizeStrings() { if (this.Localize) { @@ -65,5 +53,17 @@ public virtual void LocalizeStrings() } } } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); + } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs index 76573c23e7b..8233bb6851f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs @@ -22,6 +22,11 @@ namespace DotNetNuke.Web.UI.WebControls [ToolboxData("<{0}:DnnSkinComboBox runat='server'>")] public class DnnSkinComboBox : DnnComboBox { + public DnnSkinComboBox() + { + this.PortalId = Null.NullInteger; + } + public int PortalId { get; set; } public string RootPath { get; set; } @@ -37,11 +42,6 @@ private PortalInfo Portal get { return this.PortalId == Null.NullInteger ? null : PortalController.Instance.GetPortal(this.PortalId); } } - public DnnSkinComboBox() - { - this.PortalId = Null.NullInteger; - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabPanel.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabPanel.cs index 20c9c865980..047fd8f225d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabPanel.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTabPanel.cs @@ -16,42 +16,42 @@ public class DnnTabPanel : WebControl private RadMultiPage _TelerikPages; private RadTabStrip _TelerikTabs; - private RadTabStrip TelerikTabs + public DnnTabCollection Tabs { get { - if (this._TelerikTabs == null) + if (this._Tabs == null) { - this._TelerikTabs = new RadTabStrip(); + this._Tabs = new DnnTabCollection(this); } - return this._TelerikTabs; + return this._Tabs; } } - private RadMultiPage TelerikPages + private RadTabStrip TelerikTabs { get { - if (this._TelerikPages == null) + if (this._TelerikTabs == null) { - this._TelerikPages = new RadMultiPage(); + this._TelerikTabs = new RadTabStrip(); } - return this._TelerikPages; + return this._TelerikTabs; } } - public DnnTabCollection Tabs + private RadMultiPage TelerikPages { get { - if (this._Tabs == null) + if (this._TelerikPages == null) { - this._Tabs = new DnnTabCollection(this); + this._TelerikPages = new RadMultiPage(); } - return this._Tabs; + return this._TelerikPages; } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs index aa16b780fdc..e46bf6afea8 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs @@ -9,57 +9,57 @@ namespace DotNetNuke.Web.UI.WebControls using DotNetNuke.Web.UI; using Telerik.Web.UI; - public class DnnToolTip : RadToolTip, ILocalizable - { - private bool _localize = true; - - protected override void Render(HtmlTextWriter writer) - { - this.LocalizeStrings(); - base.Render(writer); - } - - public string ResourceKey { get; set; } + public class DnnToolTip : RadToolTip, ILocalizable + { + private bool _localize = true; - public bool Localize - { - get - { - if (this.DesignMode) - { - return false; - } + public string ResourceKey { get; set; } - return this._localize; - } + public bool Localize + { + get + { + if (this.DesignMode) + { + return false; + } - set - { - this._localize = value; - } - } - - public string LocalResourceFile { get; set; } - - public virtual void LocalizeStrings() - { - if (this.Localize && (! string.IsNullOrEmpty(this.ResourceKey))) - { - if (! string.IsNullOrEmpty(this.ManualCloseButtonText)) - { - this.ManualCloseButtonText = Utilities.GetLocalizedStringFromParent(string.Format("{0}.ManualCloseButtonText", this.ResourceKey), this); - } - - if (! string.IsNullOrEmpty(this.Text)) - { - this.Text = Utilities.GetLocalizedStringFromParent(string.Format("{0}.Text", this.ResourceKey), this); - } - - if (! string.IsNullOrEmpty(this.ToolTip)) - { - this.ToolTip = Utilities.GetLocalizedStringFromParent(string.Format("{0}.ToolTip", this.ResourceKey), this); - } - } - } + return this._localize; + } + + set + { + this._localize = value; + } + } + + public string LocalResourceFile { get; set; } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } + + public virtual void LocalizeStrings() + { + if (this.Localize && (!string.IsNullOrEmpty(this.ResourceKey))) + { + if (!string.IsNullOrEmpty(this.ManualCloseButtonText)) + { + this.ManualCloseButtonText = Utilities.GetLocalizedStringFromParent(string.Format("{0}.ManualCloseButtonText", this.ResourceKey), this); + } + + if (!string.IsNullOrEmpty(this.Text)) + { + this.Text = Utilities.GetLocalizedStringFromParent(string.Format("{0}.Text", this.ResourceKey), this); + } + + if (!string.IsNullOrEmpty(this.ToolTip)) + { + this.ToolTip = Utilities.GetLocalizedStringFromParent(string.Format("{0}.ToolTip", this.ResourceKey), this); + } + } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs index e829813d8ef..c9d135df542 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs @@ -33,6 +33,28 @@ public class DateEditControl : EditControl private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateEditControl)); private DnnDatePicker _dateControl; + public override string ID + { + get + { + return base.ID + "_control"; + } + + set + { + base.ID = value; + } + } + + public override string EditControlClientId + { + get + { + this.EnsureChildControls(); + return this.DateControl.DateInput.ClientID; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets dateValue returns the Date representation of the Value. @@ -154,28 +176,6 @@ protected override string StringValue } } - public override string ID - { - get - { - return base.ID + "_control"; - } - - set - { - base.ID = value; - } - } - - public override string EditControlClientId - { - get - { - this.EnsureChildControls(); - return this.DateControl.DateInput.ClientID; - } - } - private DnnDatePicker DateControl { get @@ -188,24 +188,6 @@ private DnnDatePicker DateControl return this._dateControl; } } - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); - this.DateControl.ID = base.ID + "_control"; - - this.Controls.Add(this.DateControl); - } - - protected virtual void LoadDateControls() - { - if (this.DateValue != Null.NullDate) - { - this.DateControl.SelectedDate = this.DateValue.Date; - } - } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -230,6 +212,24 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo this.LoadDateControls(); return dataChanged; } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); + this.DateControl.ID = base.ID + "_control"; + + this.Controls.Add(this.DateControl); + } + + protected virtual void LoadDateControls() + { + if (this.DateValue != Null.NullDate) + { + this.DateControl.SelectedDate = this.DateValue.Date; + } + } /// /// OnDataChanged is called by the PostBack Handler when the Data has changed. diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs index adb714d630e..e2664d9d320 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs @@ -37,6 +37,19 @@ public class DateTimeEditControl : EditControl private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateTimeEditControl)); private DnnDateTimePicker _dateControl; + public override string ID + { + get + { + return base.ID + "_control"; + } + + set + { + base.ID = value; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets dateValue returns the Date representation of the Value. @@ -158,19 +171,6 @@ protected override string StringValue } } - public override string ID - { - get - { - return base.ID + "_control"; - } - - set - { - base.ID = value; - } - } - private DnnDateTimePicker DateControl { get @@ -183,24 +183,6 @@ private DnnDateTimePicker DateControl return this._dateControl; } } - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); - this.DateControl.ID = base.ID + "_control"; - - this.Controls.Add(this.DateControl); - } - - protected virtual void LoadDateControls() - { - if (this.DateValue != Null.NullDate) - { - this.DateControl.SelectedDate = this.DateValue; - } - } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -230,6 +212,24 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo this.LoadDateControls(); return dataChanged; } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); + this.DateControl.ID = base.ID + "_control"; + + this.Controls.Add(this.DateControl); + } + + protected virtual void LoadDateControls() + { + if (this.DateValue != Null.NullDate) + { + this.DateControl.SelectedDate = this.DateValue; + } + } /// /// OnDataChanged is called by the PostBack Handler when the Data has changed. diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs index 8ee455f42d8..fb5b16143a5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs @@ -86,6 +86,26 @@ public List Terms } } + public void BindTerms(List terms, bool isHeirarchical, bool dataBind) + { + this._IsHeirarchical = isHeirarchical; + + this._ListBox.DataSource = terms; + this._TreeView.DataSource = terms; + + if (dataBind) + { + this._ListBox.DataBind(); + this._TreeView.DataBind(); + } + } + + public void ClearSelectedTerm() + { + this._ListBox.SelectedIndex = Null.NullInteger; + this._TreeView.UnselectAllNodes(); + } + protected override void CreateChildControls() { this.Controls.Clear(); @@ -149,25 +169,5 @@ private void TreeViewNodeClick(object sender, RadTreeNodeEventArgs e) // Raise the SelectedTermChanged Event this.OnSelectedTermChanged(new TermsEventArgs(this.SelectedTerm)); } - - public void BindTerms(List terms, bool isHeirarchical, bool dataBind) - { - this._IsHeirarchical = isHeirarchical; - - this._ListBox.DataSource = terms; - this._TreeView.DataSource = terms; - - if (dataBind) - { - this._ListBox.DataBind(); - this._TreeView.DataBind(); - } - } - - public void ClearSelectedTerm() - { - this._ListBox.SelectedIndex = Null.NullInteger; - this._TreeView.UnselectAllNodes(); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs index 01b54a6ef90..9b1e7dd7921 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs @@ -37,6 +37,18 @@ public TermsSelector() public List Terms { get; set; } + public string RaiseClientAPICallbackEvent(string eventArgument) + { + var parameters = eventArgument.Split('-'); + this.PortalId = Convert.ToInt32(parameters[1]); + this.IncludeTags = Convert.ToBoolean(parameters[2]); + this.IncludeSystemVocabularies = Convert.ToBoolean(parameters[3]); + var terms = this.GetTerms(); + terms.Insert(0, new { clientId = parameters[0] }); + var serializer = new JavaScriptSerializer(); + return serializer.Serialize(terms); + } + protected override void OnInit(EventArgs e) { this.ItemTemplate = new TreeViewTemplate(); @@ -118,42 +130,6 @@ protected override void OnPreRender(EventArgs e) this.Attributes.Add("PortalId", this.PortalId.ToString()); } - public class TreeViewTemplate : ITemplate - { - private RadComboBoxItem _container; - private TermsSelector _termsSelector; - - private DnnTreeView _tree; - - public void InstantiateIn(Control container) - { - this._container = (RadComboBoxItem)container; - this._termsSelector = (TermsSelector)container.Parent; - - this._tree = new DnnTreeView(); - this._tree.ID = string.Format("{0}_TreeView", this._termsSelector.ID); - this._tree.CheckBoxes = true; - this._tree.EnableViewState = false; - - // bind client-side events - this._tree.OnClientNodeChecked = "webcontrols.termsSelector.OnClientNodeChecked"; - - this._container.Controls.Add(this._tree); - } - } - - public string RaiseClientAPICallbackEvent(string eventArgument) - { - var parameters = eventArgument.Split('-'); - this.PortalId = Convert.ToInt32(parameters[1]); - this.IncludeTags = Convert.ToBoolean(parameters[2]); - this.IncludeSystemVocabularies = Convert.ToBoolean(parameters[3]); - var terms = this.GetTerms(); - terms.Insert(0, new { clientId = parameters[0] }); - var serializer = new JavaScriptSerializer(); - return serializer.Serialize(terms); - } - private ArrayList GetTerms() { var vocabRep = Util.GetVocabularyController(); @@ -198,5 +174,29 @@ private void AddTerms(Vocabulary v, ArrayList terms) terms.Add(new { termId = t.TermId, name = t.Name, parentTermId = t.ParentTermId }); } } + + public class TreeViewTemplate : ITemplate + { + private RadComboBoxItem _container; + private TermsSelector _termsSelector; + + private DnnTreeView _tree; + + public void InstantiateIn(Control container) + { + this._container = (RadComboBoxItem)container; + this._termsSelector = (TermsSelector)container.Parent; + + this._tree = new DnnTreeView(); + this._tree.ID = string.Format("{0}_TreeView", this._termsSelector.ID); + this._tree.CheckBoxes = true; + this._tree.EnableViewState = false; + + // bind client-side events + this._tree.OnClientNodeChecked = "webcontrols.termsSelector.OnClientNodeChecked"; + + this._container.Controls.Add(this._tree); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs index d09288d6208..041b6e714aa 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs @@ -11,14 +11,14 @@ namespace DotNetNuke.Web.Mvc.Common public class DesktopModuleControllerAdapter : ServiceLocator, IDesktopModuleController { - protected override Func GetFactory() - { - return () => new DesktopModuleControllerAdapter(); - } - public DesktopModuleInfo GetDesktopModule(int desktopModuleId, int portalId) { return Entities.Modules.DesktopModuleController.GetDesktopModule(desktopModuleId, portalId); } + + protected override Func GetFactory() + { + return () => new DesktopModuleControllerAdapter(); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/ModuleControlControllerAdapter.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/ModuleControlControllerAdapter.cs index 46f9567e21e..af6ec17d7d3 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/ModuleControlControllerAdapter.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/ModuleControlControllerAdapter.cs @@ -15,14 +15,14 @@ namespace DotNetNuke.Web.Mvc.Common public class ModuleControlControllerAdapter : ServiceLocator, IModuleControlController { - protected override Func GetFactory() - { - return () => new ModuleControlControllerAdapter(); - } - public ModuleControlInfo GetModuleControlByControlKey(string controlKey, int moduleDefID) { return ModuleControlController.GetModuleControlByControlKey(controlKey, moduleDefID); } + + protected override Func GetFactory() + { + return () => new ModuleControlControllerAdapter(); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs index 5a58726d43c..d7c633fb398 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs @@ -32,22 +32,6 @@ public PropertyHelper(PropertyInfo property) public virtual string Name { get; protected set; } - private static object CallPropertyGetter(Func getter, object @this) - { - return getter((TDeclaringType)@this); - } - - private static object CallPropertyGetterByReference(ByRefFunc getter, object @this) - { - TDeclaringType unboxed = (TDeclaringType)@this; - return getter(ref unboxed); - } - - private static PropertyHelper CreateInstance(PropertyInfo property) - { - return new PropertyHelper(property); - } - /// /// Creates and caches fast property helpers that expose getters for every public get property on the underlying type. /// @@ -58,6 +42,52 @@ public static PropertyHelper[] GetProperties(object instance) return GetProperties(instance, CreateInstance, ReflectionCache); } + /// + /// Creates a single fast property getter. The result is not cached. + /// + /// propertyInfo to extract the getter for. + /// a fast getter. + /// This method is more memory efficient than a dynamically compiled lambda, and about the same speed. + public static Func MakeFastPropertyGetter(PropertyInfo propertyInfo) + { + Requires.NotNull("property", propertyInfo); + + MethodInfo getMethod = propertyInfo.GetGetMethod(); + Guard.Against(getMethod == null, "Property must have a Get Method"); + Guard.Against(getMethod.IsStatic, "Property's Get method must not be static"); + Guard.Against(getMethod.GetParameters().Length != 0, "Property's Get method must not have parameters"); + + // Instance methods in the CLR can be turned into static methods where the first parameter + // is open over "this". This parameter is always passed by reference, so we have a code + // path for value types and a code path for reference types. + Type typeInput = getMethod.ReflectedType; + Type typeOutput = getMethod.ReturnType; + + Delegate callPropertyGetterDelegate; + if (typeInput.IsValueType) + { + // Create a delegate (ref TDeclaringType) -> TValue + Delegate propertyGetterAsFunc = getMethod.CreateDelegate(typeof(ByRefFunc<,>).MakeGenericType(typeInput, typeOutput)); + MethodInfo callPropertyGetterClosedGenericMethod = CallPropertyGetterByReferenceOpenGenericMethod.MakeGenericMethod(typeInput, typeOutput); + callPropertyGetterDelegate = Delegate.CreateDelegate(typeof(Func), propertyGetterAsFunc, callPropertyGetterClosedGenericMethod); + } + else + { + // Create a delegate TDeclaringType -> TValue + Delegate propertyGetterAsFunc = getMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(typeInput, typeOutput)); + MethodInfo callPropertyGetterClosedGenericMethod = CallPropertyGetterOpenGenericMethod.MakeGenericMethod(typeInput, typeOutput); + callPropertyGetterDelegate = Delegate.CreateDelegate(typeof(Func), propertyGetterAsFunc, callPropertyGetterClosedGenericMethod); + } + + return (Func)callPropertyGetterDelegate; + } + + public object GetValue(object instance) + { + // Contract.Assert(_valueGetter != null, "Must call Initialize before using this object"); + return this._valueGetter(instance); + } + protected static PropertyHelper[] GetProperties( object instance, Func createPropertyHelper, @@ -92,50 +122,20 @@ protected static PropertyHelper[] GetProperties( return helpers; } - public object GetValue(object instance) + private static object CallPropertyGetter(Func getter, object @this) { - // Contract.Assert(_valueGetter != null, "Must call Initialize before using this object"); - return this._valueGetter(instance); + return getter((TDeclaringType)@this); } - /// - /// Creates a single fast property getter. The result is not cached. - /// - /// propertyInfo to extract the getter for. - /// a fast getter. - /// This method is more memory efficient than a dynamically compiled lambda, and about the same speed. - public static Func MakeFastPropertyGetter(PropertyInfo propertyInfo) + private static object CallPropertyGetterByReference(ByRefFunc getter, object @this) { - Requires.NotNull("property", propertyInfo); - - MethodInfo getMethod = propertyInfo.GetGetMethod(); - Guard.Against(getMethod == null, "Property must have a Get Method"); - Guard.Against(getMethod.IsStatic, "Property's Get method must not be static"); - Guard.Against(getMethod.GetParameters().Length != 0, "Property's Get method must not have parameters"); - - // Instance methods in the CLR can be turned into static methods where the first parameter - // is open over "this". This parameter is always passed by reference, so we have a code - // path for value types and a code path for reference types. - Type typeInput = getMethod.ReflectedType; - Type typeOutput = getMethod.ReturnType; - - Delegate callPropertyGetterDelegate; - if (typeInput.IsValueType) - { - // Create a delegate (ref TDeclaringType) -> TValue - Delegate propertyGetterAsFunc = getMethod.CreateDelegate(typeof(ByRefFunc<,>).MakeGenericType(typeInput, typeOutput)); - MethodInfo callPropertyGetterClosedGenericMethod = CallPropertyGetterByReferenceOpenGenericMethod.MakeGenericMethod(typeInput, typeOutput); - callPropertyGetterDelegate = Delegate.CreateDelegate(typeof(Func), propertyGetterAsFunc, callPropertyGetterClosedGenericMethod); - } - else - { - // Create a delegate TDeclaringType -> TValue - Delegate propertyGetterAsFunc = getMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(typeInput, typeOutput)); - MethodInfo callPropertyGetterClosedGenericMethod = CallPropertyGetterOpenGenericMethod.MakeGenericMethod(typeInput, typeOutput); - callPropertyGetterDelegate = Delegate.CreateDelegate(typeof(Func), propertyGetterAsFunc, callPropertyGetterClosedGenericMethod); - } + TDeclaringType unboxed = (TDeclaringType)@this; + return getter(ref unboxed); + } - return (Func)callPropertyGetterDelegate; + private static PropertyHelper CreateInstance(PropertyInfo property) + { + return new PropertyHelper(property); } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs index f596888b99e..f0d547beb0e 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs @@ -21,6 +21,10 @@ namespace DotNetNuke.Web.Mvc public class DnnMvcHandler : IHttpHandler, IRequiresSessionState { + public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version"; + + private ControllerBuilder _controllerBuilder; + public DnnMvcHandler(RequestContext requestContext) { if (requestContext == null) @@ -31,9 +35,12 @@ public DnnMvcHandler(RequestContext requestContext) this.RequestContext = requestContext; } - public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version"; + public static bool DisableMvcResponseHeader { get; set; } - private ControllerBuilder _controllerBuilder; + bool IHttpHandler.IsReusable + { + get { return this.IsReusable; } + } internal ControllerBuilder ControllerBuilder { @@ -55,12 +62,7 @@ protected virtual bool IsReusable get { return false; } } - public static bool DisableMvcResponseHeader { get; set; } - - bool IHttpHandler.IsReusable - { - get { return this.IsReusable; } - } + public RequestContext RequestContext { get; private set; } void IHttpHandler.ProcessRequest(HttpContext httpContext) { @@ -68,14 +70,6 @@ void IHttpHandler.ProcessRequest(HttpContext httpContext) this.ProcessRequest(httpContext); } - public RequestContext RequestContext { get; private set; } - - protected virtual void ProcessRequest(HttpContext httpContext) - { - HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); - this.ProcessRequest(httpContextBase); - } - protected internal virtual void ProcessRequest(HttpContextBase httpContext) { try @@ -92,6 +86,12 @@ protected internal virtual void ProcessRequest(HttpContextBase httpContext) { } } + + protected virtual void ProcessRequest(HttpContext httpContext) + { + HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); + this.ProcessRequest(httpContextBase); + } private IModuleExecutionEngine GetModuleExecutionEngine() { diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs index c0dc5b1e94a..cc70bc66ce1 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs @@ -22,6 +22,11 @@ public DnnMvcRouteHandler(IControllerFactory controllerFactory) { this._controllerFactory = controllerFactory; } + + IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) + { + return this.GetHttpHandler(requestContext); + } protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext) { @@ -40,10 +45,5 @@ protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext re IControllerFactory controllerFactory = this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory(); return controllerFactory.GetControllerSessionBehavior(requestContext, controllerName); } - - IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) - { - return this.GetHttpHandler(requestContext); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs index 1eda5cd0a63..5ea5e45c7a3 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs @@ -12,16 +12,12 @@ namespace DotNetNuke.Web.Mvc.Framework.ActionFilters public abstract class AuthorizeAttributeBase : FilterAttribute, IAuthorizationFilter { - protected virtual bool AuthorizeCore(HttpContextBase httpContext) - { - return true; - } - - private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) + public static bool IsAnonymousAttributePresent(AuthorizationContext filterContext) { - validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context)); + return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) + || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); } - + public virtual void OnAuthorization(AuthorizationContext filterContext) { Requires.NotNull("filterContext", filterContext); @@ -40,6 +36,11 @@ public virtual void OnAuthorization(AuthorizationContext filterContext) this.HandleUnauthorizedRequest(filterContext); } } + + protected virtual bool AuthorizeCore(HttpContextBase httpContext) + { + return true; + } protected virtual void HandleAuthorizedRequest(AuthorizationContext filterContext) { @@ -48,6 +49,11 @@ protected virtual void HandleAuthorizedRequest(AuthorizationContext filterContex cachePolicy.AddValidationCallback(this.CacheValidateHandler, null /* data */); } + private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) + { + validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context)); + } + protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) { const string failureMessage = "Authorization has been denied for this request."; @@ -74,11 +80,5 @@ protected virtual bool SkipAuthorization(AuthorizationContext filterContext) { return IsAnonymousAttributePresent(filterContext); } - - public static bool IsAnonymousAttributePresent(AuthorizationContext filterContext) - { - return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) - || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnModuleAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnModuleAuthorizeAttribute.cs index 47cec2cd3ef..70870d9e308 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnModuleAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnModuleAuthorizeAttribute.cs @@ -26,16 +26,6 @@ public DnnModuleAuthorizeAttribute() public string PermissionKey { get; set; } - protected override bool AuthorizeCore(HttpContextBase httpContext) - { - if (this._module != null) - { - return this.HasModuleAccess(); - } - - return false; - } - public override void OnAuthorization(AuthorizationContext filterContext) { var controller = filterContext.Controller as IDnnController; @@ -50,6 +40,16 @@ public override void OnAuthorization(AuthorizationContext filterContext) base.OnAuthorization(filterContext); } + protected override bool AuthorizeCore(HttpContextBase httpContext) + { + if (this._module != null) + { + return this.HasModuleAccess(); + } + + return false; + } + protected virtual bool HasModuleAccess() { return ModulePermissionController.HasModuleAccess(this.AccessLevel, this.PermissionKey, this._module); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/RequireHostAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/RequireHostAttribute.cs index 0193fa88068..1578f8fc094 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/RequireHostAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/RequireHostAttribute.cs @@ -16,6 +16,20 @@ public class RequireHostAttribute : AuthorizeAttributeBase { private UserInfo _user; + public override void OnAuthorization(AuthorizationContext filterContext) + { + var controller = filterContext.Controller as IDnnController; + + if (controller == null) + { + throw new InvalidOperationException("This attribute can only be applied to Controllers that implement IDnnController"); + } + + this._user = controller.ModuleContext.PortalSettings.UserInfo; + + base.OnAuthorization(filterContext); + } + protected override bool AuthorizeCore(HttpContextBase httpContext) { var principal = Thread.CurrentPrincipal; @@ -31,19 +45,5 @@ protected override bool AuthorizeCore(HttpContextBase httpContext) return false; } - - public override void OnAuthorization(AuthorizationContext filterContext) - { - var controller = filterContext.Controller as IDnnController; - - if (controller == null) - { - throw new InvalidOperationException("This attribute can only be applied to Controllers that implement IDnnController"); - } - - this._user = controller.ModuleContext.PortalSettings.UserInfo; - - base.OnAuthorization(filterContext); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs index 268b24b7737..df015229dda 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs @@ -13,9 +13,9 @@ namespace DotNetNuke.Web.Mvc.Framework.ActionFilters using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; - using DotNetNuke.Web.Mvc.Common; + using DotNetNuke.Web.Mvc.Common; - public class ValidateAntiForgeryTokenAttribute : AuthorizeAttributeBase + public class ValidateAntiForgeryTokenAttribute : AuthorizeAttributeBase { public virtual bool IsAuthenticated(HttpContextBase httpContext) { diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs index 67254affc23..6d79d51ed49 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs @@ -15,8 +15,6 @@ namespace DotNetNuke.Web.Mvc.Framework.ActionResults internal class DnnRedirecttoRouteResult : RedirectToRouteResult { - protected INavigationManager NavigationManager { get; } - public DnnRedirecttoRouteResult(string actionName, string controllerName, string routeName, RouteValueDictionary routeValues, bool permanent) : base(routeName, routeValues, permanent) { @@ -32,6 +30,8 @@ public DnnRedirecttoRouteResult(string actionName, string controllerName, string } public DnnUrlHelper Url { get; private set; } + + protected INavigationManager NavigationManager { get; } public string ActionName { get; private set; } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs index f11fefb4938..d2c29dbc52e 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs @@ -44,11 +44,6 @@ public TabInfo ActivePage public string LocalResourceFile { get; set; } - public string LocalizeString(string key) - { - return Localization.GetString(key, this.LocalResourceFile); - } - public ModuleActionCollection ModuleActions { get; set; } public ModuleInstanceContext ModuleContext { get; set; } @@ -58,14 +53,9 @@ public PortalSettings PortalSettings get { return (this.ModuleContext == null) ? null : this.ModuleContext.PortalSettings; } } - protected override RedirectToRouteResult RedirectToAction(string actionName, string controllerName, RouteValueDictionary routeValues) - { - return new DnnRedirecttoRouteResult(actionName, controllerName, string.Empty, routeValues, false, this.Url); - } - - protected internal RedirectToRouteResult RedirectToDefaultRoute() + public string LocalizeString(string key) { - return new DnnRedirecttoRouteResult(string.Empty, string.Empty, string.Empty, null, false); + return Localization.GetString(key, this.LocalResourceFile); } public ActionResult ResultOfLastExecute @@ -82,6 +72,18 @@ public ActionResult ResultOfLastExecute get { return (this.PortalSettings == null) ? null : this.PortalSettings.UserInfo; } } + public ViewEngineCollection ViewEngineCollectionEx { get; set; } + + protected internal RedirectToRouteResult RedirectToDefaultRoute() + { + return new DnnRedirecttoRouteResult(string.Empty, string.Empty, string.Empty, null, false); + } + + protected override RedirectToRouteResult RedirectToAction(string actionName, string controllerName, RouteValueDictionary routeValues) + { + return new DnnRedirecttoRouteResult(actionName, controllerName, string.Empty, routeValues, false, this.Url); + } + protected override ViewResult View(IView view, object model) { if (model != null) @@ -135,7 +137,5 @@ protected override void Initialize(RequestContext requestContext) base.Initialize(requestContext); this.Url = new DnnUrlHelper(requestContext, this); } - - public ViewEngineCollection ViewEngineCollectionEx { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs index b114d19e1b4..3c2f1ba3b45 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs @@ -19,14 +19,14 @@ public interface IDnnController : IController string LocalResourceFile { get; set; } - string LocalizeString(string key); - ModuleActionCollection ModuleActions { get; set; } ModuleInstanceContext ModuleContext { get; set; } ActionResult ResultOfLastExecute { get; } + string LocalizeString(string key); + bool ValidateRequest { get; set; } ViewEngineCollection ViewEngineCollectionEx { get; set; } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs index cec5bd3d018..fadc409b3a8 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs @@ -55,6 +55,16 @@ public void ReleaseView(ControllerContext controllerContext, IView view) } } + private static ModuleRequestResult GetCurrentModuleRequestResult(ControllerContext controllerContext) + { + if (controllerContext.HttpContext.HasModuleRequestResult()) + { + return controllerContext.HttpContext.GetModuleRequestResult(); + } + + return null; + } + private ViewEngineResult RunAgainstModuleViewEngines(ControllerContext controllerContext, Func engineRequest) { var controller = controllerContext.Controller as IDnnController; @@ -73,15 +83,5 @@ private ViewEngineResult RunAgainstModuleViewEngines(ControllerContext controlle return result; } - - private static ModuleRequestResult GetCurrentModuleRequestResult(ControllerContext controllerContext) - { - if (controllerContext.HttpContext.HasModuleRequestResult()) - { - return controllerContext.HttpContext.GetModuleRequestResult(); - } - - return null; - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs index 74fa4a1c9cc..488367a5958 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs @@ -20,27 +20,27 @@ namespace DotNetNuke.Web.Mvc.Framework.Modules public class ModuleApplication { + internal static readonly string MvcVersion = GetMvcVersionString(); + protected const string ControllerMasterFormat = "~/DesktopModules/MVC/{0}/Views/{{1}}/{{0}}.cshtml"; protected const string SharedMasterFormat = "~/DesktopModules/MVC/{0}/Views/Shared/{{0}}.cshtml"; protected const string ControllerViewFormat = "~/DesktopModules/MVC/{0}/Views/{{1}}/{{0}}.cshtml"; protected const string SharedViewFormat = "~/DesktopModules/MVC/{0}/Views/Shared/{{0}}.cshtml"; protected const string ControllerPartialFormat = "~/DesktopModules/MVC/{0}/Views/{{1}}/{{0}}.cshtml"; protected const string SharedPartialFormat = "~/DesktopModules/MVC/{0}/Views/Shared/{{0}}.cshtml"; - - public RequestContext RequestContext { get; private set; } - - internal static readonly string MvcVersion = GetMvcVersionString(); private const string MvcVersionHeaderName = "X-AspNetMvc-Version"; - - private static bool DisableMvcResponseHeader { get; set; } + private readonly object _lock = new object(); private bool _initialized; - private readonly object _lock = new object(); public ModuleApplication() : this(null, false) { } + + public RequestContext RequestContext { get; private set; } + + private static bool DisableMvcResponseHeader { get; set; } public ModuleApplication(bool disableMvcResponseHeader) : this(null, disableMvcResponseHeader) @@ -73,27 +73,6 @@ public ModuleApplication(RequestContext requestContext, bool disableMvcResponseH public ViewEngineCollection ViewEngines { get; set; } - protected void EnsureInitialized() - { - // Double-check lock to wait for initialization - // TODO: Is there a better (preferably using events and waits) way to do this? - if (this._initialized) - { - return; - } - - lock (this._lock) - { - if (this._initialized) - { - return; - } - - this.Init(); - this._initialized = true; - } - } - public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) { this.EnsureInitialized(); @@ -148,14 +127,14 @@ public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) var result = moduleController.ResultOfLastExecute; // Return the final result - return new ModuleRequestResult - { - ActionResult = result, - ControllerContext = moduleController.ControllerContext, - ModuleActions = moduleController.ModuleActions, - ModuleContext = context.ModuleContext, - ModuleApplication = this, - }; + return new ModuleRequestResult + { + ActionResult = result, + ControllerContext = moduleController.ControllerContext, + ModuleActions = moduleController.ModuleActions, + ModuleContext = context.ModuleContext, + ModuleApplication = this, + }; } finally { @@ -179,18 +158,33 @@ protected internal virtual void Init() string.Format(CultureInfo.InvariantCulture, SharedPartialFormat, prefix), }; - this.ViewEngines.Add(new RazorViewEngine - { - MasterLocationFormats = masterFormats, - ViewLocationFormats = viewFormats, - PartialViewLocationFormats = viewFormats, - }); + this.ViewEngines.Add(new RazorViewEngine + { + MasterLocationFormats = masterFormats, + ViewLocationFormats = viewFormats, + PartialViewLocationFormats = viewFormats, + }); } - protected static string NormalizeFolderPath(string path) + protected void EnsureInitialized() { - // Remove leading and trailing slashes - return !string.IsNullOrEmpty(path) ? path.Trim('/') : path; + // Double-check lock to wait for initialization + // TODO: Is there a better (preferably using events and waits) way to do this? + if (this._initialized) + { + return; + } + + lock (this._lock) + { + if (this._initialized) + { + return; + } + + this.Init(); + this._initialized = true; + } } protected internal virtual void AddVersionHeader(HttpContextBase httpContext) @@ -201,12 +195,10 @@ protected internal virtual void AddVersionHeader(HttpContextBase httpContext) } } - private void RemoveOptionalRoutingParameters() + protected static string NormalizeFolderPath(string path) { - var rvd = this.RequestContext.RouteData.Values; - - // Ensure delegate is stateless - rvd.RemoveFromDictionary((entry) => entry.Value == UrlParameter.Optional); + // Remove leading and trailing slashes + return !string.IsNullOrEmpty(path) ? path.Trim('/') : path; } private static string GetMvcVersionString() @@ -216,5 +208,13 @@ private static string GetMvcVersionString() // medium trust. However, Assembly.FullName *is* accessible in medium trust. return new AssemblyName(typeof(MvcHandler).Assembly.FullName).Version.ToString(2); } + + private void RemoveOptionalRoutingParameters() + { + var rvd = this.RequestContext.RouteData.Values; + + // Ensure delegate is stateless + rvd.RemoveFromDictionary((entry) => entry.Value == UrlParameter.Optional); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs index 9f03afc134f..dfe25e6642f 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs @@ -59,17 +59,12 @@ public TabInfo ActivePage public Page DnnPage { get; set; } - internal HtmlHelper HtmlHelper { get; set; } - public string LocalResourceFile { get; set; } - public string LocalizeString(string key) - { - return Localization.GetString(key, this.LocalResourceFile); - } - public ModuleInstanceContext ModuleContext { get; set; } + internal HtmlHelper HtmlHelper { get; set; } + public PortalSettings PortalSettings { get { return (this.ModuleContext == null) ? null : this.ModuleContext.PortalSettings; } @@ -80,6 +75,11 @@ public RouteCollection RouteCollection get { return this.HtmlHelper.RouteCollection; } } + public string LocalizeString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } + public UserInfo User { get { return (this.PortalSettings == null) ? null : this.PortalSettings.UserInfo; } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs index 564c1c6c9e0..ef5d1819820 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs @@ -40,18 +40,18 @@ protected DnnHtmlHelper(HtmlHelper htmlHelper) this.ModuleContext = controller.ModuleContext; } + public ModuleInstanceContext ModuleContext { get; set; } + + public RouteCollection RouteCollection => this.HtmlHelper.RouteCollection; + + internal HtmlHelper HtmlHelper { get; set; } + public MvcHtmlString AntiForgeryToken() { ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); return new MvcHtmlString(string.Empty); } - internal HtmlHelper HtmlHelper { get; set; } - - public ModuleInstanceContext ModuleContext { get; set; } - - public RouteCollection RouteCollection => this.HtmlHelper.RouteCollection; - public dynamic ViewBag => this.HtmlHelper.ViewBag; public ViewContext ViewContext => this.HtmlHelper.ViewContext; diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelperOfT.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelperOfT.cs index d2016752271..9858e7b094e 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelperOfT.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelperOfT.cs @@ -19,10 +19,10 @@ public DnnHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContain { } - internal new HtmlHelper HtmlHelper => (HtmlHelper)base.HtmlHelper; - public new object ViewBag => this.HtmlHelper.ViewBag; public new ViewDataDictionary ViewData => this.HtmlHelper.ViewData; + + internal new HtmlHelper HtmlHelper => (HtmlHelper)base.HtmlHelper; } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs index 7c0c08a5c0c..74e7c975a90 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs @@ -88,15 +88,6 @@ public static MvcHtmlString LabelFor(this DnnHelper dnnH htmlAttributes); } - internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, string helpText = null, IDictionary htmlAttributes = null) - { - string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); - string resolvedHelpText = helpText ?? metadata.Description ?? metadata.Description ?? null; - string resolvedId = TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)); - - return LabelHelper(html, resolvedId, resolvedLabelText, resolvedHelpText, htmlAttributes); - } - public static MvcHtmlString LabelHelper(HtmlHelper html, string htmlFieldName, string labelText, string helpText = null, IDictionary htmlAttributes = null) { if (string.IsNullOrEmpty(labelText)) @@ -150,5 +141,14 @@ public static MvcHtmlString LabelHelper(HtmlHelper html, string htmlFieldName, s return new MvcHtmlString(divTag.ToString(TagRenderMode.Normal)); } + + internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, string helpText = null, IDictionary htmlAttributes = null) + { + string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); + string resolvedHelpText = helpText ?? metadata.Description ?? metadata.Description ?? null; + string resolvedId = TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)); + + return LabelHelper(html, resolvedId, resolvedLabelText, resolvedHelpText, htmlAttributes); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs index 3e0ce15fd5e..6b3e9acdaef 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs @@ -54,10 +54,10 @@ public DnnUrlHelper(ViewContext viewContext, RouteCollection routeCollection) this.ModuleContext = this._controller.ModuleContext; } - internal UrlHelper UrlHelper { get; set; } - public ModuleInstanceContext ModuleContext { get; set; } + internal UrlHelper UrlHelper { get; set; } + public virtual string Encode(string url) { return HttpUtility.UrlEncode(url); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlEditorExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlEditorExtensions.cs index 78c6b79d4a5..f0a13707144 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlEditorExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlEditorExtensions.cs @@ -37,7 +37,7 @@ public static MvcHtmlString Editor(this DnnHtmlHelper html, string expression) /// The HTML helper instance that this method extends.An expression that identifies the object that contains the properties to display.An anonymous object that can contain additional view data that will be merged into the instance that is created for the template. public static MvcHtmlString Editor(this DnnHtmlHelper html, string expression, object additionalViewData) { - return html.HtmlHelper.Editor(expression, additionalViewData); + return html.HtmlHelper.Editor(expression, additionalViewData); } /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLabelExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLabelExtensions.cs index cfdb63ae5e1..a0cfddb4005 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLabelExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/HtmlLabelExtensions.cs @@ -51,7 +51,7 @@ public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, st /// The HTML helper instance that this method extends.An expression that identifies the property to display.An object that contains the HTML attributes to set for the element. public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, object htmlAttributes) { - return html.HtmlHelper.Label(expression, htmlAttributes); + return html.HtmlHelper.Label(expression, htmlAttributes); } /// @@ -64,7 +64,7 @@ public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, ob /// The HTML helper instance that this method extends.An expression that identifies the property to display.An object that contains the HTML attributes to set for the element. public static MvcHtmlString Label(this DnnHtmlHelper html, string expression, IDictionary htmlAttributes) { - return html.HtmlHelper.Label(expression, htmlAttributes); + return html.HtmlHelper.Label(expression, htmlAttributes); } /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/HttpConfigurationExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/HttpConfigurationExtensions.cs index 7e918df0d09..c019e97257c 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/HttpConfigurationExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/HttpConfigurationExtensions.cs @@ -30,11 +30,6 @@ public static void AddTabAndModuleInfoProvider(this HttpConfiguration configurat providers.Enqueue(tabAndModuleInfoProvider); } - private static object InitValue(object o) - { - return new ConcurrentQueue(); - } - public static IEnumerable GetTabAndModuleInfoProviders(this HttpConfiguration configuration) { Requires.NotNull("configuration", configuration); @@ -49,5 +44,10 @@ public static IEnumerable GetTabAndModuleInfoProvider return providers.ToArray(); } + + private static object InitValue(object o) + { + return new ConcurrentQueue(); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs index 5e14bea2ccc..407d8448d4c 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs @@ -39,6 +39,40 @@ public MvcHostControl(string controlKey) this._controlKey = controlKey; } + public ModuleActionCollection ModuleActions { get; private set; } + + protected bool ExecuteModuleImmediately { get; set; } = true; + + protected void ExecuteModule() + { + try + { + HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current); + + var moduleExecutionEngine = this.GetModuleExecutionEngine(); + + this._result = moduleExecutionEngine.ExecuteModule(this.GetModuleRequestContext(httpContext)); + + this.ModuleActions = this.LoadActions(this._result); + + httpContext.SetModuleRequestResult(this._result); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (this.ExecuteModuleImmediately) + { + this.ExecuteModule(); + } + } + private ModuleApplication GetModuleApplication(DesktopModuleInfo desktopModule, RouteData defaultRouteData) { ModuleApplication moduleApplication = null; @@ -66,14 +100,14 @@ private ModuleApplication GetModuleApplication(DesktopModuleInfo desktopModule, var defaultActionName = (string)defaultRouteData.Values["action"]; var defaultNamespaces = (string[])defaultRouteData.DataTokens["namespaces"]; - moduleApplication = new ModuleApplication - { - DefaultActionName = defaultControllerName, - DefaultControllerName = defaultActionName, - DefaultNamespaces = defaultNamespaces, - ModuleName = desktopModule.ModuleName, - FolderPath = desktopModule.FolderName, - }; + moduleApplication = new ModuleApplication + { + DefaultActionName = defaultControllerName, + DefaultControllerName = defaultActionName, + DefaultNamespaces = defaultNamespaces, + ModuleName = desktopModule.ModuleName, + FolderPath = desktopModule.FolderName, + }; } return moduleApplication; @@ -130,14 +164,14 @@ private ModuleRequestContext GetModuleRequestContext(HttpContextBase httpContext routeData = ModuleRoutingProvider.Instance().GetRouteData(httpContext, control); } - var moduleRequestContext = new ModuleRequestContext - { - DnnPage = this.Page, - HttpContext = httpContext, - ModuleContext = this.ModuleContext, - ModuleApplication = moduleApplication, - RouteData = routeData, - }; + var moduleRequestContext = new ModuleRequestContext + { + DnnPage = this.Page, + HttpContext = httpContext, + ModuleContext = this.ModuleContext, + ModuleApplication = moduleApplication, + RouteData = routeData, + }; return moduleRequestContext; } @@ -173,40 +207,6 @@ private MvcHtmlString RenderModule(ModuleRequestResult moduleResult) return moduleOutput; } - protected void ExecuteModule() - { - try - { - HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current); - - var moduleExecutionEngine = this.GetModuleExecutionEngine(); - - this._result = moduleExecutionEngine.ExecuteModule(this.GetModuleRequestContext(httpContext)); - - this.ModuleActions = this.LoadActions(this._result); - - httpContext.SetModuleRequestResult(this._result); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - public ModuleActionCollection ModuleActions { get; private set; } - - protected bool ExecuteModuleImmediately { get; set; } = true; - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (this.ExecuteModuleImmediately) - { - this.ExecuteModule(); - } - } - protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs index 3cb42894e77..423c8154e8a 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs @@ -39,6 +39,10 @@ public void Init(HttpApplication context) ComponentFactory.RegisterComponentInstance(new ModuleExecutionEngine()); context.BeginRequest += InitDnn; } + + public void Dispose() + { + } private static void InitDnn(object sender, EventArgs e) { @@ -48,10 +52,6 @@ private static void InitDnn(object sender, EventArgs e) Initialize.Init(app); } } - - public void Dispose() - { - } /// /// Suppress X-Frame-Options Header if there is configuration specified in web.config for it. diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs index 31cc29d76d1..f6a4a16feeb 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs @@ -18,29 +18,36 @@ namespace DotNetNuke.Web.Mvc.Routing internal static class HttpRequestExtensions { + private delegate bool TryMethod(ITabAndModuleInfoProvider provider, HttpRequestBase request, out T output); + public static int FindTabId(this HttpRequestBase request) { return IterateTabAndModuleInfoProviders(request, TryFindTabId, -1); } - private static bool TryFindTabId(ITabAndModuleInfoProvider provider, HttpRequestBase request, out int output) + public static ModuleInfo FindModuleInfo(this HttpRequestBase request) { - return provider.TryFindTabId(request, out output); + return IterateTabAndModuleInfoProviders(request, TryFindModuleInfo, null); } - public static ModuleInfo FindModuleInfo(this HttpRequestBase request) + public static int FindModuleId(this HttpRequestBase request) { - return IterateTabAndModuleInfoProviders(request, TryFindModuleInfo, null); + return IterateTabAndModuleInfoProviders(request, TryFindModuleId, -1); } - private static bool TryFindModuleInfo(ITabAndModuleInfoProvider provider, HttpRequestBase request, out ModuleInfo output) + public static string GetIPAddress(HttpRequestBase request) { - return provider.TryFindModuleInfo(request, out output); + return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(request); } - public static int FindModuleId(this HttpRequestBase request) + private static bool TryFindTabId(ITabAndModuleInfoProvider provider, HttpRequestBase request, out int output) { - return IterateTabAndModuleInfoProviders(request, TryFindModuleId, -1); + return provider.TryFindTabId(request, out output); + } + + private static bool TryFindModuleInfo(ITabAndModuleInfoProvider provider, HttpRequestBase request, out ModuleInfo output) + { + return provider.TryFindModuleInfo(request, out output); } private static bool TryFindModuleId(ITabAndModuleInfoProvider provider, HttpRequestBase request, out int output) @@ -48,8 +55,6 @@ private static bool TryFindModuleId(ITabAndModuleInfoProvider provider, HttpRequ return provider.TryFindModuleId(request, out output); } - private delegate bool TryMethod(ITabAndModuleInfoProvider provider, HttpRequestBase request, out T output); - private static T IterateTabAndModuleInfoProviders(HttpRequestBase request, TryMethod func, T fallback) { var providers = GlobalConfiguration.Configuration.GetTabAndModuleInfoProviders(); @@ -65,10 +70,5 @@ private static T IterateTabAndModuleInfoProviders(HttpRequestBase request, Tr return fallback; } - - public static string GetIPAddress(HttpRequestBase request) - { - return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(request); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs index 39cf9220875..24678e46e6f 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs @@ -15,6 +15,15 @@ public static class MvcRouteExtensions { private const string NamespaceKey = "namespaces"; private const string NameKey = "name"; + + /// + /// Get the name of the route. + /// + /// Route name. + public static string GetName(this Route route) + { + return (string)route.DataTokens[NameKey]; + } internal static void SetNameSpaces(this Route route, string[] namespaces) { @@ -34,14 +43,5 @@ internal static void SetName(this Route route, string name) { route.DataTokens[NameKey] = name; } - - /// - /// Get the name of the route. - /// - /// Route name. - public static string GetName(this Route route) - { - return (string)route.DataTokens[NameKey]; - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs index e107da52d0a..e7cda2d1251 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs @@ -94,6 +94,11 @@ public void RegisterRoutes() Logger.TraceFormat("Registered a total of {0} routes", this._routes.Count); } + internal static bool IsValidServiceRouteMapper(Type t) + { + return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IMvcRouteMapper).IsAssignableFrom(t); + } + private static bool IsTracingEnabled() { var configValue = Config.GetSetting("EnableServicesFrameworkTracing"); @@ -101,6 +106,33 @@ private static bool IsTracingEnabled() return !string.IsNullOrEmpty(configValue) && Convert.ToBoolean(configValue); } + private static void RegisterSystemRoutes() + { + // _routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + } + + private static Route MapRouteWithNamespace(string name, string url, object defaults, object constraints, string[] namespaces) + { + var route = new Route(url, new DnnMvcRouteHandler()) + { + Defaults = CreateRouteValueDictionaryUncached(defaults), + Constraints = CreateRouteValueDictionaryUncached(constraints), + }; + if (route.DataTokens == null) + { + route.DataTokens = new RouteValueDictionary(); + } + + ConstraintValidation.Validate(route); + if ((namespaces != null) && (namespaces.Length > 0)) + { + route.SetNameSpaces(namespaces); + } + + route.SetName(name); + return route; + } + private void LocateServicesAndMapRoutes() { RegisterSystemRoutes(); @@ -126,11 +158,6 @@ private void ClearCachedRouteData() this._portalAliasMvcRouteManager.ClearCachedData(); } - private static void RegisterSystemRoutes() - { - // _routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); - } - private IEnumerable GetServiceRouteMappers() { IEnumerable types = this.GetAllServiceRouteMapperTypes(); @@ -161,33 +188,6 @@ private IEnumerable GetAllServiceRouteMapperTypes() return this.TypeLocator.GetAllMatchingTypes(IsValidServiceRouteMapper); } - internal static bool IsValidServiceRouteMapper(Type t) - { - return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IMvcRouteMapper).IsAssignableFrom(t); - } - - private static Route MapRouteWithNamespace(string name, string url, object defaults, object constraints, string[] namespaces) - { - var route = new Route(url, new DnnMvcRouteHandler()) - { - Defaults = CreateRouteValueDictionaryUncached(defaults), - Constraints = CreateRouteValueDictionaryUncached(constraints), - }; - if (route.DataTokens == null) - { - route.DataTokens = new RouteValueDictionary(); - } - - ConstraintValidation.Validate(route); - if ((namespaces != null) && (namespaces.Length > 0)) - { - route.SetNameSpaces(namespaces); - } - - route.SetName(name); - return route; - } - private static RouteValueDictionary CreateRouteValueDictionaryUncached(object values) { var dictionary = values as IDictionary; diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs index 2edf724d2b9..9212f6bb1cf 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs @@ -44,23 +44,6 @@ public string GetRouteName(string moduleFolderName, string routeName, PortalAlia return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); } - private static string GeneratePrefixString(int count) - { - if (count == 0) - { - return string.Empty; - } - - var prefix = string.Empty; - - for (var i = count - 1; i >= 0; i--) - { - prefix = "{prefix" + i + "}/" + prefix; - } - - return prefix; - } - public RouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) { var allRouteValues = new RouteValueDictionary(routeValues); @@ -90,6 +73,23 @@ public string GetRouteUrl(string moduleFolderName, string url, int count) return $"{GeneratePrefixString(count)}DesktopModules/MVC/{moduleFolderName}/{url}"; } + private static string GeneratePrefixString(int count) + { + if (count == 0) + { + return string.Empty; + } + + var prefix = string.Empty; + + for (var i = count - 1; i >= 0; i--) + { + prefix = "{prefix" + i + "}/" + prefix; + } + + return prefix; + } + public void ClearCachedData() { this._prefixCounts = null; @@ -133,13 +133,6 @@ private static int CalcAliasPrefixCount(string alias) return alias.Count(c => c == '/'); } - private IEnumerable StripApplicationPath(IEnumerable aliases) - { - var appPath = TestableGlobals.Instance.ApplicationPath; - - return string.IsNullOrEmpty(appPath) ? aliases : StripApplicationPathIterable(aliases, appPath); - } - private static IEnumerable StripApplicationPathIterable(IEnumerable aliases, string appPath) { foreach (var alias in aliases) @@ -156,5 +149,12 @@ private static IEnumerable StripApplicationPathIterable(IEnumerable StripApplicationPath(IEnumerable aliases) + { + var appPath = TestableGlobals.Instance.ApplicationPath; + + return string.IsNullOrEmpty(appPath) ? aliases : StripApplicationPathIterable(aliases, appPath); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs index c776d37c615..d814f713543 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs @@ -19,8 +19,6 @@ namespace DotNetNuke.Web.Mvc.Routing public class StandardModuleRoutingProvider : ModuleRoutingProvider { - protected INavigationManager NavigationManager { get; } - private const string ExcludedQueryStringParams = "tabid,mid,ctl,language,popup,action,controller"; private const string ExcludedRouteValues = "mid,ctl,popup"; @@ -29,6 +27,8 @@ public StandardModuleRoutingProvider() this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } + public override string GenerateUrl(RouteValueDictionary routeValues, ModuleInstanceContext moduleContext) { // Look for a module control diff --git a/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs index 71899ff9a7c..92940fb6b28 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs @@ -16,10 +16,10 @@ namespace DotNetNuke.Web.Mvc public sealed class StandardTabAndModuleInfoProvider : ITabAndModuleInfoProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); - private const string ModuleIdKey = "ModuleId"; private const string TabIdKey = "TabId"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); private const string MonikerQueryKey = "Moniker"; private const string MonikerHeaderKey = "X-DNN-MONIKER"; private const string MonikerSettingsKey = "Moniker"; @@ -29,6 +29,23 @@ public bool TryFindTabId(HttpRequestBase request, out int tabId) return TryFindTabId(request, out tabId, true); } + public bool TryFindModuleId(HttpRequestBase request, out int moduleId) + { + return TryFindModuleId(request, out moduleId, true); + } + + public bool TryFindModuleInfo(HttpRequestBase request, out ModuleInfo moduleInfo) + { + int tabId, moduleId; + if (TryFindTabId(request, out tabId, false) && TryFindModuleId(request, out moduleId, false)) + { + moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); + return moduleInfo != null; + } + + return TryFindByMoniker(request, out moduleInfo); + } + private static bool TryFindTabId(HttpRequestBase request, out int tabId, bool tryMoniker) { tabId = FindInt(request, TabIdKey); @@ -50,11 +67,6 @@ private static bool TryFindTabId(HttpRequestBase request, out int tabId, bool tr return false; } - public bool TryFindModuleId(HttpRequestBase request, out int moduleId) - { - return TryFindModuleId(request, out moduleId, true); - } - private static bool TryFindModuleId(HttpRequestBase request, out int moduleId, bool tryMoniker) { moduleId = FindInt(request, ModuleIdKey); @@ -76,18 +88,6 @@ private static bool TryFindModuleId(HttpRequestBase request, out int moduleId, b return false; } - public bool TryFindModuleInfo(HttpRequestBase request, out ModuleInfo moduleInfo) - { - int tabId, moduleId; - if (TryFindTabId(request, out tabId, false) && TryFindModuleId(request, out moduleId, false)) - { - moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); - return moduleInfo != null; - } - - return TryFindByMoniker(request, out moduleInfo); - } - private static int FindInt(HttpRequestBase requestBase, string key) { string value = null; diff --git a/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs b/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs index 2966bd521c8..434444bdbf5 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs @@ -16,6 +16,13 @@ public abstract class DotNetNukeWebPage : WebPageBase { private dynamic _model; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + public dynamic Model + { + get { return this._model ?? (this._model = this.PageContext.Model); } + set { this._model = value; } + } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected internal DnnHelper Dnn { get; internal set; } @@ -33,13 +40,6 @@ protected override void ConfigurePage(WebPageBase parentPage) // Child pages need to get their context from the Parent this.Context = parentPage.Context; } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public dynamic Model - { - get { return this._model ?? (this._model = this.PageContext.Model); } - set { this._model = value; } - } } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] diff --git a/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs b/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs index d0932dc8d3b..2904da99fde 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs @@ -14,8 +14,6 @@ namespace DotNetNuke.Web.Razor.Helpers public class UrlHelper { private readonly ModuleInstanceContext _context; - - protected INavigationManager NavigationManager { get; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public UrlHelper(ModuleInstanceContext context) @@ -23,6 +21,8 @@ public UrlHelper(ModuleInstanceContext context) this._context = context; this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + + protected INavigationManager NavigationManager { get; } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public string NavigateToControl() diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs index 1e73db9a580..cca41cad8d8 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs @@ -44,6 +44,9 @@ public RazorEngine(string razorScriptFile, ModuleInstanceContext moduleContext, } } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + public DotNetNukeWebPage Webpage { get; set; } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string RazorScriptFile { get; set; } @@ -53,9 +56,6 @@ public RazorEngine(string razorScriptFile, ModuleInstanceContext moduleContext, [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string LocalResourceFile { get; set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public DotNetNukeWebPage Webpage { get; set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected HttpContextBase HttpContext { diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs index 9fc757a026e..22effdb2320 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs @@ -17,19 +17,33 @@ public class RazorHostControl : ModuleControlBase, IActionable { private readonly string _razorScriptFile; + private RazorEngine _engine; + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public RazorHostControl(string scriptFile) { this._razorScriptFile = scriptFile; } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + public ModuleActionCollection ModuleActions + { + get + { + if (this.Engine.Webpage is IActionable) + { + return (this.Engine.Webpage as IActionable).ModuleActions; + } + + return new ModuleActionCollection(); + } + } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected virtual string RazorScriptFile { get { return this._razorScriptFile; } } - - private RazorEngine _engine; private RazorEngine Engine { @@ -49,26 +63,12 @@ protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (! string.IsNullOrEmpty(this.RazorScriptFile)) + if (!string.IsNullOrEmpty(this.RazorScriptFile)) { var writer = new StringWriter(); this.Engine.Render(writer); this.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(writer.ToString()))); } } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public ModuleActionCollection ModuleActions - { - get - { - if (this.Engine.Webpage is IActionable) - { - return (this.Engine.Webpage as IActionable).ModuleActions; - } - - return new ModuleActionCollection(); - } - } } } diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs index f67f0ce66cd..2d6ca46ba70 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs @@ -22,12 +22,12 @@ protected virtual string RazorScriptFile var fileRoot = Path.GetFileNameWithoutExtension(this.AppRelativeVirtualPath); var scriptFile = scriptFolder + "_" + fileRoot + ".cshtml"; - if (! File.Exists(this.Server.MapPath(scriptFile))) + if (!File.Exists(this.Server.MapPath(scriptFile))) { // Try VB (vbhtml) scriptFile = scriptFolder + "_" + fileRoot + ".vbhtml"; - if (! File.Exists(this.Server.MapPath(scriptFile))) + if (!File.Exists(this.Server.MapPath(scriptFile))) { // Return "" scriptFile = string.Empty; @@ -44,7 +44,7 @@ protected override void OnPreRender(EventArgs e) base.OnPreRender(e); try { - if (! string.IsNullOrEmpty(this.RazorScriptFile)) + if (!string.IsNullOrEmpty(this.RazorScriptFile)) { var razorEngine = new RazorEngine(this.RazorScriptFile, this.ModuleContext, this.LocalResourceFile); var writer = new StringWriter(); diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs index f08c5e10ff2..09048d61bd5 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs @@ -18,6 +18,12 @@ public abstract class AuthMessageHandlerBase : DelegatingHandler { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthMessageHandlerBase)); + protected AuthMessageHandlerBase(bool includeByDefault, bool forceSsl) + { + this.DefaultInclude = includeByDefault; + this.ForceSsl = forceSsl; + } + public abstract string AuthScheme { get; } public virtual bool BypassAntiForgeryToken => false; @@ -26,24 +32,6 @@ public abstract class AuthMessageHandlerBase : DelegatingHandler public bool ForceSsl { get; } - protected AuthMessageHandlerBase(bool includeByDefault, bool forceSsl) - { - this.DefaultInclude = includeByDefault; - this.ForceSsl = forceSsl; - } - - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - var response = this.OnInboundRequest(request, cancellationToken); - if (response != null) - { - response.RequestMessage = response.RequestMessage ?? request; // if someone returns new HttpResponseMessage(), fill in the requestMessage for other handlers in the chain - return Task.Factory.StartNew(() => response, cancellationToken); - } - - return base.SendAsync(request, cancellationToken).ContinueWith(x => this.OnOutboundResponse(x.Result, cancellationToken), cancellationToken); - } - /// /// A chance to process inbound requests. /// @@ -66,20 +54,16 @@ public virtual HttpResponseMessage OnOutboundResponse(HttpResponseMessage respon return response; } - protected bool NeedsAuthentication(HttpRequestMessage request) + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - if (this.MustEnforceSslInRequest(request)) - { - return !Thread.CurrentPrincipal.Identity.IsAuthenticated; - } - - if (Logger.IsTraceEnabled) + var response = this.OnInboundRequest(request, cancellationToken); + if (response != null) { - Logger.Trace($"{this.AuthScheme}: Validating request vs. SSL mode ({this.ForceSsl}) failed. "); + response.RequestMessage = response.RequestMessage ?? request; // if someone returns new HttpResponseMessage(), fill in the requestMessage for other handlers in the chain + return Task.Factory.StartNew(() => response, cancellationToken); } - // will let callers to return without authenticating the user - return false; + return base.SendAsync(request, cancellationToken).ContinueWith(x => this.OnOutboundResponse(x.Result, cancellationToken), cancellationToken); } protected static bool IsXmlHttpRequest(HttpRequestMessage request) @@ -95,6 +79,28 @@ protected static bool IsXmlHttpRequest(HttpRequestMessage request) value.Equals("XmlHttpRequest", StringComparison.InvariantCultureIgnoreCase); } + protected static void SetCurrentPrincipal(IPrincipal principal, HttpRequestMessage request) + { + Thread.CurrentPrincipal = principal; + request.GetHttpContext().User = principal; + } + + protected bool NeedsAuthentication(HttpRequestMessage request) + { + if (this.MustEnforceSslInRequest(request)) + { + return !Thread.CurrentPrincipal.Identity.IsAuthenticated; + } + + if (Logger.IsTraceEnabled) + { + Logger.Trace($"{this.AuthScheme}: Validating request vs. SSL mode ({this.ForceSsl}) failed. "); + } + + // will let callers to return without authenticating the user + return false; + } + /// /// Validated the setting of the instane against the HTTP(S) request. /// @@ -103,11 +109,5 @@ private bool MustEnforceSslInRequest(HttpRequestMessage request) { return !this.ForceSsl || request.RequestUri.Scheme.Equals("HTTPS", StringComparison.InvariantCultureIgnoreCase); } - - protected static void SetCurrentPrincipal(IPrincipal principal, HttpRequestMessage request) - { - Thread.CurrentPrincipal = principal; - request.GetHttpContext().User = principal; - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs index 672397df148..21b9b462621 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs @@ -19,14 +19,14 @@ namespace DotNetNuke.Web.Api.Auth public class BasicAuthMessageHandler : AuthMessageHandlerBase { - public override string AuthScheme => "Basic"; - private readonly Encoding _encoding = Encoding.GetEncoding("iso-8859-1"); public BasicAuthMessageHandler(bool includeByDefault, bool forceSsl) : base(includeByDefault, forceSsl) { } + + public override string AuthScheme => "Basic"; public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) { diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs index ea70c5627ba..d903da4cb50 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs @@ -18,12 +18,12 @@ namespace DotNetNuke.Web.Api.Auth public class DigestAuthMessageHandler : AuthMessageHandlerBase { - public override string AuthScheme => DigestAuthentication.AuthenticationScheme; - public DigestAuthMessageHandler(bool includeByDefault, bool forceSsl) : base(includeByDefault, forceSsl) { } + + public override string AuthScheme => DigestAuthentication.AuthenticationScheme; public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) { @@ -57,17 +57,6 @@ public override HttpResponseMessage OnOutboundResponse(HttpResponseMessage respo return base.OnOutboundResponse(response, cancellationToken); } - private void AddStaleWwwAuthenticateHeader(HttpResponseMessage response) - { - this.AddWwwAuthenticateHeader(response, true); - } - - private void AddWwwAuthenticateHeader(HttpResponseMessage response, bool isStale = false) - { - var value = string.Format("realm=\"DNNAPI\", nonce=\"{0}\", opaque=\"0000000000000000\", stale={1}, algorithm=MD5, qop=\"auth\"", CreateNewNonce(), isStale); - response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(this.AuthScheme, value)); - } - private static string CreateNewNonce() { DateTime nonceTime = DateTime.Now + TimeSpan.FromMinutes(1); @@ -103,6 +92,17 @@ private static bool TryToAuthenticate(HttpRequestMessage request, int portalId) return false; } + private void AddStaleWwwAuthenticateHeader(HttpResponseMessage response) + { + this.AddWwwAuthenticateHeader(response, true); + } + + private void AddWwwAuthenticateHeader(HttpResponseMessage response, bool isStale = false) + { + var value = string.Format("realm=\"DNNAPI\", nonce=\"{0}\", opaque=\"0000000000000000\", stale={1}, algorithm=MD5, qop=\"auth\"", CreateNewNonce(), isStale); + response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(this.AuthScheme, value)); + } + private bool SupportsDigestAuth(HttpRequestMessage request) { return !IsXmlHttpRequest(request) && MembershipProviderConfig.PasswordRetrievalEnabled; diff --git a/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs b/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs index ebb186ae77b..e98ec9a7d49 100644 --- a/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs @@ -15,6 +15,11 @@ namespace DotNetNuke.Web.Api public abstract class AuthFilterBase : IAuthorizationFilter { + /// + /// Gets a value indicating whether more than one instance of the indicated attribute can be specified for a single program element. + /// + public abstract bool AllowMultiple { get; } + /// /// Tests if the request passes the authorization requirements. /// @@ -22,27 +27,6 @@ public abstract class AuthFilterBase : IAuthorizationFilter /// True when authorization is succesful. public abstract bool IsAuthorized(AuthFilterContext context); - /// - /// Co-ordinates check of authorization and handles Auth failure. Should rarely be overridden. - /// - /// - protected virtual void OnAuthorization(HttpActionContext actionContext) - { - Requires.NotNull("actionContext", actionContext); - - const string failureMessage = "Authorization has been denied for this request."; - var authFilterContext = new AuthFilterContext(actionContext, failureMessage); - if (!this.IsAuthorized(authFilterContext)) - { - authFilterContext.HandleUnauthorizedRequest(); - } - } - - /// - /// Gets a value indicating whether more than one instance of the indicated attribute can be specified for a single program element. - /// - public abstract bool AllowMultiple { get; } - Task IAuthorizationFilter.ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func> continuation) { Requires.NotNull("actionContext", actionContext); @@ -68,5 +52,21 @@ Task IAuthorizationFilter.ExecuteAuthorizationFilterAsync(H return continuation(); } + + /// + /// Co-ordinates check of authorization and handles Auth failure. Should rarely be overridden. + /// + /// + protected virtual void OnAuthorization(HttpActionContext actionContext) + { + Requires.NotNull("actionContext", actionContext); + + const string failureMessage = "Authorization has been denied for this request."; + var authFilterContext = new AuthFilterContext(actionContext, failureMessage); + if (!this.IsAuthorized(authFilterContext)) + { + authFilterContext.HandleUnauthorizedRequest(); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs b/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs index 9ad76ea812b..117d098c114 100644 --- a/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs @@ -14,6 +14,13 @@ namespace DotNetNuke.Web.Api public abstract class AuthorizeAttributeBase : AuthorizationFilterAttribute { + public static bool IsAnonymousAttributePresent(HttpActionContext actionContext) + { + return actionContext.ActionDescriptor.GetCustomAttributes().Any() + || (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().Any() + && actionContext.ActionDescriptor.GetCustomAttributes().All(t => t is SupportedModulesAttribute)); + } + /// /// Tests if the request passes the authorization requirements. /// @@ -51,12 +58,5 @@ protected virtual bool SkipAuthorization(HttpActionContext actionContext) { return IsAnonymousAttributePresent(actionContext); } - - public static bool IsAnonymousAttributePresent(HttpActionContext actionContext) - { - return actionContext.ActionDescriptor.GetCustomAttributes().Any() - || (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().Any() - && actionContext.ActionDescriptor.GetCustomAttributes().All(t => t is SupportedModulesAttribute)); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs b/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs index 958820268c8..f574289fb31 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs @@ -21,11 +21,6 @@ protected DnnApiController() this._activeModule = new Lazy(this.InitModuleInfo); } - private ModuleInfo InitModuleInfo() - { - return this.Request.FindModuleInfo(); - } - /// /// Gets portalSettings for the current portal. /// @@ -53,5 +48,10 @@ public ModuleInfo ActiveModule { get { return this._activeModule.Value; } } + + private ModuleInfo InitModuleInfo() + { + return this.Request.FindModuleInfo(); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs index f9d17ae56f2..81674351f8d 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs @@ -14,6 +14,10 @@ namespace DotNetNuke.Web.Api public sealed class DnnAuthorizeAttribute : AuthorizeAttributeBase, IOverrideDefaultAuthLevel { + private static readonly List DefaultAuthTypes = new List(); + + private static readonly string[] EmptyArray = new string[0]; + private string _staticRoles; private string[] _staticRolesSplit = new string[0]; @@ -23,16 +27,6 @@ public sealed class DnnAuthorizeAttribute : AuthorizeAttributeBase, IOverrideDef private string _authTypes; private string[] _authTypesSplit = new string[0]; - private static readonly List DefaultAuthTypes = new List(); - - internal static void AppendToDefaultAuthTypes(string authType) - { - if (!string.IsNullOrEmpty(authType)) - { - DefaultAuthTypes.Add(authType.Trim()); - } - } - /// /// Gets or sets the authorized roles (separated by comma). /// @@ -75,6 +69,14 @@ public string AuthTypes } } + internal static void AppendToDefaultAuthTypes(string authType) + { + if (!string.IsNullOrEmpty(authType)) + { + DefaultAuthTypes.Add(authType.Trim()); + } + } + public override bool IsAuthorized(AuthFilterContext context) { Requires.NotNull("context", context); @@ -118,8 +120,6 @@ public override bool IsAuthorized(AuthFilterContext context) return true; } - - private static readonly string[] EmptyArray = new string[0]; private static string[] SplitString(string original) { diff --git a/DNN Platform/DotNetNuke.Web/Api/HttpConfigurationExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/HttpConfigurationExtensions.cs index 14392696449..b9b92643563 100644 --- a/DNN Platform/DotNetNuke.Web/Api/HttpConfigurationExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/HttpConfigurationExtensions.cs @@ -31,11 +31,6 @@ public static void AddTabAndModuleInfoProvider(this HttpConfiguration configurat providers.Enqueue(tabAndModuleInfoProvider); } - private static object InitValue(object o) - { - return new ConcurrentQueue(); - } - public static IEnumerable GetTabAndModuleInfoProviders(this HttpConfiguration configuration) { Requires.NotNull("configuration", configuration); @@ -50,5 +45,10 @@ public static IEnumerable GetTabAndModuleInfoProvider return providers.ToArray(); } + + private static object InitValue(object o) + { + return new ConcurrentQueue(); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs index 4188e392bc7..c6e558b6c2c 100644 --- a/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs @@ -12,29 +12,44 @@ namespace DotNetNuke.Web.Api public static class HttpRequestMessageExtensions { + private delegate bool TryMethod(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out T output); + public static int FindTabId(this HttpRequestMessage request) { return IterateTabAndModuleInfoProviders(request, TryFindTabId, -1); } - private static bool TryFindTabId(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out int output) + public static ModuleInfo FindModuleInfo(this HttpRequestMessage request) { - return provider.TryFindTabId(request, out output); + return IterateTabAndModuleInfoProviders(request, TryFindModuleInfo, null); } - public static ModuleInfo FindModuleInfo(this HttpRequestMessage request) + public static int FindModuleId(this HttpRequestMessage request) { - return IterateTabAndModuleInfoProviders(request, TryFindModuleInfo, null); + return IterateTabAndModuleInfoProviders(request, TryFindModuleId, -1); } - private static bool TryFindModuleInfo(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out ModuleInfo output) + public static HttpContextBase GetHttpContext(this HttpRequestMessage request) { - return provider.TryFindModuleInfo(request, out output); + object context; + request.Properties.TryGetValue("MS_HttpContext", out context); + + return context as HttpContextBase; } - public static int FindModuleId(this HttpRequestMessage request) + public static string GetIPAddress(this HttpRequestMessage request) { - return IterateTabAndModuleInfoProviders(request, TryFindModuleId, -1); + return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(GetHttpContext(request).Request); + } + + private static bool TryFindTabId(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out int output) + { + return provider.TryFindTabId(request, out output); + } + + private static bool TryFindModuleInfo(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out ModuleInfo output) + { + return provider.TryFindModuleInfo(request, out output); } private static bool TryFindModuleId(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out int output) @@ -42,8 +57,6 @@ private static bool TryFindModuleId(ITabAndModuleInfoProvider provider, HttpRequ return provider.TryFindModuleId(request, out output); } - private delegate bool TryMethod(ITabAndModuleInfoProvider provider, HttpRequestMessage request, out T output); - private static T IterateTabAndModuleInfoProviders(HttpRequestMessage request, TryMethod func, T fallback) { var providers = request.GetConfiguration().GetTabAndModuleInfoProviders(); @@ -59,18 +72,5 @@ private static T IterateTabAndModuleInfoProviders(HttpRequestMessage request, return fallback; } - - public static HttpContextBase GetHttpContext(this HttpRequestMessage request) - { - object context; - request.Properties.TryGetValue("MS_HttpContext", out context); - - return context as HttpContextBase; - } - - public static string GetIPAddress(this HttpRequestMessage request) - { - return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(GetHttpContext(request).Request); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs index 7c1d3fe7040..38e05f87b8b 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs @@ -21,6 +21,14 @@ internal class DigestAuthentication private readonly int _portalId; private readonly string _ipAddress; + public DigestAuthentication(DigestAuthenticationRequest request, int portalId, string ipAddress) + { + this._request = request; + this._portalId = portalId; + this._ipAddress = ipAddress ?? string.Empty; + this.AuthenticateRequest(); + } + public DigestAuthenticationRequest Request { get { return this._request; } @@ -31,19 +39,52 @@ public DigestAuthenticationRequest Request public bool IsNonceStale { get; private set; } + public IPrincipal User { get; private set; } + public string CalculateHashedDigest() { return CreateMd5HashBinHex(this.GenerateUnhashedDigest()); } - public IPrincipal User { get; private set; } + private static string CreateMd5HashBinHex(string val) + { + // Services.Logging.LoggingController.SimpleLog(String.Format("Creating Hash for {0}", val)) + // Services.Logging.LoggingController.SimpleLog(String.Format("Back and forth: {0}", Encoding.Default.GetString(Encoding.Default.GetBytes(val)))) + byte[] bha1 = Md5.ComputeHash(Encoding.Default.GetBytes(val)); + string ha1 = string.Empty; + for (int i = 0; i <= 15; i++) + { + ha1 += string.Format("{0:x02}", bha1[i]); + } + + return ha1; + } - public DigestAuthentication(DigestAuthenticationRequest request, int portalId, string ipAddress) + // the nonce is created in DotNetNuke.Web.Api.DigestAuthMessageHandler + private static bool IsNonceValid(string nonce) { - this._request = request; - this._portalId = portalId; - this._ipAddress = ipAddress ?? string.Empty; - this.AuthenticateRequest(); + DateTime expireTime; + + int numPadChars = nonce.Length % 4; + if (numPadChars > 0) + { + numPadChars = 4 - numPadChars; + } + + string newNonce = nonce.PadRight(nonce.Length + numPadChars, '='); + + try + { + byte[] decodedBytes = Convert.FromBase64String(newNonce); + string expireStr = Encoding.Default.GetString(decodedBytes); + expireTime = DateTime.Parse(expireStr); + } + catch (FormatException) + { + return false; + } + + return DateTime.Now <= expireTime; } private void AuthenticateRequest() @@ -51,7 +92,7 @@ private void AuthenticateRequest() this._password = this.GetPassword(this.Request); if (this._password != null) { - this.IsNonceStale = ! IsNonceValid(this._request.RequestParams["nonce"]); + this.IsNonceStale = !IsNonceValid(this._request.RequestParams["nonce"]); // Services.Logging.LoggingController.SimpleLog(String.Format("Request hash: {0} - Response Hash: {1}", _request.RequestParams("response"), HashedDigest)) if ((!this.IsNonceStale) && this._request.RequestParams["response"] == this.CalculateHashedDigest()) @@ -106,46 +147,5 @@ private string GenerateUnhashedDigest() // Services.Logging.LoggingController.SimpleLog(A1, HA1, A2, HA2, unhashedDigest) return unhashedDigest; } - - private static string CreateMd5HashBinHex(string val) - { - // Services.Logging.LoggingController.SimpleLog(String.Format("Creating Hash for {0}", val)) - // Services.Logging.LoggingController.SimpleLog(String.Format("Back and forth: {0}", Encoding.Default.GetString(Encoding.Default.GetBytes(val)))) - byte[] bha1 = Md5.ComputeHash(Encoding.Default.GetBytes(val)); - string ha1 = string.Empty; - for (int i = 0; i <= 15; i++) - { - ha1 += string.Format("{0:x02}", bha1[i]); - } - - return ha1; - } - - // the nonce is created in DotNetNuke.Web.Api.DigestAuthMessageHandler - private static bool IsNonceValid(string nonce) - { - DateTime expireTime; - - int numPadChars = nonce.Length % 4; - if (numPadChars > 0) - { - numPadChars = 4 - numPadChars; - } - - string newNonce = nonce.PadRight(nonce.Length + numPadChars, '='); - - try - { - byte[] decodedBytes = Convert.FromBase64String(newNonce); - string expireStr = Encoding.Default.GetString(decodedBytes); - expireTime = DateTime.Parse(expireStr); - } - catch (FormatException) - { - return false; - } - - return DateTime.Now <= expireTime; - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnContextMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnContextMessageHandler.cs index 2c4e3b5fd4d..db0844c7c22 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnContextMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnContextMessageHandler.cs @@ -28,6 +28,11 @@ protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, return request; } + protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) + { + return response; + } + private static void SetThreadCulture(PortalSettings portalSettings) { CultureInfo pageLocale = TestableLocalization.Instance.GetPageLocale(portalSettings); @@ -98,10 +103,5 @@ private static void ValidateTabAndModuleContext(HttpRequestMessage request, int } } } - - protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) - { - return response; - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs index b648eb20cb8..a9b9ec69f9e 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs @@ -147,6 +147,11 @@ public void RegisterRoutes() Logger.TraceFormat("Registered a total of {0} routes", this._routes.Count); } + internal static bool IsValidServiceRouteMapper(Type t) + { + return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IServiceRouteMapper).IsAssignableFrom(t); + } + private static void RegisterAuthenticationHandlers() { // authentication message handlers from web.config file @@ -274,11 +279,6 @@ private IEnumerable GetAllServiceRouteMapperTypes() return this.TypeLocator.GetAllMatchingTypes(IsValidServiceRouteMapper); } - internal static bool IsValidServiceRouteMapper(Type t) - { - return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IServiceRouteMapper).IsAssignableFrom(t); - } - private Route MapHttpRouteWithNamespace(string name, string url, object defaults, object constraints, string[] namespaces) { Route route = this._routes.MapHttpRoute(name, url, defaults, constraints); diff --git a/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs b/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs index b0f0e37ae94..85135b250c2 100644 --- a/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs @@ -19,6 +19,16 @@ internal class PortalAliasRouteManager : IPortalAliasRouteManager { private List _prefixCounts; + // TODO: this method need remove after drop use old api format. + [Obsolete("Replaced with GetRouteUrl. Scheduled for removal in v11.0.0")] + public static string GetOldRouteUrl(string moduleFolderName, string url, int count) + { + Requires.NotNegative("count", count); + Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + + return string.Format("{0}DesktopModules/{1}/API/{2}", new PortalAliasRouteManager().GeneratePrefixString(count), moduleFolderName, url); + } + public string GetRouteName(string moduleFolderName, string routeName, int count) { Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); @@ -43,23 +53,6 @@ public string GetRouteName(string moduleFolderName, string routeName, PortalAlia return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); } - private string GeneratePrefixString(int count) - { - if (count == 0) - { - return string.Empty; - } - - string prefix = string.Empty; - - for (int i = count - 1; i >= 0; i--) - { - prefix = "{prefix" + i + "}/" + prefix; - } - - return prefix; - } - public HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) { var allRouteValues = new HttpRouteValueDictionary(routeValues); @@ -67,13 +60,13 @@ public HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInf var segments = portalAliasInfo.HTTPAlias.Split('/'); if (segments.Length > 1) - { - for (int i = 1; i < segments.Length; i++) - { - var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); - var value = segments[i]; - allRouteValues.Add(key, value); - } + { + for (int i = 1; i < segments.Length; i++) + { + var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); + var value = segments[i]; + allRouteValues.Add(key, value); + } } return allRouteValues; @@ -87,14 +80,21 @@ public string GetRouteUrl(string moduleFolderName, string url, int count) return string.Format("{0}API/{1}/{2}", this.GeneratePrefixString(count), moduleFolderName, url); } - // TODO: this method need remove after drop use old api format. - [Obsolete("Replaced with GetRouteUrl. Scheduled for removal in v11.0.0")] - public static string GetOldRouteUrl(string moduleFolderName, string url, int count) + private string GeneratePrefixString(int count) { - Requires.NotNegative("count", count); - Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + if (count == 0) + { + return string.Empty; + } - return string.Format("{0}DesktopModules/{1}/API/{2}", new PortalAliasRouteManager().GeneratePrefixString(count), moduleFolderName, url); + string prefix = string.Empty; + + for (int i = count - 1; i >= 0; i--) + { + prefix = "{prefix" + i + "}/" + prefix; + } + + return prefix; } public void ClearCachedData() @@ -141,18 +141,6 @@ private static int CalcAliasPrefixCount(string alias) return alias.Count(c => c == '/'); } - private IEnumerable StripApplicationPath(IEnumerable aliases) - { - string appPath = TestableGlobals.Instance.ApplicationPath; - - if (string.IsNullOrEmpty(appPath)) - { - return aliases; - } - - return StripApplicationPathIterable(aliases, appPath); - } - private static IEnumerable StripApplicationPathIterable(IEnumerable aliases, string appPath) { foreach (string alias in aliases) @@ -169,5 +157,17 @@ private static IEnumerable StripApplicationPathIterable(IEnumerable StripApplicationPath(IEnumerable aliases) + { + string appPath = TestableGlobals.Instance.ApplicationPath; + + if (string.IsNullOrEmpty(appPath)) + { + return aliases; + } + + return StripApplicationPathIterable(aliases, appPath); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/RouteExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/RouteExtensions.cs index d01831d9dad..f51f9ee82f3 100644 --- a/DNN Platform/DotNetNuke.Web/Api/RouteExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/RouteExtensions.cs @@ -13,6 +13,24 @@ public static class RouteExtensions private const string NamespaceKey = "namespaces"; private const string NameKey = "name"; + /// + /// Get the name of the route. + /// + /// Route name. + public static string GetName(this Route route) + { + return (string)route.DataTokens[NameKey]; + } + + /// + /// Get the name of the route. + /// + /// Route name. + public static string GetName(this IHttpRoute route) + { + return (string)route.DataTokens[NameKey]; + } + internal static void SetNameSpaces(this Route route, string[] namespaces) { route.DataTokens[NamespaceKey] = namespaces; @@ -50,23 +68,5 @@ internal static void SetName(this IHttpRoute route, string name) { route.DataTokens[NameKey] = name; } - - /// - /// Get the name of the route. - /// - /// Route name. - public static string GetName(this Route route) - { - return (string)route.DataTokens[NameKey]; - } - - /// - /// Get the name of the route. - /// - /// Route name. - public static string GetName(this IHttpRoute route) - { - return (string)route.DataTokens[NameKey]; - } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs index 3f7da056d56..8425baf70a0 100644 --- a/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs @@ -16,10 +16,10 @@ namespace DotNetNuke.Web.Api public sealed class StandardTabAndModuleInfoProvider : ITabAndModuleInfoProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); - private const string ModuleIdKey = "ModuleId"; private const string TabIdKey = "TabId"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); private const string MonikerQueryKey = "Moniker"; private const string MonikerHeaderKey = "X-DNN-MONIKER"; private const string MonikerSettingsKey = "Moniker"; @@ -29,6 +29,28 @@ public bool TryFindTabId(HttpRequestMessage request, out int tabId) return TryFindTabId(request, out tabId, true); } + public bool TryFindModuleId(HttpRequestMessage request, out int moduleId) + { + return TryFindModuleId(request, out moduleId, true); + } + + public bool TryFindModuleInfo(HttpRequestMessage request, out ModuleInfo moduleInfo) + { + int tabId, moduleId; + if (TryFindTabId(request, out tabId, false) && TryFindModuleId(request, out moduleId, false)) + { + moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); + if (moduleInfo != null && moduleInfo.IsDeleted) + { + moduleInfo = null; + } + + return moduleInfo != null; + } + + return TryFindByMoniker(request, out moduleInfo); + } + private static bool TryFindTabId(HttpRequestMessage request, out int tabId, bool tryMoniker) { tabId = FindInt(request, TabIdKey); @@ -50,11 +72,6 @@ private static bool TryFindTabId(HttpRequestMessage request, out int tabId, bool return false; } - public bool TryFindModuleId(HttpRequestMessage request, out int moduleId) - { - return TryFindModuleId(request, out moduleId, true); - } - private static bool TryFindModuleId(HttpRequestMessage request, out int moduleId, bool tryMoniker) { moduleId = FindInt(request, ModuleIdKey); @@ -76,23 +93,6 @@ private static bool TryFindModuleId(HttpRequestMessage request, out int moduleId return false; } - public bool TryFindModuleInfo(HttpRequestMessage request, out ModuleInfo moduleInfo) - { - int tabId, moduleId; - if (TryFindTabId(request, out tabId, false) && TryFindModuleId(request, out moduleId, false)) - { - moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); - if (moduleInfo != null && moduleInfo.IsDeleted) - { - moduleInfo = null; - } - - return moduleInfo != null; - } - - return TryFindByMoniker(request, out moduleInfo); - } - private static int FindInt(HttpRequestMessage requestMessage, string key) { string value = null; diff --git a/DNN Platform/DotNetNuke.Web/Api/SupportedModulesAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/SupportedModulesAttribute.cs index 46d2861de41..954881f476f 100644 --- a/DNN Platform/DotNetNuke.Web/Api/SupportedModulesAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/SupportedModulesAttribute.cs @@ -32,11 +32,6 @@ public override bool IsAuthorized(AuthFilterContext context) return false; } - private bool ModuleIsSupported(ModuleInfo module) - { - return this._supportedModules.Contains(module.DesktopModule.ModuleName); - } - protected virtual ModuleInfo FindModuleInfo(HttpRequestMessage request) { return request.FindModuleInfo(); @@ -46,5 +41,10 @@ protected override bool SkipAuthorization(HttpActionContext actionContext) { return false; } + + private bool ModuleIsSupported(ModuleInfo module) + { + return this._supportedModules.Contains(module.DesktopModule.ModuleName); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs index aedfe24bb9a..2888c0df2eb 100644 --- a/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs @@ -15,9 +15,23 @@ namespace DotNetNuke.Web.Api public class ValidateAntiForgeryTokenAttribute : ActionFilterAttribute { + protected static Tuple SuccessResult = new Tuple(true, null); + private static readonly List BypassedAuthTypes = new List(); - protected static Tuple SuccessResult = new Tuple(true, null); + public override bool AllowMultiple => false; + + public override void OnActionExecuting(HttpActionContext actionContext) + { + if (!BypassTokenCheck()) + { + var result = this.IsAuthorized(actionContext); + if (!result.Item1) + { + throw new UnauthorizedAccessException(result.Item2); + } + } + } internal static void AppendToBypassAuthTypes(string authType) { @@ -28,23 +42,24 @@ internal static void AppendToBypassAuthTypes(string authType) } } - private static bool BypassTokenCheck() - { - // bypass anti-forgery for those handllers that request so. - var authType = Thread.CurrentPrincipal?.Identity?.AuthenticationType; - return !string.IsNullOrEmpty(authType) && BypassedAuthTypes.Contains(authType); - } - - public override void OnActionExecuting(HttpActionContext actionContext) + protected static string GetAntiForgeryCookieValue(HttpActionContext actionContext) { - if (!BypassTokenCheck()) + IEnumerable cookies; + if (actionContext?.Request != null && actionContext.Request.Headers.TryGetValues("Cookie", out cookies)) { - var result = this.IsAuthorized(actionContext); - if (!result.Item1) + foreach (var cookieValue in cookies) { - throw new UnauthorizedAccessException(result.Item2); + var nameIndex = cookieValue.IndexOf(AntiForgery.Instance.CookieName, StringComparison.InvariantCultureIgnoreCase); + if (nameIndex > -1) + { + var valueIndex = nameIndex + AntiForgery.Instance.CookieName.Length + 1; + var valueEndIndex = cookieValue.Substring(valueIndex).IndexOf(';'); + return valueEndIndex > -1 ? cookieValue.Substring(valueIndex, valueEndIndex) : cookieValue.Substring(valueIndex); + } } } + + return string.Empty; } protected virtual Tuple IsAuthorized(HttpActionContext actionContext) @@ -78,26 +93,11 @@ protected virtual Tuple IsAuthorized(HttpActionContext actionConte return SuccessResult; } - protected static string GetAntiForgeryCookieValue(HttpActionContext actionContext) + private static bool BypassTokenCheck() { - IEnumerable cookies; - if (actionContext?.Request != null && actionContext.Request.Headers.TryGetValues("Cookie", out cookies)) - { - foreach (var cookieValue in cookies) - { - var nameIndex = cookieValue.IndexOf(AntiForgery.Instance.CookieName, StringComparison.InvariantCultureIgnoreCase); - if (nameIndex > -1) - { - var valueIndex = nameIndex + AntiForgery.Instance.CookieName.Length + 1; - var valueEndIndex = cookieValue.Substring(valueIndex).IndexOf(';'); - return valueEndIndex > -1 ? cookieValue.Substring(valueIndex, valueEndIndex) : cookieValue.Substring(valueIndex); - } - } - } - - return string.Empty; + // bypass anti-forgery for those handllers that request so. + var authType = Thread.CurrentPrincipal?.Identity?.AuthenticationType; + return !string.IsNullOrEmpty(authType) && BypassedAuthTypes.Contains(authType); } - - public override bool AllowMultiple => false; } } diff --git a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs index 499939674b0..54c2525279c 100644 --- a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs +++ b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs @@ -44,6 +44,35 @@ public class DotNetNukeHttpApplication : HttpApplication { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DotNetNukeHttpApplication)); + private static readonly string[] Endings = + { + ".css", ".gif", ".jpeg", ".jpg", ".js", ".png", "scriptresource.axd", "webresource.axd", + }; + + private static void RegisterIfNotAlreadyRegistered() + where TConcrete : class, new() + { + RegisterIfNotAlreadyRegistered(string.Empty); + } + + private static void RegisterIfNotAlreadyRegistered(string name) + where TAbstract : class + where TConcrete : class, new() + { + var provider = ComponentFactory.GetComponent(); + if (provider == null) + { + if (string.IsNullOrEmpty(name)) + { + ComponentFactory.RegisterComponentInstance(new TConcrete()); + } + else + { + ComponentFactory.RegisterComponentInstance(name, new TConcrete()); + } + } + } + private void Application_Error(object sender, EventArgs eventArgs) { // Code that runs when an unhandled error occurs @@ -79,10 +108,10 @@ private void Application_Start(object sender, EventArgs eventArgs) ComponentFactory.InstallComponents(new ProviderInstaller("caching", typeof(CachingProvider), typeof(FBCachingProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("logging", typeof(LoggingProvider), typeof(DBLoggingProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("scheduling", typeof(SchedulingProvider), typeof(DNNScheduler))); - ComponentFactory.InstallComponents(new ProviderInstaller("searchIndex", typeof(IndexingProvider), typeof(ModuleIndexer))); - #pragma warning disable 0618 - ComponentFactory.InstallComponents(new ProviderInstaller("searchDataStore", typeof(SearchDataStoreProvider), typeof(SearchDataStore))); - #pragma warning restore 0618 + ComponentFactory.InstallComponents(new ProviderInstaller("searchIndex", typeof(IndexingProvider), typeof(ModuleIndexer))); +#pragma warning disable 0618 + ComponentFactory.InstallComponents(new ProviderInstaller("searchDataStore", typeof(SearchDataStoreProvider), typeof(SearchDataStore))); +#pragma warning restore 0618 ComponentFactory.InstallComponents(new ProviderInstaller("members", typeof(MembershipProvider), typeof(AspNetMembershipProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("roles", typeof(RoleProvider), typeof(DNNRoleProvider))); ComponentFactory.InstallComponents(new ProviderInstaller("profiles", typeof(ProfileProvider), typeof(DNNProfileProvider))); @@ -111,28 +140,16 @@ private void Application_Start(object sender, EventArgs eventArgs) // DotNetNukeSecurity.Initialize(); } - private static void RegisterIfNotAlreadyRegistered() - where TConcrete : class, new() + private static bool IsInstallOrUpgradeRequest(HttpRequest request) { - RegisterIfNotAlreadyRegistered(string.Empty); - } + var url = request.Url.LocalPath.ToLowerInvariant(); - private static void RegisterIfNotAlreadyRegistered(string name) - where TAbstract : class - where TConcrete : class, new() - { - var provider = ComponentFactory.GetComponent(); - if (provider == null) - { - if (string.IsNullOrEmpty(name)) - { - ComponentFactory.RegisterComponentInstance(new TConcrete()); - } - else - { - ComponentFactory.RegisterComponentInstance(name, new TConcrete()); - } - } + return url.EndsWith("webresource.axd") + || url.EndsWith("scriptresource.axd") + || url.EndsWith("captcha.aspx") + || url.Contains("upgradewizard.aspx") + || url.Contains("installwizard.aspx") + || url.EndsWith("install.aspx"); } private void Application_End(object sender, EventArgs eventArgs) @@ -184,11 +201,6 @@ private void Application_End(object sender, EventArgs eventArgs) Logger.Info("Application Ended"); } - private static readonly string[] Endings = - { - ".css", ".gif", ".jpeg", ".jpg", ".js", ".png", "scriptresource.axd", "webresource.axd", - }; - private void Application_BeginRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; @@ -231,17 +243,5 @@ private bool IsInstallInProgress(HttpApplication app) { return InstallBlocker.Instance.IsInstallInProgress(); } - - private static bool IsInstallOrUpgradeRequest(HttpRequest request) - { - var url = request.Url.LocalPath.ToLowerInvariant(); - - return url.EndsWith("webresource.axd") - || url.EndsWith("scriptresource.axd") - || url.EndsWith("captcha.aspx") - || url.Contains("upgradewizard.aspx") - || url.Contains("installwizard.aspx") - || url.EndsWith("install.aspx"); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs index be8eb5177bf..68954da3bb1 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs @@ -95,6 +95,11 @@ public IEnumerable GetCustomMenuItems() return menuItemsExtensionPoints.Select(this.GetMenuItemFromExtensionPoint); } + protected override Func GetFactory() + { + return () => new ControlBarController(); + } + private UpgradeIndicatorViewModel GetDefaultUpgradeIndicator(string imageUrl) { var alt = LocalizationHelper.GetControlBarString("Upgrade.Text"); @@ -146,10 +151,5 @@ private IEnumerable> GetBookmarked return bookmarkedModules; } - - protected override Func GetFactory() - { - return () => new ControlBarController(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs b/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs index 373417b1f33..7b91872deb4 100644 --- a/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs +++ b/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs @@ -8,12 +8,12 @@ namespace DotNetNuke.Web.ConfigSection public class AuthServicesConfiguration : ConfigurationSection { + [ConfigurationProperty("messageHandlers", IsRequired = true)] + public MessageHandlersCollection MessageHandlers => this["messageHandlers"] as MessageHandlersCollection; + public static AuthServicesConfiguration GetConfig() { return ConfigurationManager.GetSection("dotnetnuke/authServices") as AuthServicesConfiguration; } - - [ConfigurationProperty("messageHandlers", IsRequired = true)] - public MessageHandlersCollection MessageHandlers => this["messageHandlers"] as MessageHandlersCollection; } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs index 62003406a3d..683e1283cb7 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs @@ -43,13 +43,13 @@ public HttpResponseMessage Reject(NotificationDTO postData) string[] parameters = notification.Context.Split(':'); - var stateTransiction = new StateTransaction - { - ContentItemId = int.Parse(parameters[0]), - CurrentStateId = int.Parse(parameters[2]), - Message = new StateTransactionMessage(), - UserId = this.UserInfo.UserID, - }; + var stateTransiction = new StateTransaction + { + ContentItemId = int.Parse(parameters[0]), + CurrentStateId = int.Parse(parameters[2]), + Message = new StateTransactionMessage(), + UserId = this.UserInfo.UserID, + }; this._workflowEngine.DiscardState(stateTransiction); return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); @@ -79,13 +79,13 @@ public HttpResponseMessage Approve(NotificationDTO postData) string[] parameters = notification.Context.Split(':'); - var stateTransiction = new StateTransaction - { - ContentItemId = int.Parse(parameters[0]), - CurrentStateId = int.Parse(parameters[2]), - Message = new StateTransactionMessage(), - UserId = this.UserInfo.UserID, - }; + var stateTransiction = new StateTransaction + { + ContentItemId = int.Parse(parameters[0]), + CurrentStateId = int.Parse(parameters[2]), + Message = new StateTransactionMessage(), + UserId = this.UserInfo.UserID, + }; this._workflowEngine.CompleteState(stateTransiction); return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs index e700cfe2883..507a242c161 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs @@ -37,8 +37,8 @@ namespace DotNetNuke.Web.InternalServices [DnnAuthorize] public class ControlBarController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ControlBarController)); private const string DefaultExtensionImage = "icon_extensions_32px.png"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ControlBarController)); private readonly Components.Controllers.IControlBarController Controller; private IDictionary _nameDics; @@ -46,60 +46,6 @@ public ControlBarController() { this.Controller = Components.Controllers.ControlBarController.Instance; } - - public class ModuleDefDTO - { - public int ModuleID { get; set; } - - public string ModuleName { get; set; } - - public string ModuleImage { get; set; } - - public bool Bookmarked { get; set; } - - public bool ExistsInBookmarkCategory { get; set; } - } - - public class PageDefDTO - { - public int TabID { get; set; } - - public string IndentedTabName { get; set; } - } - - public class AddModuleDTO - { - public string Visibility { get; set; } - - public string Position { get; set; } - - public string Module { get; set; } - - public string Page { get; set; } - - public string Pane { get; set; } - - public string AddExistingModule { get; set; } - - public string CopyModule { get; set; } - - public string Sort { get; set; } - } - - public class UserModeDTO - { - public string UserMode { get; set; } - } - - public class SwitchSiteDTO - { - public string Site { get; set; } - } - - public class SwitchLanguageDTO - { - public string Language { get; set; } - } [HttpGet] [DnnPageEditor] @@ -219,16 +165,58 @@ public HttpResponseMessage GetTabModules(string tab) return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } - private IList GetModules(int tabID) + public class ModuleDefDTO { - var isRemote = TabController.Instance.GetTab(tabID, Null.NullInteger, false).PortalID != PortalSettings.Current.PortalId; - var tabModules = ModuleController.Instance.GetTabModules(tabID); + public int ModuleID { get; set; } + + public string ModuleName { get; set; } + + public string ModuleImage { get; set; } + + public bool Bookmarked { get; set; } + + public bool ExistsInBookmarkCategory { get; set; } + } - var pageModules = isRemote - ? tabModules.Values.Where(m => this.ModuleSupportsSharing(m) && !m.IsDeleted).ToList() - : tabModules.Values.Where(m => ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "MANAGE", m) && !m.IsDeleted).ToList(); + public class PageDefDTO + { + public int TabID { get; set; } + + public string IndentedTabName { get; set; } + } - return pageModules; + public class AddModuleDTO + { + public string Visibility { get; set; } + + public string Position { get; set; } + + public string Module { get; set; } + + public string Page { get; set; } + + public string Pane { get; set; } + + public string AddExistingModule { get; set; } + + public string CopyModule { get; set; } + + public string Sort { get; set; } + } + + public class UserModeDTO + { + public string UserMode { get; set; } + } + + public class SwitchSiteDTO + { + public string Site { get; set; } + } + + public class SwitchLanguageDTO + { + public string Language { get; set; } } [HttpPost] @@ -348,6 +336,18 @@ public HttpResponseMessage AddModule(AddModuleDTO dto) return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } + private IList GetModules(int tabID) + { + var isRemote = TabController.Instance.GetTab(tabID, Null.NullInteger, false).PortalID != PortalSettings.Current.PortalId; + var tabModules = ModuleController.Instance.GetTabModules(tabID); + + var pageModules = isRemote + ? tabModules.Values.Where(m => this.ModuleSupportsSharing(m) && !m.IsDeleted).ToList() + : tabModules.Values.Where(m => ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "MANAGE", m) && !m.IsDeleted).ToList(); + + return pageModules; + } + [HttpPost] [ValidateAntiForgeryToken] [RequireHost] @@ -472,13 +472,6 @@ public HttpResponseMessage ToggleUserMode(UserModeDTO userMode) return response; } - public class BookmarkDTO - { - public string Title { get; set; } - - public string Bookmark { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] [DnnPageEditor] @@ -494,11 +487,6 @@ public HttpResponseMessage SaveBookmark(BookmarkDTO bookmark) return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); } - public class LockingDTO - { - public bool Lock { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] [RequireHost] @@ -517,6 +505,21 @@ public HttpResponseMessage LockSite(LockingDTO lockingRequest) return this.Request.CreateResponse(HttpStatusCode.OK); } + public bool CanAddModuleToPage() + { + return true; + + // If we are not in an edit page + // return (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) && (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"])); + } + + private static void SetCloneModuleContext(bool cloneModuleContext) + { + Thread.SetData( + Thread.GetNamedDataSlot("CloneModuleContext"), + cloneModuleContext ? bool.TrueString : bool.FalseString); + } + private void ToggleUserMode(string mode) { var personalizationController = new DotNetNuke.Services.Personalization.PersonalizationController(); @@ -526,6 +529,18 @@ private void ToggleUserMode(string mode) personalizationController.SaveProfile(personalization); } + public class BookmarkDTO + { + public string Title { get; set; } + + public string Bookmark { get; set; } + } + + public class LockingDTO + { + public bool Lock { get; set; } + } + private PortalSettings GetPortalSettings(string portal) { var portalSettings = PortalSettings.Current; @@ -594,14 +609,6 @@ join tabMods in tabModules on modDefs.Value.DesktopModuleID equals tabMods.Value return System.Web.VirtualPathUtility.ToAbsolute(imageUrl); } - public bool CanAddModuleToPage() - { - return true; - - // If we are not in an edit page - // return (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) && (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"])); - } - private bool ActiveTabHasChildren() { var children = TabController.GetTabsByParent(this.PortalSettings.ActiveTab.TabID, this.PortalSettings.ActiveTab.PortalID); @@ -750,13 +757,6 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po return -1; } - private static void SetCloneModuleContext(bool cloneModuleContext) - { - Thread.SetData( - Thread.GetNamedDataSlot("CloneModuleContext"), - cloneModuleContext ? bool.TrueString : bool.FalseString); - } - private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess) { var objModulePermission = new ModulePermissionInfo diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs index 81593853312..6ef33ae2874 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs @@ -29,12 +29,6 @@ public HttpResponseMessage Countries() x => x.NormalizedFullName.IndexOf(searchString, StringComparison.CurrentCulture) > -1).OrderBy(x => x.NormalizedFullName)); } - public struct Region - { - public string Text; - public string Value; - } - [HttpGet] public HttpResponseMessage Regions(int country) { @@ -50,5 +44,11 @@ public HttpResponseMessage Regions(int country) return this.Request.CreateResponse(HttpStatusCode.OK, res.OrderBy(r => r.Text)); } + + public struct Region + { + public string Text; + public string Value; + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs index 401dde9263d..26a28743727 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs @@ -40,11 +40,11 @@ public HttpResponseMessage GetLogDetails(string guid) return this.Request.CreateResponse(HttpStatusCode.BadRequest); } - return this.Request.CreateResponse(HttpStatusCode.OK, new - { - Title = Localization.GetSafeJSString("CriticalError.Error", Localization.SharedResourceFile), - Content = this.GetPropertiesText(logInfo), - }); + return this.Request.CreateResponse(HttpStatusCode.OK, new + { + Title = Localization.GetSafeJSString("CriticalError.Error", Localization.SharedResourceFile), + Content = this.GetPropertiesText(logInfo), + }); } catch (Exception ex) { diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs index c9c76f98623..eddb6abdc30 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs @@ -45,20 +45,12 @@ public class FileUploadController : DnnApiController private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileUploadController)); private static readonly Regex UserFolderEx = new Regex(@"users/\d+/\d+/(\d+)/", RegexOptions.Compiled | RegexOptions.IgnoreCase); - public class FolderItemDTO - { - public int FolderId { get; set; } - - public string FileFilter { get; set; } - - public bool Required { get; set; } - } + private static readonly List ImageExtensions = Globals.glbImageFileTypes.Split(',').ToList(); - public class SavedFileDTO + public static string GetUrl(int fileId) { - public string FileId { get; set; } - - public string FilePath { get; set; } + var file = FileManager.Instance.GetFile(fileId, true); + return FileManager.Instance.GetUrl(file); } [HttpPost] @@ -218,6 +210,150 @@ public Task PostFile() return task; } + public class FolderItemDTO + { + public int FolderId { get; set; } + + public string FileFilter { get; set; } + + public bool Required { get; set; } + } + + public class SavedFileDTO + { + public string FileId { get; set; } + + public string FilePath { get; set; } + } + + [HttpPost] + [IFrameSupportedValidateAntiForgeryToken] + [AllowAnonymous] + public Task UploadFromLocal() + { + return this.UploadFromLocal(this.PortalSettings.PortalId); + } + + [HttpPost] + [IFrameSupportedValidateAntiForgeryToken] + [AllowAnonymous] + public Task UploadFromLocal(int portalId) + { + var request = this.Request; + FileUploadDto result = null; + if (!request.Content.IsMimeMultipartContent()) + { + throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); + } + + if (portalId > -1) + { + if (!this.IsPortalIdValid(portalId)) + { + throw new HttpResponseException(HttpStatusCode.Unauthorized); + } + } + else + { + portalId = this.PortalSettings.PortalId; + } + + var provider = new MultipartMemoryStreamProvider(); + + // local references for use in closure + var currentSynchronizationContext = SynchronizationContext.Current; + var userInfo = this.UserInfo; + var task = request.Content.ReadAsMultipartAsync(provider) + .ContinueWith(o => + { + var folder = string.Empty; + var filter = string.Empty; + var fileName = string.Empty; + var validationCode = string.Empty; + var overwrite = false; + var isHostPortal = false; + var extract = false; + Stream stream = null; + + foreach (var item in provider.Contents) + { + var name = item.Headers.ContentDisposition.Name; + switch (name.ToUpper()) + { + case "\"FOLDER\"": + folder = item.ReadAsStringAsync().Result ?? string.Empty; + break; + + case "\"FILTER\"": + filter = item.ReadAsStringAsync().Result ?? string.Empty; + break; + + case "\"OVERWRITE\"": + bool.TryParse(item.ReadAsStringAsync().Result, out overwrite); + break; + + case "\"ISHOSTPORTAL\"": + bool.TryParse(item.ReadAsStringAsync().Result, out isHostPortal); + break; + + case "\"EXTRACT\"": + bool.TryParse(item.ReadAsStringAsync().Result, out extract); + break; + + case "\"PORTALID\"": + if (userInfo.IsSuperUser) + { + int.TryParse(item.ReadAsStringAsync().Result, out portalId); + } + + break; + case "\"VALIDATIONCODE\"": + validationCode = item.ReadAsStringAsync().Result ?? string.Empty; + break; + case "\"POSTFILE\"": + fileName = item.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); + if (fileName.IndexOf("\\", StringComparison.Ordinal) != -1) + { + fileName = Path.GetFileName(fileName); + } + + if (Globals.FileEscapingRegex.Match(fileName).Success == false) + { + stream = item.ReadAsStreamAsync().Result; + } + + break; + } + } + + if (!string.IsNullOrEmpty(fileName) && stream != null) + { + // The SynchronizationContext keeps the main thread context. Send method is synchronous + currentSynchronizationContext.Send( + state => + { + result = UploadFile(stream, portalId, userInfo, folder, filter, fileName, overwrite, isHostPortal, extract, validationCode); + }, + null); + } + + var mediaTypeFormatter = new JsonMediaTypeFormatter(); + mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); + + /* Response Content Type cannot be application/json + * because IE9 with iframe-transport manages the response + * as a file download + */ + return this.Request.CreateResponse( + HttpStatusCode.OK, + result, + mediaTypeFormatter, + "text/plain"); + }); + + return task; + } + private static SavedFileDTO SaveFile( Stream stream, PortalSettings portalSettings, @@ -326,8 +462,6 @@ private static string ShowImage(int fileId) return null; } - private static readonly List ImageExtensions = Globals.glbImageFileTypes.Split(',').ToList(); - private static bool IsImageExtension(string extension) { return ImageExtensions.Any(e => e.Equals(extension, StringComparison.OrdinalIgnoreCase)); @@ -338,59 +472,6 @@ private static bool IsImage(string fileName) return ImageExtensions.Any(extension => fileName.EndsWith("." + extension, StringComparison.OrdinalIgnoreCase)); } - public class UploadByUrlDto - { - public string Url { get; set; } - - public string Folder { get; set; } - - public bool Overwrite { get; set; } - - public bool Unzip { get; set; } - - public string Filter { get; set; } - - public bool IsHostMenu { get; set; } - - public int PortalId { get; set; } = -1; - - public string ValidationCode { get; set; } - } - - [DataContract] - public class FileUploadDto - { - [DataMember(Name = "path")] - public string Path { get; set; } - - [DataMember(Name = "orientation")] - public Orientation Orientation { get; set; } - - [DataMember(Name = "alreadyExists")] - public bool AlreadyExists { get; set; } - - [DataMember(Name = "message")] - public string Message { get; set; } - - [DataMember(Name = "fileIconUrl")] - public string FileIconUrl { get; set; } - - [DataMember(Name = "fileId")] - public int FileId { get; set; } - - [DataMember(Name = "fileName")] - public string FileName { get; set; } - - [DataMember(Name = "prompt")] - public string Prompt { get; set; } - } - - public static string GetUrl(int fileId) - { - var file = FileManager.Instance.GetFile(fileId, true); - return FileManager.Instance.GetUrl(file); - } - private static FileUploadDto UploadFile( Stream stream, int portalId, @@ -543,132 +624,51 @@ private static FileUploadDto UploadFile( } } - [HttpPost] - [IFrameSupportedValidateAntiForgeryToken] - [AllowAnonymous] - public Task UploadFromLocal() - { - return this.UploadFromLocal(this.PortalSettings.PortalId); - } - - [HttpPost] - [IFrameSupportedValidateAntiForgeryToken] - [AllowAnonymous] - public Task UploadFromLocal(int portalId) + public class UploadByUrlDto { - var request = this.Request; - FileUploadDto result = null; - if (!request.Content.IsMimeMultipartContent()) - { - throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); - } - - if (portalId > -1) - { - if (!this.IsPortalIdValid(portalId)) - { - throw new HttpResponseException(HttpStatusCode.Unauthorized); - } - } - else - { - portalId = this.PortalSettings.PortalId; - } + public string Url { get; set; } - var provider = new MultipartMemoryStreamProvider(); + public string Folder { get; set; } - // local references for use in closure - var currentSynchronizationContext = SynchronizationContext.Current; - var userInfo = this.UserInfo; - var task = request.Content.ReadAsMultipartAsync(provider) - .ContinueWith(o => - { - var folder = string.Empty; - var filter = string.Empty; - var fileName = string.Empty; - var validationCode = string.Empty; - var overwrite = false; - var isHostPortal = false; - var extract = false; - Stream stream = null; + public bool Overwrite { get; set; } - foreach (var item in provider.Contents) - { - var name = item.Headers.ContentDisposition.Name; - switch (name.ToUpper()) - { - case "\"FOLDER\"": - folder = item.ReadAsStringAsync().Result ?? string.Empty; - break; + public bool Unzip { get; set; } - case "\"FILTER\"": - filter = item.ReadAsStringAsync().Result ?? string.Empty; - break; + public string Filter { get; set; } - case "\"OVERWRITE\"": - bool.TryParse(item.ReadAsStringAsync().Result, out overwrite); - break; + public bool IsHostMenu { get; set; } - case "\"ISHOSTPORTAL\"": - bool.TryParse(item.ReadAsStringAsync().Result, out isHostPortal); - break; + public int PortalId { get; set; } = -1; - case "\"EXTRACT\"": - bool.TryParse(item.ReadAsStringAsync().Result, out extract); - break; + public string ValidationCode { get; set; } + } - case "\"PORTALID\"": - if (userInfo.IsSuperUser) - { - int.TryParse(item.ReadAsStringAsync().Result, out portalId); - } + [DataContract] + public class FileUploadDto + { + [DataMember(Name = "path")] + public string Path { get; set; } - break; - case "\"VALIDATIONCODE\"": - validationCode = item.ReadAsStringAsync().Result ?? string.Empty; - break; - case "\"POSTFILE\"": - fileName = item.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); - if (fileName.IndexOf("\\", StringComparison.Ordinal) != -1) - { - fileName = Path.GetFileName(fileName); - } + [DataMember(Name = "orientation")] + public Orientation Orientation { get; set; } - if (Globals.FileEscapingRegex.Match(fileName).Success == false) - { - stream = item.ReadAsStreamAsync().Result; - } + [DataMember(Name = "alreadyExists")] + public bool AlreadyExists { get; set; } - break; - } - } + [DataMember(Name = "message")] + public string Message { get; set; } - if (!string.IsNullOrEmpty(fileName) && stream != null) - { - // The SynchronizationContext keeps the main thread context. Send method is synchronous - currentSynchronizationContext.Send( - state => - { - result = UploadFile(stream, portalId, userInfo, folder, filter, fileName, overwrite, isHostPortal, extract, validationCode); - }, - null); - } + [DataMember(Name = "fileIconUrl")] + public string FileIconUrl { get; set; } - var mediaTypeFormatter = new JsonMediaTypeFormatter(); - mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); + [DataMember(Name = "fileId")] + public int FileId { get; set; } - /* Response Content Type cannot be application/json - * because IE9 with iframe-transport manages the response - * as a file download - */ - return this.Request.CreateResponse( - HttpStatusCode.OK, - result, - mediaTypeFormatter, - "text/plain"); - }); + [DataMember(Name = "fileName")] + public string FileName { get; set; } - return task; + [DataMember(Name = "prompt")] + public string Prompt { get; set; } } [HttpPost] @@ -756,6 +756,17 @@ public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) } } + private static IEnumerable GetMyPortalGroup() + { + var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); + var mygroup = (from @group in groups + select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); + return mygroup; + } + private string GetFileName(WebResponse response) { if (!response.Headers.AllKeys.Contains("Content-Disposition")) @@ -804,17 +815,6 @@ private bool VerifySafeUrl(string url) return false; } - private static IEnumerable GetMyPortalGroup() - { - var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); - var mygroup = (from @group in groups - select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); - return mygroup; - } - private bool IsPortalIdValid(int portalId) { if (this.UserInfo.IsSuperUser) diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs index 576510133d6..4a64f05bb8e 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs @@ -31,33 +31,10 @@ namespace DotNetNuke.Web.InternalServices [DnnAuthorize] public class ItemListServiceController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ItemListServiceController)); - private const string PortalPrefix = "P-"; private const string RootKey = "Root"; - [DataContract] - public class ItemDto - { - [DataMember(Name = "key")] - public string Key { get; set; } - - [DataMember(Name = "value")] - public string Value { get; set; } - - [DataMember(Name = "hasChildren")] - public bool HasChildren { get; set; } - - [DataMember(Name = "selectable")] - public bool Selectable { get; set; } - } - - [DataContract] - public class ItemIdDto - { - [DataMember(Name = "id")] - public string Id { get; set; } - } + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ItemListServiceController)); [HttpGet] public HttpResponseMessage GetPageDescendants(string parentId = null, int sortOrder = 0, @@ -103,6 +80,29 @@ public HttpResponseMessage SortPages(string treeAsJson, int sortOrder = 0, strin }; return this.Request.CreateResponse(HttpStatusCode.OK, response); } + + [DataContract] + public class ItemDto + { + [DataMember(Name = "key")] + public string Key { get; set; } + + [DataMember(Name = "value")] + public string Value { get; set; } + + [DataMember(Name = "hasChildren")] + public bool HasChildren { get; set; } + + [DataMember(Name = "selectable")] + public bool Selectable { get; set; } + } + + [DataContract] + public class ItemIdDto + { + [DataMember(Name = "id")] + public string Id { get; set; } + } [HttpGet] public HttpResponseMessage SortPagesInPortalGroup(string treeAsJson, int sortOrder = 0, @@ -296,6 +296,93 @@ public HttpResponseMessage SearchFiles(int parentId, string filter, string searc }; return this.Request.CreateResponse(HttpStatusCode.OK, response); } + + [HttpGet] + public HttpResponseMessage SearchUser(string q) + { + try + { + var portalId = PortalController.GetEffectivePortalId(this.PortalSettings.PortalId); + const int numResults = 5; + + // GetUsersAdvancedSearch doesn't accept a comma or a single quote in the query so we have to remove them for now. See issue 20224. + q = q.Replace(",", string.Empty).Replace("'", string.Empty); + if (q.Length == 0) + { + return this.Request.CreateResponse(HttpStatusCode.OK, null); + } + + var results = UserController.Instance.GetUsersBasicSearch(portalId, 0, numResults, "DisplayName", true, "DisplayName", q) + .Select(user => new SearchResult + { + id = user.UserID, + name = user.DisplayName, + iconfile = UserController.Instance.GetUserProfilePictureUrl(user.UserID, 32, 32), + }).ToList(); + + return this.Request.CreateResponse(HttpStatusCode.OK, results.OrderBy(sr => sr.name)); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpGet] + public HttpResponseMessage GetTerms(string q, bool includeSystem, bool includeTags) + { + var portalId = PortalSettings.Current.PortalId; + + var vocabRep = Util.GetVocabularyController(); + var termRep = Util.GetTermController(); + + var terms = new ArrayList(); + var vocabularies = from v in vocabRep.GetVocabularies() + where (v.ScopeType.ScopeType == "Application" + || (v.ScopeType.ScopeType == "Portal" && v.ScopeId == portalId)) + && (!v.IsSystem || includeSystem) + && (v.Name != "Tags" || includeTags) + select v; + + foreach (var v in vocabularies) + { + terms.AddRange(new[] + { + from t in termRep.GetTermsByVocabulary(v.VocabularyId) + where string.IsNullOrEmpty(q) || t.Name.IndexOf(q, StringComparison.InvariantCultureIgnoreCase) > -1 + select new { text = t.Name, value = t.TermId }, + }); + } + + return this.Request.CreateResponse(HttpStatusCode.OK, terms); + } + + private static NTree GetPagesInPortalGroupInternal(int sortOrder) + { + var treeNode = new NTree { Data = new ItemDto { Key = RootKey } }; + var portals = GetPortalGroup(sortOrder); + treeNode.Children = portals.Select(dto => new NTree { Data = dto }).ToList(); + return treeNode; + } + + private static IEnumerable GetChildrenOf(IEnumerable tabs, int parentId, IList filterTabs = null) + { + return tabs.Where(tab => tab.ParentId == parentId).Select(tab => new ItemDto + { + Key = tab.TabID.ToString(CultureInfo.InvariantCulture), + Value = tab.LocalizedTabName, + HasChildren = tab.HasChildren, + Selectable = filterTabs == null || filterTabs.Contains(tab.TabID), + }).ToList(); + } + + private static IEnumerable GetChildrenOf(IEnumerable tabs, string parentId) + { + int id; + id = int.TryParse(parentId, out id) ? id : Null.NullInteger; + return GetChildrenOf(tabs, id); + } private NTree GetPagesInternal(int portalId, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, @@ -319,14 +406,6 @@ private NTree GetPagesInternal(int portalId, int sortOrder, bool includ return sortedTree; } - private static NTree GetPagesInPortalGroupInternal(int sortOrder) - { - var treeNode = new NTree { Data = new ItemDto { Key = RootKey } }; - var portals = GetPortalGroup(sortOrder); - treeNode.Children = portals.Select(dto => new NTree { Data = dto }).ToList(); - return treeNode; - } - private IEnumerable GetPageDescendantsInPortalGroupInternal(string parentId, int sortOrder, string searchText, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = true, bool includeHostPages = false, string roles = "") @@ -543,12 +622,12 @@ private List GetPortalPages(int portalId, bool includeDisabled = false, } if (portalId > -1) - { - tabs = TabController.GetPortalTabs(portalId, includeActive ? Null.NullInteger : this.PortalSettings.ActiveTab.TabID, false, null, true, false, includeAllTypes, true, false) - .Where(t => (!t.DisableLink || includeDisabled) && !t.IsSystem) - .ToList(); - - if (this.PortalSettings.UserInfo.IsSuperUser && includeHostPages) + { + tabs = TabController.GetPortalTabs(portalId, includeActive ? Null.NullInteger : this.PortalSettings.ActiveTab.TabID, false, null, true, false, includeAllTypes, true, false) + .Where(t => (!t.DisableLink || includeDisabled) && !t.IsSystem) + .ToList(); + + if (this.PortalSettings.UserInfo.IsSuperUser && includeHostPages) { tabs.AddRange(TabController.Instance.GetTabsByPortal(-1).AsList().Where(t => !t.IsDeleted && !t.DisableLink && !t.IsSystem).ToList()); } @@ -564,23 +643,55 @@ private List GetPortalPages(int portalId, bool includeDisabled = false, return tabs; } - private static IEnumerable GetChildrenOf(IEnumerable tabs, int parentId, IList filterTabs = null) + private static void SortPagesRecursevely(IEnumerable tabs, NTree treeNode, NTree openedNode, int sortOrder) { - return tabs.Where(tab => tab.ParentId == parentId).Select(tab => new ItemDto + if (openedNode == null) { - Key = tab.TabID.ToString(CultureInfo.InvariantCulture), - Value = tab.LocalizedTabName, - HasChildren = tab.HasChildren, - Selectable = filterTabs == null || filterTabs.Contains(tab.TabID), - }).ToList(); + return; + } + + var children = ApplySort(GetChildrenOf(tabs, openedNode.Data.Id), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); + treeNode.Children = children; + if (openedNode.HasChildren()) + { + foreach (var openedNodeChild in openedNode.Children) + { + var treeNodeChild = treeNode.Children.Find(child => string.Equals(child.Data.Key, openedNodeChild.Data.Id, StringComparison.InvariantCultureIgnoreCase)); + if (treeNodeChild == null) + { + continue; + } + + SortPagesRecursevely(tabs, treeNodeChild, openedNodeChild, sortOrder); + } + } } - private static IEnumerable GetChildrenOf(IEnumerable tabs, string parentId) + private static IEnumerable GetPortalGroup(int sortOrder) { - int id; - id = int.TryParse(parentId, out id) ? id : Null.NullInteger; - return GetChildrenOf(tabs, id); + var mygroup = GetMyPortalGroup(); + var portals = mygroup.Select(p => new ItemDto + { + Key = PortalPrefix + p.PortalID.ToString(CultureInfo.InvariantCulture), + Value = p.PortalName, + HasChildren = true, + Selectable = false, + }).ToList(); + return ApplySort(portals, sortOrder); } + + private static IEnumerable ApplySort(IEnumerable items, int sortOrder) + { + switch (sortOrder) + { + case 1: // sort by a-z + return items.OrderBy(item => item.Value).ToList(); + case 2: // sort by z-a + return items.OrderByDescending(item => item.Value).ToList(); + default: // no sort + return items; + } + } private NTree SortPagesInternal(int portalId, string treeAsJson, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, @@ -709,30 +820,6 @@ private NTree SortPagesInPortalGroupInternal(NTree openedNod return treeNode; } - private static void SortPagesRecursevely(IEnumerable tabs, NTree treeNode, NTree openedNode, int sortOrder) - { - if (openedNode == null) - { - return; - } - - var children = ApplySort(GetChildrenOf(tabs, openedNode.Data.Id), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); - treeNode.Children = children; - if (openedNode.HasChildren()) - { - foreach (var openedNodeChild in openedNode.Children) - { - var treeNodeChild = treeNode.Children.Find(child => string.Equals(child.Data.Key, openedNodeChild.Data.Id, StringComparison.InvariantCultureIgnoreCase)); - if (treeNodeChild == null) - { - continue; - } - - SortPagesRecursevely(tabs, treeNodeChild, openedNodeChild, sortOrder); - } - } - } - private NTree GetTreePathForPageInternal(int portalId, string itemId, int sortOrder, bool includePortalTree = false, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "") @@ -893,19 +980,6 @@ private NTree GetTreePathForPageInternal(int portalId, int selectedItem return tree; } - private static IEnumerable GetPortalGroup(int sortOrder) - { - var mygroup = GetMyPortalGroup(); - var portals = mygroup.Select(p => new ItemDto - { - Key = PortalPrefix + p.PortalID.ToString(CultureInfo.InvariantCulture), - Value = p.PortalName, - HasChildren = true, - Selectable = false, - }).ToList(); - return ApplySort(portals, sortOrder); - } - private List FilterTabsByRole(IList tabs, string roles, bool disabledNotSelectable) { var filterTabs = new List(); @@ -1323,89 +1397,15 @@ private class SearchResult // ReSharper restore NotAccessedField.Local // ReSharper restore InconsistentNaming } - - [HttpGet] - public HttpResponseMessage SearchUser(string q) - { - try - { - var portalId = PortalController.GetEffectivePortalId(this.PortalSettings.PortalId); - const int numResults = 5; - - // GetUsersAdvancedSearch doesn't accept a comma or a single quote in the query so we have to remove them for now. See issue 20224. - q = q.Replace(",", string.Empty).Replace("'", string.Empty); - if (q.Length == 0) - { - return this.Request.CreateResponse(HttpStatusCode.OK, null); - } - - var results = UserController.Instance.GetUsersBasicSearch(portalId, 0, numResults, "DisplayName", true, "DisplayName", q) - .Select(user => new SearchResult - { - id = user.UserID, - name = user.DisplayName, - iconfile = UserController.Instance.GetUserProfilePictureUrl(user.UserID, 32, 32), - }).ToList(); - - return this.Request.CreateResponse(HttpStatusCode.OK, results.OrderBy(sr => sr.name)); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - [HttpGet] - public HttpResponseMessage GetTerms(string q, bool includeSystem, bool includeTags) - { - var portalId = PortalSettings.Current.PortalId; - - var vocabRep = Util.GetVocabularyController(); - var termRep = Util.GetTermController(); - - var terms = new ArrayList(); - var vocabularies = from v in vocabRep.GetVocabularies() - where (v.ScopeType.ScopeType == "Application" - || (v.ScopeType.ScopeType == "Portal" && v.ScopeId == portalId)) - && (!v.IsSystem || includeSystem) - && (v.Name != "Tags" || includeTags) - select v; - - foreach (var v in vocabularies) - { - terms.AddRange(new[] - { - from t in termRep.GetTermsByVocabulary(v.VocabularyId) - where string.IsNullOrEmpty(q) || t.Name.IndexOf(q, StringComparison.InvariantCultureIgnoreCase) > -1 - select new { text = t.Name, value = t.TermId }, - }); - } - - return this.Request.CreateResponse(HttpStatusCode.OK, terms); - } - - private static IEnumerable ApplySort(IEnumerable items, int sortOrder) - { - switch (sortOrder) - { - case 1: // sort by a-z - return items.OrderBy(item => item.Value).ToList(); - case 2: // sort by z-a - return items.OrderByDescending(item => item.Value).ToList(); - default: // no sort - return items; - } - } private static IEnumerable GetMyPortalGroup() { var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); var mygroup = (from @group in groups select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); return mygroup; } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs index adc2e409053..c23114caca7 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs @@ -21,26 +21,12 @@ namespace DotNetNuke.Web.InternalServices [DnnAuthorize] public class LanguageServiceController : DnnApiController { - protected INavigationManager NavigationManager { get; } - public LanguageServiceController(INavigationManager navigationManager) { this.NavigationManager = navigationManager; } - - public class PageDto - { - public string Name { get; set; } - - public string ViewUrl { get; set; } - public string EditUrl { get; set; } - } - - private bool IsDefaultLanguage(string code) - { - return code == this.PortalSettings.DefaultLanguage; - } + protected INavigationManager NavigationManager { get; } [HttpGet] public HttpResponseMessage GetNonTranslatedPages(string languageCode) @@ -66,5 +52,19 @@ public HttpResponseMessage GetNonTranslatedPages(string languageCode) return this.Request.CreateResponse(HttpStatusCode.OK, pages); } + + private bool IsDefaultLanguage(string code) + { + return code == this.PortalSettings.DefaultLanguage; + } + + public class PageDto + { + public string Name { get; set; } + + public string ViewUrl { get; set; } + + public string EditUrl { get; set; } + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs index e5599c35c3e..97fd3384e13 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs @@ -43,15 +43,6 @@ public HttpResponseMessage WaitTimeForNextMessage() } } - public class CreateDTO - { - public string Subject; - public string Body; - public string RoleIds; - public string UserIds; - public string FileIds; - } - [ValidateAntiForgeryToken] [HttpPost] public HttpResponseMessage Create(CreateDTO postData) @@ -110,18 +101,18 @@ public HttpResponseMessage Search(string q) // Roles should be visible to Administrators or User in the Role. var roles = RoleController.Instance.GetRolesBasicSearch(portalId, numResults, q); - results.AddRange(from roleInfo in roles - where - isAdmin || - this.UserInfo.Social.Roles.SingleOrDefault(ur => ur.RoleID == roleInfo.RoleID && ur.IsOwner) != null - select new SearchResult - { - id = "role-" + roleInfo.RoleID, - name = roleInfo.RoleName, - iconfile = TestableGlobals.Instance.ResolveUrl(string.IsNullOrEmpty(roleInfo.IconFile) - ? "~/images/no_avatar.gif" - : this.PortalSettings.HomeDirectory.TrimEnd('/') + "/" + roleInfo.IconFile), - }); + results.AddRange(from roleInfo in roles + where + isAdmin || + this.UserInfo.Social.Roles.SingleOrDefault(ur => ur.RoleID == roleInfo.RoleID && ur.IsOwner) != null + select new SearchResult + { + id = "role-" + roleInfo.RoleID, + name = roleInfo.RoleName, + iconfile = TestableGlobals.Instance.ResolveUrl(string.IsNullOrEmpty(roleInfo.IconFile) + ? "~/images/no_avatar.gif" + : this.PortalSettings.HomeDirectory.TrimEnd('/') + "/" + roleInfo.IconFile), + }); return this.Request.CreateResponse(HttpStatusCode.OK, results.OrderBy(sr => sr.name)); } @@ -132,6 +123,15 @@ public HttpResponseMessage Search(string q) } } + public class CreateDTO + { + public string Subject; + public string Body; + public string RoleIds; + public string UserIds; + public string FileIds; + } + /// /// This class stores a single search result needed by jQuery Tokeninput. /// diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs index c29561f26b2..c94be293c03 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs @@ -22,26 +22,6 @@ namespace DotNetNuke.Web.InternalServices public class ModuleServiceController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleServiceController)); - - public class MoveModuleDTO - { - public int ModuleId { get; set; } - - public int ModuleOrder { get; set; } - - public string Pane { get; set; } - - public int TabId { get; set; } - } - - public class DeleteModuleDto - { - public int ModuleId { get; set; } - - public int TabId { get; set; } - - public bool SoftDelete { get; set; } - } [HttpGet] [DnnAuthorize(StaticRoles = "Registered Users")] @@ -123,6 +103,26 @@ public HttpResponseMessage DeleteModule(DeleteModuleDto deleteModuleDto) return this.Request.CreateResponse(HttpStatusCode.OK); } + + public class MoveModuleDTO + { + public int ModuleId { get; set; } + + public int ModuleOrder { get; set; } + + public string Pane { get; set; } + + public int TabId { get; set; } + } + + public class DeleteModuleDto + { + public int ModuleId { get; set; } + + public int TabId { get; set; } + + public bool SoftDelete { get; set; } + } private int FixPortalId(int portalId) { diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs index 2f4ffc19383..a827d8c7582 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs @@ -100,18 +100,18 @@ public HttpResponseMessage UpdateCustomUrl(SaveUrlDto dto) if (tabUrl == null) { // Just create Url - tabUrl = new TabUrlInfo - { - TabId = tab.TabID, - SeqNum = dto.Id, - PortalAliasId = dto.SiteAliasKey, - PortalAliasUsage = (PortalAliasUsageType)dto.SiteAliasUsage, - QueryString = dto.QueryString.ValueOrEmpty(), - Url = dto.Path.ValueOrEmpty(), - CultureCode = cultureCode, - HttpStatus = dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture), - IsSystem = dto.IsSystem, // false - }; + tabUrl = new TabUrlInfo + { + TabId = tab.TabID, + SeqNum = dto.Id, + PortalAliasId = dto.SiteAliasKey, + PortalAliasUsage = (PortalAliasUsageType)dto.SiteAliasUsage, + QueryString = dto.QueryString.ValueOrEmpty(), + Url = dto.Path.ValueOrEmpty(), + CultureCode = cultureCode, + HttpStatus = dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture), + IsSystem = dto.IsSystem, // false + }; TabController.Instance.SaveTabUrl(tabUrl, this.PortalId, true); } else @@ -131,18 +131,18 @@ public HttpResponseMessage UpdateCustomUrl(SaveUrlDto dto) else { // Just update the url - var tabUrl = new TabUrlInfo - { - TabId = tab.TabID, - SeqNum = dto.Id, - PortalAliasId = dto.SiteAliasKey, - PortalAliasUsage = (PortalAliasUsageType)dto.SiteAliasUsage, - QueryString = dto.QueryString.ValueOrEmpty(), - Url = dto.Path.ValueOrEmpty(), - CultureCode = cultureCode, - HttpStatus = dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture), - IsSystem = dto.IsSystem, // false - }; + var tabUrl = new TabUrlInfo + { + TabId = tab.TabID, + SeqNum = dto.Id, + PortalAliasId = dto.SiteAliasKey, + PortalAliasUsage = (PortalAliasUsageType)dto.SiteAliasUsage, + QueryString = dto.QueryString.ValueOrEmpty(), + Url = dto.Path.ValueOrEmpty(), + CultureCode = cultureCode, + HttpStatus = dto.StatusCodeKey.ToString(CultureInfo.InvariantCulture), + IsSystem = dto.IsSystem, // false + }; TabController.Instance.SaveTabUrl(tabUrl, this.PortalId, true); } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs index cdbf2e5036e..18a6b9463eb 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs @@ -48,12 +48,12 @@ public HttpResponseMessage UpdateVanityUrl(VanityUrlDTO vanityUrl) return this.Request.CreateResponse( HttpStatusCode.OK, new - { - Result = "warning", - Title = Localization.GetString("CleanWarningTitle", Localization.SharedResourceFile), - Message = Localization.GetString("ProfileUrlCleaned", Localization.SharedResourceFile), - SuggestedUrl = cleanUrl, - }); + { + Result = "warning", + Title = Localization.GetString("CleanWarningTitle", Localization.SharedResourceFile), + Message = Localization.GetString("ProfileUrlCleaned", Localization.SharedResourceFile), + SuggestedUrl = cleanUrl, + }); } // Validate for uniqueness @@ -63,13 +63,13 @@ public HttpResponseMessage UpdateVanityUrl(VanityUrlDTO vanityUrl) { return this.Request.CreateResponse( HttpStatusCode.OK, - new - { - Result = "warning", - Title = Localization.GetString("DuplicateUrlWarningTitle", Localization.SharedResourceFile), - Message = Localization.GetString("ProfileUrlNotUnique", Localization.SharedResourceFile), - SuggestedUrl = uniqueUrl, - }); + new + { + Result = "warning", + Title = Localization.GetString("DuplicateUrlWarningTitle", Localization.SharedResourceFile), + Message = Localization.GetString("ProfileUrlNotUnique", Localization.SharedResourceFile), + SuggestedUrl = uniqueUrl, + }); } var user = this.PortalSettings.UserInfo; @@ -82,11 +82,6 @@ public HttpResponseMessage UpdateVanityUrl(VanityUrlDTO vanityUrl) return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - public class VanityUrlDTO - { - public string Url { get; set; } - } - [DnnAuthorize] [HttpGet] public HttpResponseMessage ProfilePropertyValues() @@ -96,5 +91,10 @@ public HttpResponseMessage ProfilePropertyValues() int portalId = int.Parse(HttpContext.Current.Request.Params["PortalId"]); return this.Request.CreateResponse(HttpStatusCode.OK, Entities.Profile.ProfileController.SearchProfilePropertyValues(portalId, propertyName, searchString)); } + + public class VanityUrlDTO + { + public string Url { get; set; } + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs index 59fc050d319..0cd24fb0512 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs @@ -31,29 +31,13 @@ namespace DotNetNuke.Web.InternalServices [DnnAuthorize(StaticRoles = "Administrators")] public class SearchServiceController : DnnApiController { - private static readonly Regex GroupedBasicViewRegex = new Regex("userid(/|\\|=)(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - public class SynonymsGroupDto - { - public int Id { get; set; } - - public string Tags { get; set; } - - public int PortalId { get; set; } - - public string Culture { get; set; } - } - - public class StopWordsDto - { - public int Id { get; set; } - - public string Words { get; set; } + private const string ModuleInfosCacheKey = "ModuleInfos{0}"; + private const CacheItemPriority ModuleInfosCachePriority = CacheItemPriority.AboveNormal; + private const int ModuleInfosCacheTimeOut = 20; - public int PortalId { get; set; } + private static readonly Regex GroupedBasicViewRegex = new Regex("userid(/|\\|=)(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); - public string Culture { get; set; } - } + private int HtmlModuleDefitionId; public SearchServiceController() { @@ -69,8 +53,6 @@ internal SearchServiceController(int htmlModuleDefitionId) // , TabController ne // _tabController = newtabController; // _moduleController = newmoduleController; } - - private int HtmlModuleDefitionId; private bool IsWildCardEnabledForModule() { @@ -83,199 +65,34 @@ private bool IsWildCardEnabledForModule() return enableWildSearch; } - - private const string ModuleInfosCacheKey = "ModuleInfos{0}"; - private const CacheItemPriority ModuleInfosCachePriority = CacheItemPriority.AboveNormal; - private const int ModuleInfosCacheTimeOut = 20; - - private static ArrayList GetModulesByDefinition(int portalID, string friendlyName) - { - var cacheKey = string.Format(ModuleInfosCacheKey, portalID); - return CBO.GetCachedObject( - new CacheItemArgs(cacheKey, ModuleInfosCacheTimeOut, ModuleInfosCachePriority), - args => CBO.FillCollection(DataProvider.Instance().GetModuleByDefinition(portalID, friendlyName), typeof(ModuleInfo))); - } - - private ModuleInfo GetSearchModule() - { - var arrModules = GetModulesByDefinition(this.PortalSettings.PortalId, "Search Results"); - ModuleInfo findModule = null; - if (arrModules.Count > 1) - { - findModule = arrModules.Cast().FirstOrDefault(searchModule => searchModule.CultureCode == this.PortalSettings.CultureCode); - } - return findModule ?? (arrModules.Count > 0 ? (ModuleInfo)arrModules[0] : null); - } - - private Hashtable GetSearchModuleSettings() - { - if (this.ActiveModule != null && this.ActiveModule.ModuleDefinition.FriendlyName == "Search Results") - { - return this.ActiveModule.ModuleSettings; - } - - var searchModule = this.GetSearchModule(); - return searchModule != null ? searchModule.ModuleSettings : null; - } - - private bool GetBooleanSetting(string settingName, bool defaultValue) - { - if (this.PortalSettings == null) - { - return defaultValue; - } - - var settings = this.GetSearchModuleSettings(); - if (settings == null || !settings.ContainsKey(settingName)) - { - return defaultValue; - } - - return Convert.ToBoolean(settings[settingName]); - } - - private int GetIntegerSetting(string settingName, int defaultValue) - { - if (this.PortalSettings == null) - { - return defaultValue; - } - - var settings = this.GetSearchModuleSettings(); - if (settings == null || !settings.ContainsKey(settingName)) - { - return defaultValue; - } - - var settingValue = Convert.ToString(settings[settingName]); - if (!string.IsNullOrEmpty(settingValue) && Regex.IsMatch(settingValue, "^\\d+$")) - { - return Convert.ToInt32(settingValue); - } - - return defaultValue; - } - - private List GetSearchPortalIds(IDictionary settings, int portalId) + public class SynonymsGroupDto { - var list = new List(); - if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForPortals"]))) - { - list = Convert.ToString(settings["ScopeForPortals"]).Split('|').Select(s => Convert.ToInt32(s)).ToList(); - } - - if (portalId == -1) - { - portalId = this.PortalSettings.ActiveTab.PortalID; - } + public int Id { get; set; } - if (portalId > -1 && !list.Contains(portalId)) - { - list.Add(portalId); - } + public string Tags { get; set; } - // Add Host - var userInfo = this.UserInfo; - if (userInfo.IsSuperUser) - { - list.Add(-1); - } + public int PortalId { get; set; } - return list; + public string Culture { get; set; } } - private static List GetSearchTypeIds(IDictionary settings, IEnumerable searchContentSources) + public class StopWordsDto { - var list = new List(); - var configuredList = new List(); - if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForFilters"]))) - { - configuredList = Convert.ToString(settings["ScopeForFilters"]).Split('|').ToList(); - } - - // check content source in configured list or not - foreach (var contentSource in searchContentSources) - { - if (contentSource.IsPrivate) - { - continue; - } + public int Id { get; set; } - if (configuredList.Count > 0) - { - if (configuredList.Any(l => l.Contains(contentSource.LocalizedName))) // in configured list - { - list.Add(contentSource.SearchTypeId); - } - } - else - { - list.Add(contentSource.SearchTypeId); - } - } - - return list.Distinct().ToList(); - } - - private static IEnumerable GetSearchModuleDefIds(IDictionary settings, IEnumerable searchContentSources) - { - var list = new List(); - var configuredList = new List(); - if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForFilters"]))) - { - configuredList = Convert.ToString(settings["ScopeForFilters"]).Split('|').ToList(); - } - - // check content source in configured list or not - foreach (var contentSource in searchContentSources) - { - if (contentSource.IsPrivate) - { - continue; - } + public string Words { get; set; } - if (configuredList.Count > 0) - { - if (configuredList.Any(l => l.Contains(contentSource.LocalizedName)) && contentSource.ModuleDefinitionId > 0) // in configured list - { - list.Add(contentSource.ModuleDefinitionId); - } - } - else - { - if (contentSource.ModuleDefinitionId > 0) - { - list.Add(contentSource.ModuleDefinitionId); - } - } - } - - return list; + public int PortalId { get; set; } + + public string Culture { get; set; } } - private IList GetSearchContentSources(IList typesList) - { - var sources = new List(); - var list = InternalSearchController.Instance.GetSearchContentSourceList(this.PortalSettings.PortalId); - - if (typesList.Any()) - { - foreach (var contentSources in typesList.Select(t1 => list.Where(src => string.Equals(src.LocalizedName, t1, StringComparison.OrdinalIgnoreCase)))) - { - sources.AddRange(contentSources); - } - } - else - { - // no types fitler specified, add all available content sources - sources.AddRange(list); - } - - return sources; - } + private const string ModuleTitleCacheKey = "SearchModuleTabTitle_{0}"; + private const CacheItemPriority ModuleTitleCachePriority = CacheItemPriority.Normal; + private const int ModuleTitleCacheTimeOut = 20; - internal IEnumerable GetGroupedDetailViews(SearchQuery searchQuery, int userSearchTypeId, out int totalHits, out bool more) + internal IEnumerable GetGroupedDetailViews(SearchQuery searchQuery, int userSearchTypeId, out int totalHits, out bool more) { var searchResults = SearchController.Instance.SiteSearch(searchQuery); totalHits = searchResults.TotalHits; @@ -379,16 +196,6 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search return groups; } - private string GetFriendlyTitle(SearchResult result) - { - if (result.Keywords.ContainsKey("title") && !string.IsNullOrEmpty(result.Keywords["title"])) - { - return result.Keywords["title"]; - } - - return result.Title; - } - internal List GetGroupedBasicViews(SearchQuery query, SearchContentSource userSearchSource, int portalId) { int totalHists; @@ -464,50 +271,221 @@ internal IEnumerable GetBasicViews(SearchQuery searchQuery, out int t }); } - private string GetTitle(SearchResult result, bool showFriendlyTitle = false) + private static ArrayList GetModulesByDefinition(int portalID, string friendlyName) { - if (result.ModuleDefId > 0 && result.ModuleDefId == this.HtmlModuleDefitionId) // special handling for Html module + var cacheKey = string.Format(ModuleInfosCacheKey, portalID); + return CBO.GetCachedObject( + new CacheItemArgs(cacheKey, ModuleInfosCacheTimeOut, ModuleInfosCachePriority), + args => CBO.FillCollection(DataProvider.Instance().GetModuleByDefinition(portalID, friendlyName), typeof(ModuleInfo))); + } + + private static List GetSearchTypeIds(IDictionary settings, IEnumerable searchContentSources) + { + var list = new List(); + var configuredList = new List(); + if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForFilters"]))) { - var tabTitle = this.GetTabTitleFromModuleId(result.ModuleId); - if (!string.IsNullOrEmpty(tabTitle)) + configuredList = Convert.ToString(settings["ScopeForFilters"]).Split('|').ToList(); + } + + // check content source in configured list or not + foreach (var contentSource in searchContentSources) + { + if (contentSource.IsPrivate) + { + continue; + } + + if (configuredList.Count > 0) { - if (result.Title != "Enter Title" && result.Title != "Text/HTML") + if (configuredList.Any(l => l.Contains(contentSource.LocalizedName))) // in configured list { - return tabTitle + " > " + result.Title; + list.Add(contentSource.SearchTypeId); } + } + else + { + list.Add(contentSource.SearchTypeId); + } + } + + return list.Distinct().ToList(); + } + + private static IEnumerable GetSearchModuleDefIds(IDictionary settings, IEnumerable searchContentSources) + { + var list = new List(); + var configuredList = new List(); + if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForFilters"]))) + { + configuredList = Convert.ToString(settings["ScopeForFilters"]).Split('|').ToList(); + } + + // check content source in configured list or not + foreach (var contentSource in searchContentSources) + { + if (contentSource.IsPrivate) + { + continue; + } - return tabTitle; + if (configuredList.Count > 0) + { + if (configuredList.Any(l => l.Contains(contentSource.LocalizedName)) && contentSource.ModuleDefinitionId > 0) // in configured list + { + list.Add(contentSource.ModuleDefinitionId); + } + } + else + { + if (contentSource.ModuleDefinitionId > 0) + { + list.Add(contentSource.ModuleDefinitionId); + } } } - return showFriendlyTitle ? this.GetFriendlyTitle(result) : result.Title; + return list; } - private const string ModuleTitleCacheKey = "SearchModuleTabTitle_{0}"; - private const CacheItemPriority ModuleTitleCachePriority = CacheItemPriority.Normal; - private const int ModuleTitleCacheTimeOut = 20; + private ModuleInfo GetSearchModule() + { + var arrModules = GetModulesByDefinition(this.PortalSettings.PortalId, "Search Results"); + ModuleInfo findModule = null; + if (arrModules.Count > 1) + { + findModule = arrModules.Cast().FirstOrDefault(searchModule => searchModule.CultureCode == this.PortalSettings.CultureCode); + } - private string GetTabTitleFromModuleId(int moduleId) + return findModule ?? (arrModules.Count > 0 ? (ModuleInfo)arrModules[0] : null); + } + + private Hashtable GetSearchModuleSettings() { - // no manual clearing of the cache exists; let is just expire - var cacheKey = string.Format(ModuleTitleCacheKey, moduleId); + if (this.ActiveModule != null && this.ActiveModule.ModuleDefinition.FriendlyName == "Search Results") + { + return this.ActiveModule.ModuleSettings; + } - return CBO.GetCachedObject(new CacheItemArgs(cacheKey, ModuleTitleCacheTimeOut, ModuleTitleCachePriority, moduleId), this.GetTabTitleCallBack); + var searchModule = this.GetSearchModule(); + return searchModule != null ? searchModule.ModuleSettings : null; } - private object GetTabTitleCallBack(CacheItemArgs cacheItemArgs) + private bool GetBooleanSetting(string settingName, bool defaultValue) { - var moduleId = (int)cacheItemArgs.ParamList[0]; - var moduleInfo = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); - if (moduleInfo != null) + if (this.PortalSettings == null) { - var tab = moduleInfo.ParentTab; + return defaultValue; + } - return !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName; + var settings = this.GetSearchModuleSettings(); + if (settings == null || !settings.ContainsKey(settingName)) + { + return defaultValue; } - return string.Empty; + return Convert.ToBoolean(settings[settingName]); + } + + private int GetIntegerSetting(string settingName, int defaultValue) + { + if (this.PortalSettings == null) + { + return defaultValue; + } + + var settings = this.GetSearchModuleSettings(); + if (settings == null || !settings.ContainsKey(settingName)) + { + return defaultValue; + } + + var settingValue = Convert.ToString(settings[settingName]); + if (!string.IsNullOrEmpty(settingValue) && Regex.IsMatch(settingValue, "^\\d+$")) + { + return Convert.ToInt32(settingValue); + } + + return defaultValue; + } + + private List GetSearchPortalIds(IDictionary settings, int portalId) + { + var list = new List(); + if (settings != null && !string.IsNullOrEmpty(Convert.ToString(settings["ScopeForPortals"]))) + { + list = Convert.ToString(settings["ScopeForPortals"]).Split('|').Select(s => Convert.ToInt32(s)).ToList(); + } + + if (portalId == -1) + { + portalId = this.PortalSettings.ActiveTab.PortalID; + } + + if (portalId > -1 && !list.Contains(portalId)) + { + list.Add(portalId); + } + + // Add Host + var userInfo = this.UserInfo; + if (userInfo.IsSuperUser) + { + list.Add(-1); + } + + return list; + } + + private IList GetSearchContentSources(IList typesList) + { + var sources = new List(); + var list = InternalSearchController.Instance.GetSearchContentSourceList(this.PortalSettings.PortalId); + + if (typesList.Any()) + { + foreach (var contentSources in typesList.Select(t1 => list.Where(src => string.Equals(src.LocalizedName, t1, StringComparison.OrdinalIgnoreCase)))) + { + sources.AddRange(contentSources); + } + } + else + { + // no types fitler specified, add all available content sources + sources.AddRange(list); + } + + return sources; } + + private string GetFriendlyTitle(SearchResult result) + { + if (result.Keywords.ContainsKey("title") && !string.IsNullOrEmpty(result.Keywords["title"])) + { + return result.Keywords["title"]; + } + + return result.Title; + } + + private string GetTitle(SearchResult result, bool showFriendlyTitle = false) + { + if (result.ModuleDefId > 0 && result.ModuleDefId == this.HtmlModuleDefitionId) // special handling for Html module + { + var tabTitle = this.GetTabTitleFromModuleId(result.ModuleId); + if (!string.IsNullOrEmpty(tabTitle)) + { + if (result.Title != "Enter Title" && result.Title != "Text/HTML") + { + return tabTitle + " > " + result.Title; + } + + return tabTitle; + } + } + + return showFriendlyTitle ? this.GetFriendlyTitle(result) : result.Title; + } [HttpGet] [AllowAnonymous] @@ -584,23 +562,23 @@ public HttpResponseMessage Search(string search, string culture, int pageIndex, if (portalIds.Any() && searchTypeIds.Any() && (!string.IsNullOrEmpty(cleanedKeywords) || tags.Any())) { - var query = new SearchQuery - { - KeyWords = cleanedKeywords, - Tags = tags, - PortalIds = portalIds, - SearchTypeIds = searchTypeIds, - ModuleDefIds = moduleDefids, - BeginModifiedTimeUtc = beginModifiedTimeUtc, - EndModifiedTimeUtc = beginModifiedTimeUtc > DateTime.MinValue ? DateTime.MaxValue : DateTime.MinValue, - PageIndex = pageIndex, - PageSize = pageSize, - SortField = (SortFields)sortOption, - TitleSnippetLength = 120, - BodySnippetLength = 300, - CultureCode = culture, - WildCardSearch = this.IsWildCardEnabledForModule(), - }; + var query = new SearchQuery + { + KeyWords = cleanedKeywords, + Tags = tags, + PortalIds = portalIds, + SearchTypeIds = searchTypeIds, + ModuleDefIds = moduleDefids, + BeginModifiedTimeUtc = beginModifiedTimeUtc, + EndModifiedTimeUtc = beginModifiedTimeUtc > DateTime.MinValue ? DateTime.MaxValue : DateTime.MinValue, + PageIndex = pageIndex, + PageSize = pageSize, + SortField = (SortFields)sortOption, + TitleSnippetLength = 120, + BodySnippetLength = 300, + CultureCode = culture, + WildCardSearch = this.IsWildCardEnabledForModule(), + }; try { @@ -615,6 +593,28 @@ public HttpResponseMessage Search(string search, string culture, int pageIndex, return this.Request.CreateResponse(HttpStatusCode.OK, new { results, totalHits, more }); } + private string GetTabTitleFromModuleId(int moduleId) + { + // no manual clearing of the cache exists; let is just expire + var cacheKey = string.Format(ModuleTitleCacheKey, moduleId); + + return CBO.GetCachedObject(new CacheItemArgs(cacheKey, ModuleTitleCacheTimeOut, ModuleTitleCachePriority, moduleId), this.GetTabTitleCallBack); + } + + private object GetTabTitleCallBack(CacheItemArgs cacheItemArgs) + { + var moduleId = (int)cacheItemArgs.ParamList[0]; + var moduleInfo = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); + if (moduleInfo != null) + { + var tab = moduleInfo.ParentTab; + + return !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName; + } + + return string.Empty; + } + [HttpPost] [ValidateAntiForgeryToken] [SupportedModules("SearchAdmin")] diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs index 1eeb24af07a..845eba8919a 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs @@ -62,6 +62,27 @@ public HttpResponseMessage GetItems(string fileExtensions) } } + private static string GetModifiedTime(DateTime dateTime) + { + return string.Format("{0:MMM} {0:dd}, {0:yyyy} at {0:t}", dateTime); + } + + private static string GetTypeName(IFileInfo file) + { + return file.ContentType == null + ? string.Empty + : (file.ContentType.StartsWith("image/") + ? file.ContentType.Replace("image/", string.Empty) + : (file.Extension != null ? file.Extension.ToLowerInvariant() : string.Empty)); + } + + private static bool IsImageFile(string relativePath) + { + var acceptedExtensions = new List { "jpg", "png", "gif", "jpe", "jpeg", "tiff" }; + var extension = relativePath.Substring(relativePath.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLowerInvariant(); + return acceptedExtensions.Contains(extension); + } + // ReSharper disable LoopCanBeConvertedToQuery private List GetChildren(IFolderInfo folder, ICollection extensions) { @@ -105,11 +126,6 @@ private List GetChildren(IFolderInfo folder, ICollection extension return everything; } - private static string GetModifiedTime(DateTime dateTime) - { - return string.Format("{0:MMM} {0:dd}, {0:yyyy} at {0:t}", dateTime); - } - // ReSharper restore LoopCanBeConvertedToQuery private string GetThumbUrl(IFileInfo file) { @@ -127,22 +143,6 @@ private string GetThumbUrl(IFileInfo file) return fileIcon; } - private static string GetTypeName(IFileInfo file) - { - return file.ContentType == null - ? string.Empty - : (file.ContentType.StartsWith("image/") - ? file.ContentType.Replace("image/", string.Empty) - : (file.Extension != null ? file.Extension.ToLowerInvariant() : string.Empty)); - } - - private static bool IsImageFile(string relativePath) - { - var acceptedExtensions = new List { "jpg", "png", "gif", "jpe", "jpeg", "tiff" }; - var extension = relativePath.Substring(relativePath.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLowerInvariant(); - return acceptedExtensions.Contains(extension); - } - private static string GetFileSize(int sizeInBytes) { var size = sizeInBytes / 1024; diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs index 5cc702917d1..1be0a054e43 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs @@ -13,6 +13,11 @@ namespace DotNetNuke.Web.InternalServices.Views.Search /// public class BasicView { + public BasicView() + { + this.Attributes = new Dictionary(); + } + /// /// Gets or sets document's Title. /// @@ -42,10 +47,5 @@ public class BasicView /// Gets or sets custom Attributes of the document. /// public IDictionary Attributes { get; set; } - - public BasicView() - { - this.Attributes = new Dictionary(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs index e1101692a99..05090e315ca 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs @@ -11,16 +11,6 @@ namespace DotNetNuke.Web.InternalServices.Views.Search /// public class GroupedBasicView { - /// - /// Gets or sets type of Search Document. - /// - public string DocumentTypeName { get; set; } - - /// - /// Gets or sets results of the Search. - /// - public List Results { get; set; } - public GroupedBasicView() { } @@ -40,5 +30,15 @@ public GroupedBasicView(BasicView basic) }, }; } + + /// + /// Gets or sets type of Search Document. + /// + public string DocumentTypeName { get; set; } + + /// + /// Gets or sets results of the Search. + /// + public List Results { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs index 0167f6a2b25..9c9fda33ab4 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs @@ -11,6 +11,11 @@ namespace DotNetNuke.Web.InternalServices.Views.Search /// public class GroupedDetailView { + public GroupedDetailView() + { + this.Results = new List(); + } + /// /// Gets or sets document's Url. /// @@ -25,10 +30,5 @@ public class GroupedDetailView /// Gets or sets results of the Search. /// public List Results { get; set; } - - public GroupedDetailView() - { - this.Results = new List(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs b/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs index 7f254771b9d..4b859cdaafe 100644 --- a/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs +++ b/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs @@ -10,6 +10,11 @@ namespace DotNetNuke.Web.Models [DataContract] public class ModuleDetail { + public ModuleDetail() + { + this.ModuleInstances = new List(); + } + [DataMember] public string ModuleVersion { get; set; } @@ -18,10 +23,5 @@ public class ModuleDetail [DataMember] public IList ModuleInstances { get; set; } - - public ModuleDetail() - { - this.ModuleInstances = new List(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs b/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs index ac63d90ddfd..60d7a671f40 100644 --- a/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs +++ b/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs @@ -10,6 +10,11 @@ namespace DotNetNuke.Web.Models [DataContract] public class SiteDetail { + public SiteDetail() + { + this.Modules = new List(); + } + [DataMember] public string DnnVersion { get; set; } @@ -24,10 +29,5 @@ public class SiteDetail [DataMember] public IList Modules { get; set; } - - public SiteDetail() - { - this.Modules = new List(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs index 149a957ab9e..5e9dd07be43 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs @@ -11,9 +11,9 @@ namespace DotNetNuke.Web.Mvp [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public interface IModuleViewBase : IView { - bool AutoDataBind { get; set; } - event EventHandler Initialize; + + bool AutoDataBind { get; set; } void ProcessModuleLoadException(Exception ex); diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs index a9ec331a95b..4a06e9105b4 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs @@ -44,6 +44,10 @@ protected ModulePresenterBase(TView view) view.Load += this.LoadInternal; } + public bool AutoDataBind { get; set; } + + public ModuleInfo ModuleInfo { get; set; } + protected internal virtual bool AllowAnonymousAccess { get @@ -59,10 +63,6 @@ protected internal virtual bool IsUserAuthorized return true; } } - - public bool AutoDataBind { get; set; } - - public ModuleInfo ModuleInfo { get; set; } public bool IsEditable { get; set; } @@ -86,18 +86,14 @@ protected internal virtual bool IsUserAuthorized public Validator Validator { get; set; } - private void InitializeInternal(object sender, EventArgs e) + public virtual void RestoreState(StateBag stateBag) { - this.LoadFromContext(); - this.OnInit(); + AttributeBasedViewStateSerializer.DeSerialize(this, stateBag); } - private void LoadInternal(object sender, EventArgs e) + public virtual void SaveState(StateBag stateBag) { - if (this.CheckAuthPolicy()) - { - this.OnLoad(); - } + AttributeBasedViewStateSerializer.Serialize(this, stateBag); } protected internal virtual bool CheckAuthPolicy() @@ -136,6 +132,20 @@ protected virtual void LoadFromContext() this.UserId = this.ModuleContext.PortalSettings.UserInfo.UserID; } } + + private void InitializeInternal(object sender, EventArgs e) + { + this.LoadFromContext(); + this.OnInit(); + } + + private void LoadInternal(object sender, EventArgs e) + { + if (this.CheckAuthPolicy()) + { + this.OnLoad(); + } + } protected virtual string LocalizeString(string key) { @@ -218,15 +228,5 @@ protected void ShowMessage(string messageHeader, string message, ModuleMessage.M this.View.ShowMessage(messageHeader, message, messageType); } } - - public virtual void RestoreState(StateBag stateBag) - { - AttributeBasedViewStateSerializer.DeSerialize(this, stateBag); - } - - public virtual void SaveState(StateBag stateBag) - { - AttributeBasedViewStateSerializer.Serialize(this, stateBag); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs index a458555e03f..3ef2ae0a213 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs @@ -25,16 +25,6 @@ public ModuleSettingsPresenterBase(TView view) public Dictionary TabModuleSettings { get; set; } - private void OnLoadSettingsInternal(object sender, EventArgs e) - { - this.LoadSettings(); - } - - private void OnSaveSettingsInternal(object sender, EventArgs e) - { - this.SaveSettings(); - } - protected override void LoadFromContext() { base.LoadFromContext(); @@ -53,6 +43,16 @@ protected override void LoadFromContext() protected virtual void LoadSettings() { } + + private void OnLoadSettingsInternal(object sender, EventArgs e) + { + this.LoadSettings(); + } + + private void OnSaveSettingsInternal(object sender, EventArgs e) + { + this.SaveSettings(); + } protected virtual void SaveSettings() { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs index c16976b8849..2e268351498 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs @@ -23,16 +23,6 @@ protected ModuleSettingsPresenter(TView view) view.OnSaveSettings += this.OnSaveSettingsInternal; } - private void OnLoadSettingsInternal(object sender, EventArgs e) - { - this.LoadSettings(); - } - - private void OnSaveSettingsInternal(object sender, EventArgs e) - { - this.SaveSettings(); - } - protected override void OnLoad() { base.OnLoad(); @@ -57,6 +47,16 @@ protected virtual void LoadSettings() .Cast() .ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value)); } + + private void OnLoadSettingsInternal(object sender, EventArgs e) + { + this.LoadSettings(); + } + + private void OnSaveSettingsInternal(object sender, EventArgs e) + { + this.SaveSettings(); + } protected virtual void SaveSettings() { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs index 0b5d3499ca7..07a903f7962 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs @@ -18,6 +18,27 @@ protected ModuleViewBase() { this.AutoDataBind = true; } + + public event EventHandler Initialize; + + public new event EventHandler Load; + + public bool AutoDataBind { get; set; } + + public bool ThrowExceptionIfNoPresenterBound + { + get { return true; } + } + + public void ProcessModuleLoadException(Exception ex) + { + Exceptions.ProcessModuleLoadException(this, ex); + } + + public void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType) + { + DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, messageHeader, message, messageType); + } protected T DataItem() where T : class, new() @@ -47,27 +68,6 @@ protected override void OnInit(EventArgs e) this.Page.Load += this.PageLoad; } - public bool AutoDataBind { get; set; } - - public event EventHandler Initialize; - - public void ProcessModuleLoadException(Exception ex) - { - Exceptions.ProcessModuleLoadException(this, ex); - } - - public void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType) - { - DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, messageHeader, message, messageType); - } - - public new event EventHandler Load; - - public bool ThrowExceptionIfNoPresenterBound - { - get { return true; } - } - private void PageInitComplete(object sender, EventArgs e) { if (this.Initialize != null) diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs index 1fb5d582dab..b7436d124d6 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs @@ -20,8 +20,6 @@ namespace DotNetNuke.Web.Mvp public abstract class ProfileModuleViewBase : ModuleView, IProfileModule where TModel : class, new() { - protected INavigationManager NavigationManager { get; } - public ProfileModuleViewBase() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); @@ -43,6 +41,8 @@ public int ProfileUserId } } + protected INavigationManager NavigationManager { get; } + protected bool IsUser { get @@ -56,6 +56,22 @@ protected UserInfo ProfileUser get { return UserController.GetUserById(this.ModuleContext.PortalId, this.ProfileUserId); } } + protected override void OnInit(EventArgs e) + { + if (this.ProfileUserId == Null.NullInteger && + (this.ModuleContext.PortalSettings.ActiveTab.TabID == this.ModuleContext.PortalSettings.UserTabId + || this.ModuleContext.PortalSettings.ActiveTab.ParentId == this.ModuleContext.PortalSettings.UserTabId)) + { + // Clicked on breadcrumb - don't know which user + this.Response.Redirect( + this.Request.IsAuthenticated + ? this.NavigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, string.Empty, "UserId=" + this.ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture)) + : this.GetRedirectUrl(), true); + } + + base.OnInit(e); + } + private string GetRedirectUrl() { // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. @@ -73,21 +89,5 @@ private string GetRedirectUrl() return redirectUrl; } - - protected override void OnInit(EventArgs e) - { - if (this.ProfileUserId == Null.NullInteger && - (this.ModuleContext.PortalSettings.ActiveTab.TabID == this.ModuleContext.PortalSettings.UserTabId - || this.ModuleContext.PortalSettings.ActiveTab.ParentId == this.ModuleContext.PortalSettings.UserTabId)) - { - // Clicked on breadcrumb - don't know which user - this.Response.Redirect( - this.Request.IsAuthenticated - ? this.NavigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, string.Empty, "UserId=" + this.ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture)) - : this.GetRedirectUrl(), true); - } - - base.OnInit(e); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs index ca4469dea7a..183effd02a6 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs @@ -10,6 +10,10 @@ namespace DotNetNuke.Web.Mvp [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public class SettingsViewBase : ModuleViewBase, ISettingsView, ISettingsControl { + public event EventHandler OnLoadSettings; + + public event EventHandler OnSaveSettings; + public void LoadSettings() { if (this.OnLoadSettings != null) @@ -30,10 +34,6 @@ public void UpdateSettings() } } - public event EventHandler OnLoadSettings; - - public event EventHandler OnSaveSettings; - /// /// The OnSettingsLoaded method is called when the Settings have been Loaded. /// diff --git a/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs b/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs index 9d3169cf235..fc9d449eb3e 100644 --- a/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs +++ b/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs @@ -77,43 +77,6 @@ private static IEnumerable> GetMonikersForList(string return monikers.Where(kpv => resultIds.Contains(kpv.Key)); } - private SiteDetail GetSiteDetails(string moduleList) - { - var siteDetails = new SiteDetail - { - SiteName = this.PortalSettings.PortalName, - DnnVersion = this._dnnVersion, - IsHost = this.UserInfo.IsSuperUser, - IsAdmin = this.UserInfo.IsInRole("Administrators"), - }; - - foreach (var moduleName in (moduleList ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) - { - var modulesCollection = GetTabModules((moduleName ?? string.Empty).Trim()) - .Where(tabmodule => TabPermissionController.CanViewPage(tabmodule.TabInfo) && - ModulePermissionController.CanViewModule(tabmodule.ModuleInfo)); - foreach (var tabmodule in modulesCollection) - { - var moduleDetail = new ModuleDetail - { - ModuleName = moduleName, - ModuleVersion = tabmodule.ModuleVersion, - }; - - moduleDetail.ModuleInstances.Add(new ModuleInstance - { - TabId = tabmodule.TabInfo.TabID, - ModuleId = tabmodule.ModuleInfo.ModuleID, - PageName = tabmodule.TabInfo.TabName, - PagePath = tabmodule.TabInfo.TabPath, - }); - siteDetails.Modules.Add(moduleDetail); - } - } - - return siteDetails; - } - private static IEnumerable GetTabModules(string moduleName) { var portalId = PortalController.Instance.GetCurrentPortalSettings().PortalId; @@ -165,6 +128,43 @@ private static object GetTabModulesCallback(CacheItemArgs cacheItemArgs) return tabModules; } + private SiteDetail GetSiteDetails(string moduleList) + { + var siteDetails = new SiteDetail + { + SiteName = this.PortalSettings.PortalName, + DnnVersion = this._dnnVersion, + IsHost = this.UserInfo.IsSuperUser, + IsAdmin = this.UserInfo.IsInRole("Administrators"), + }; + + foreach (var moduleName in (moduleList ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + { + var modulesCollection = GetTabModules((moduleName ?? string.Empty).Trim()) + .Where(tabmodule => TabPermissionController.CanViewPage(tabmodule.TabInfo) && + ModulePermissionController.CanViewModule(tabmodule.ModuleInfo)); + foreach (var tabmodule in modulesCollection) + { + var moduleDetail = new ModuleDetail + { + ModuleName = moduleName, + ModuleVersion = tabmodule.ModuleVersion, + }; + + moduleDetail.ModuleInstances.Add(new ModuleInstance + { + TabId = tabmodule.TabInfo.TabID, + ModuleId = tabmodule.ModuleInfo.ModuleID, + PageName = tabmodule.TabInfo.TabName, + PagePath = tabmodule.TabInfo.TabPath, + }); + siteDetails.Modules.Add(moduleDetail); + } + } + + return siteDetails; + } + private static void AddChildTabsToList(TabInfo currentTab, TabCollection allPortalTabs, IDictionary tabsWithModule, IDictionary tabsInOrder) { diff --git a/DNN Platform/DotNetNuke.Web/Startup.cs b/DNN Platform/DotNetNuke.Web/Startup.cs index 490e5a4e280..c05fd6887f1 100644 --- a/DNN Platform/DotNetNuke.Web/Startup.cs +++ b/DNN Platform/DotNetNuke.Web/Startup.cs @@ -25,14 +25,6 @@ public Startup() this.Configure(); } - private void Configure() - { - var services = new ServiceCollection(); - services.AddSingleton(); - this.ConfigureServices(services); - this.DependencyProvider = services.BuildServiceProvider(); - } - public IServiceProvider DependencyProvider { get; private set; } public void ConfigureServices(IServiceCollection services) @@ -63,6 +55,14 @@ public void ConfigureServices(IServiceCollection services) services.AddWebApi(); } + private void Configure() + { + var services = new ServiceCollection(); + services.AddSingleton(); + this.ConfigureServices(services); + this.DependencyProvider = services.BuildServiceProvider(); + } + private object CreateInstance(Type startupType) { IDnnStartup startup = null; diff --git a/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs b/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs index 275db8a75f5..242e52b752d 100644 --- a/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs +++ b/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs @@ -24,6 +24,28 @@ namespace DotNetNuke.Web.UI using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.Localization; + + public enum DotNetNukeErrorCode + { + NotSet, + PageExists, + PageNameRequired, + PageNameInvalid, + DeserializePanesFailed, + PageCircularReference, + ParentTabInvalid, + PageEditorPermissionError, + HostBeforeAfterError, + DuplicateWithAlias, + } + + public enum TabRelativeLocation + { + NOTSET, + BEFORE, + AFTER, + CHILD, + } public class RibbonBarManager { @@ -523,26 +545,4 @@ public DotNetNukeErrorCode ErrorCode } } } - - public enum DotNetNukeErrorCode - { - NotSet, - PageExists, - PageNameRequired, - PageNameInvalid, - DeserializePanesFailed, - PageCircularReference, - ParentTabInvalid, - PageEditorPermissionError, - HostBeforeAfterError, - DuplicateWithAlias, - } - - public enum TabRelativeLocation - { - NOTSET, - BEFORE, - AFTER, - CHILD, - } } diff --git a/DNN Platform/DotNetNuke.Web/UI/Utilities.cs b/DNN Platform/DotNetNuke.Web/UI/Utilities.cs index 22aea95bba8..42de159479a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/Utilities.cs +++ b/DNN Platform/DotNetNuke.Web/UI/Utilities.cs @@ -24,11 +24,6 @@ namespace DotNetNuke.Web.UI public class Utilities { - private static void AddMessageWindow(Control ctrl) - { - ClientResourceManager.RegisterScript(ctrl.Page, ctrl.ResolveUrl("~/js/dnn.postbackconfirm.js")); - } - public static void ApplySkin(Control telerikControl) { ApplySkin(telerikControl, string.Empty, string.Empty, string.Empty); @@ -38,6 +33,11 @@ public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkin { ApplySkin(telerikControl, string.Empty, string.Empty, fallBackEmbeddedSkinName); } + + private static void AddMessageWindow(Control ctrl) + { + ClientResourceManager.RegisterScript(ctrl.Page, ctrl.ResolveUrl("~/js/dnn.postbackconfirm.js")); + } public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkinName, string controlName) { diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs index 9bd36031b69..dd5da6e7575 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs @@ -52,34 +52,6 @@ public string ConfirmMessage } } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (!this.Enabled) - { - this.CssClass = this.DisabledCssClass; - } - - if (!string.IsNullOrEmpty(this.ConfirmMessage)) - { - string msg = this.ConfirmMessage; - if (this.Localize) - { - msg = Utilities.GetLocalizedStringFromParent(this.ConfirmMessage, this); - } - - // must be done before render - this.OnClientClick = Utilities.GetOnClientClickConfirm(this, msg); - } - } - - protected override void Render(HtmlTextWriter writer) - { - this.LocalizeStrings(); - base.Render(writer); - } - public bool Localize { get @@ -129,5 +101,33 @@ public virtual void LocalizeStrings() } } } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (!this.Enabled) + { + this.CssClass = this.DisabledCssClass; + } + + if (!string.IsNullOrEmpty(this.ConfirmMessage)) + { + string msg = this.ConfirmMessage; + if (this.Localize) + { + msg = Utilities.GetLocalizedStringFromParent(this.ConfirmMessage, this); + } + + // must be done before render + this.OnClientClick = Utilities.GetOnClientClickConfirm(this, msg); + } + } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs index 0f2b4c3000a..42f5e46ae27 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs @@ -39,45 +39,6 @@ public class DnnDropDownList : Panel, INamingContainer private DnnGenericHiddenField _stateControl; private HtmlAnchor _selectedValue; - internal DnnDropDownListOptions Options - { - get - { - return this._options.Value; - } - } - - protected DnnGenericHiddenField StateControl - { - get - { - this.EnsureChildControls(); - return this._stateControl; - } - } - - private HtmlAnchor SelectedValue - { - get - { - this.EnsureChildControls(); - return this._selectedValue; - } - } - - private bool UseUndefinedItem - { - get - { - return this.ViewState.GetValue("UseUndefinedItem", false); - } - - set - { - this.ViewState.SetValue("UseUndefinedItem", value, false); - } - } - /// /// Occurs when the selection from the list control changes between posts to the server. /// @@ -123,6 +84,45 @@ public ListItem SelectedItem this.StateControl.TypedValueOrDefault.SelectedItem = (value == null) ? null : new SerializableKeyValuePair(value.Value, value.Text); } } + + internal DnnDropDownListOptions Options + { + get + { + return this._options.Value; + } + } + + protected DnnGenericHiddenField StateControl + { + get + { + this.EnsureChildControls(); + return this._stateControl; + } + } + + private HtmlAnchor SelectedValue + { + get + { + this.EnsureChildControls(); + return this._selectedValue; + } + } + + private bool UseUndefinedItem + { + get + { + return this.ViewState.GetValue("UseUndefinedItem", false); + } + + set + { + this.ViewState.SetValue("UseUndefinedItem", value, false); + } + } /// /// Gets when this method returns, contains the 32-bit signed integer value equivalent to the number contained in @@ -283,6 +283,26 @@ public string ExpandPath ClientAPI.RegisterClientVariable(this.Page, this.ClientID + "_expandPath", value, true); } } + + internal static void RegisterClientScript(Page page, string skin) + { + ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/components/DropDownList/dnn.DropDownList.css", FileOrder.Css.ResourceCss); + if (!string.IsNullOrEmpty(skin)) + { + ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/components/DropDownList/dnn.DropDownList." + skin + ".css", FileOrder.Css.ResourceCss); + } + + ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/scripts/jquery/dnn.jScrollBar.css", FileOrder.Css.ResourceCss); + + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.extensions.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.DataStructures.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/jquery/jquery.mousewheel.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/jquery/dnn.jScrollBar.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.TreeView.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.DynamicTreeView.js"); + ClientResourceManager.RegisterScript(page, "~/Resources/Shared/Components/DropDownList/dnn.DropDownList.js"); + } protected override void CreateChildControls() { @@ -335,26 +355,6 @@ private static string LocalizeString(string key) return Localization.GetString(key, Localization.SharedResourceFile); } - internal static void RegisterClientScript(Page page, string skin) - { - ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/components/DropDownList/dnn.DropDownList.css", FileOrder.Css.ResourceCss); - if (!string.IsNullOrEmpty(skin)) - { - ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/components/DropDownList/dnn.DropDownList." + skin + ".css", FileOrder.Css.ResourceCss); - } - - ClientResourceManager.RegisterStyleSheet(page, "~/Resources/Shared/scripts/jquery/dnn.jScrollBar.css", FileOrder.Css.ResourceCss); - - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.extensions.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/dnn.DataStructures.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/jquery/jquery.mousewheel.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/jquery/dnn.jScrollBar.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.TreeView.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.DynamicTreeView.js"); - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/Components/DropDownList/dnn.DropDownList.js"); - } - private string GetPostBackScript() { var script = string.Empty; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListOptions.cs index aa98c0913bc..a88083da748 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListOptions.cs @@ -25,23 +25,14 @@ public class DnnDropDownListOptions [DataMember(Name = "initialState")] public DnnDropDownListState InitialState; - private List _onClientSelectionChanged; - - [DataMember(Name = "onSelectionChanged")] - public List OnClientSelectionChanged - { - get - { - return this._onClientSelectionChanged ?? (this._onClientSelectionChanged = new List()); - } - } - [DataMember(Name = "services")] public ItemListServicesOptions Services; [DataMember(Name = "itemList")] public ItemListOptions ItemList; + private List _onClientSelectionChanged; + public DnnDropDownListOptions() { this.SelectedItemCss = "selected-item"; @@ -49,5 +40,14 @@ public DnnDropDownListOptions() this.Services = new ItemListServicesOptions(); this.ItemList = new ItemListOptions(); } + + [DataMember(Name = "onSelectionChanged")] + public List OnClientSelectionChanged + { + get + { + return this._onClientSelectionChanged ?? (this._onClientSelectionChanged = new List()); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs index fa5f18e8bd7..03742168353 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs @@ -20,32 +20,6 @@ namespace DotNetNuke.Web.UI.WebControls [ToolboxData("<{0}:DnnFileDropDownList runat='server'>")] public class DnnFileDropDownList : DnnDropDownList { - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectFileDefaultText", Localization.SharedResourceFile); - this.Services.GetTreeMethod = "ItemListService/GetFiles"; - this.Services.SearchTreeMethod = "ItemListService/SearchFiles"; - this.Services.SortTreeMethod = "ItemListService/SortFiles"; - this.Services.ServiceRoot = "InternalServices"; - this.Options.ItemList.DisableUnspecifiedOrder = true; - - this.FolderId = Null.NullInteger; - } - - protected override void OnPreRender(EventArgs e) - { - this.AddCssClass("file"); - - if (this.IncludeNoneSpecificItem) - { - this.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, Null.NullInteger.ToString(CultureInfo.InvariantCulture)); - } - - base.OnPreRender(e); - } - /// /// Gets or sets the selected Folder in the control, or selects the Folder in the control. /// @@ -83,6 +57,32 @@ public string Filter get { return this.Services.Parameters.ContainsKey("filter") ? this.Services.Parameters["filter"] : string.Empty; } set { this.Services.Parameters["filter"] = value; } } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectFileDefaultText", Localization.SharedResourceFile); + this.Services.GetTreeMethod = "ItemListService/GetFiles"; + this.Services.SearchTreeMethod = "ItemListService/SearchFiles"; + this.Services.SortTreeMethod = "ItemListService/SortFiles"; + this.Services.ServiceRoot = "InternalServices"; + this.Options.ItemList.DisableUnspecifiedOrder = true; + + this.FolderId = Null.NullInteger; + } + + protected override void OnPreRender(EventArgs e) + { + this.AddCssClass("file"); + + if (this.IncludeNoneSpecificItem) + { + this.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, Null.NullInteger.ToString(CultureInfo.InvariantCulture)); + } + + base.OnPreRender(e); + } public bool IncludeNoneSpecificItem { get; set; } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs index ce17ee09399..30c525347e9 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs @@ -29,6 +29,35 @@ public class DnnFileEditControl : IntegerEditControl /// ----------------------------------------------------------------------------- public string FilePath { get; set; } + /// ----------------------------------------------------------------------------- + /// + /// Loads the Post Back Data and determines whether the value has change. + /// + /// + /// In this case because the is a contained control, we do not need + /// to process the PostBackData (it has been handled by the File Control). We just use + /// this method as the Framework calls it for us. + /// + /// A key to the PostBack Data to load. + /// A name value collection of postback data. + /// + /// ----------------------------------------------------------------------------- + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + bool dataChanged = false; + string presentValue = this.StringValue; + + // string postedValue = postCollection[string.Format("{0}FileControl$dnnFileUploadFileId", postDataKey)]; + string postedValue = this._fileControl.FileID.ToString(); + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue; + dataChanged = true; + } + + return dataChanged; + } + /// ----------------------------------------------------------------------------- /// /// Creates the control contained within this control. @@ -92,34 +121,5 @@ protected override void RenderEditMode(HtmlTextWriter writer) { this.RenderChildren(writer); } - - /// ----------------------------------------------------------------------------- - /// - /// Loads the Post Back Data and determines whether the value has change. - /// - /// - /// In this case because the is a contained control, we do not need - /// to process the PostBackData (it has been handled by the File Control). We just use - /// this method as the Framework calls it for us. - /// - /// A key to the PostBack Data to load. - /// A name value collection of postback data. - /// - /// ----------------------------------------------------------------------------- - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - bool dataChanged = false; - string presentValue = this.StringValue; - - // string postedValue = postCollection[string.Format("{0}FileControl$dnnFileUploadFileId", postDataKey)]; - string postedValue = this._fileControl.FileID.ToString(); - if (!presentValue.Equals(postedValue)) - { - this.Value = postedValue; - dataChanged = true; - } - - return dataChanged; - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs index 416590b9d56..1a5be592cb7 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs @@ -28,6 +28,10 @@ public class DnnFilePicker : CompositeControl, ILocalizable { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DnnFilePicker)); + private Panel _pnlContainer; + private Panel _pnlLeftDiv; + private Panel _pnlFolder; + /// /// Represents a possible mode for the File Control. /// @@ -48,10 +52,6 @@ protected enum FileControlMode /// Preview, } - - private Panel _pnlContainer; - private Panel _pnlLeftDiv; - private Panel _pnlFolder; private Label _lblFolder; private DropDownList _cboFolders; private Panel _pnlFile; @@ -70,6 +70,32 @@ protected enum FileControlMode private bool _localize = true; private int _maxHeight = 100; private int _maxWidth = 135; + + public int MaxHeight + { + get + { + return this._maxHeight; + } + + set + { + this._maxHeight = value; + } + } + + public int MaxWidth + { + get + { + return this._maxWidth; + } + + set + { + this._maxWidth = value; + } + } /// /// Gets a value indicating whether gets whether the control is on a Host or Portal Tab. @@ -90,30 +116,45 @@ protected bool IsHost return isHost; } } - - public int MaxHeight + + /// + /// Gets or sets the class to be used for the Labels. + /// + /// + /// Defaults to 'CommandButton'. + /// + /// A String. + public string CommandCssClass { get { - return this._maxHeight; + var cssClass = Convert.ToString(this.ViewState["CommandCssClass"]); + return string.IsNullOrEmpty(cssClass) ? "dnnSecondaryAction" : cssClass; } set { - this._maxHeight = value; + this.ViewState["CommandCssClass"] = value; } } - public int MaxWidth + /// + /// Gets or sets the file Filter to use. + /// + /// + /// Defaults to ''. + /// + /// a comma seperated list of file extenstions no wildcards or periods e.g. "jpg,png,gif". + public string FileFilter { get { - return this._maxWidth; + return this.ViewState["FileFilter"] != null ? (string)this.ViewState["FileFilter"] : string.Empty; } set { - this._maxWidth = value; + this.ViewState["FileFilter"] = value; } } @@ -184,47 +225,6 @@ protected PortalSettings PortalSettings return PortalController.Instance.GetCurrentPortalSettings(); } } - - /// - /// Gets or sets the class to be used for the Labels. - /// - /// - /// Defaults to 'CommandButton'. - /// - /// A String. - public string CommandCssClass - { - get - { - var cssClass = Convert.ToString(this.ViewState["CommandCssClass"]); - return string.IsNullOrEmpty(cssClass) ? "dnnSecondaryAction" : cssClass; - } - - set - { - this.ViewState["CommandCssClass"] = value; - } - } - - /// - /// Gets or sets the file Filter to use. - /// - /// - /// Defaults to ''. - /// - /// a comma seperated list of file extenstions no wildcards or periods e.g. "jpg,png,gif". - public string FileFilter - { - get - { - return this.ViewState["FileFilter"] != null ? (string)this.ViewState["FileFilter"] : string.Empty; - } - - set - { - this.ViewState["FileFilter"] = value; - } - } /// /// Gets or sets the FileID for the control. @@ -389,6 +389,63 @@ public bool ShowUpLoad public UserInfo User { get; set; } + public bool Localize + { + get + { + return this._localize; + } + + set + { + this._localize = value; + } + } + + public string LocalResourceFile { get; set; } + + public virtual void LocalizeStrings() + { + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); + this.EnsureChildControls(); + } + + /// + /// CreateChildControls overrides the Base class's method to correctly build the + /// control based on the configuration. + /// + protected override void CreateChildControls() + { + // First clear the controls collection + this.Controls.Clear(); + + this._pnlContainer = new Panel { CssClass = "dnnFilePicker" }; + + this._pnlLeftDiv = new Panel { CssClass = "dnnLeft" }; + + this.AddFolderArea(); + this.AddFileAndUploadArea(); + this.AddButtonArea(); + this.AddMessageRow(); + + this._pnlContainer.Controls.Add(this._pnlLeftDiv); + + this._pnlRightDiv = new Panel { CssClass = "dnnLeft" }; + + this.GeneratePreviewImage(); + + this._pnlContainer.Controls.Add(this._pnlRightDiv); + + this.Controls.Add(this._pnlContainer); + + base.CreateChildControls(); + } + /// /// AddButton adds a button to the Command Row. /// @@ -544,14 +601,14 @@ private void LoadFolders() var folders = FolderManager.Instance.GetFolders(this.PortalId, "READ,ADD", user.UserID); foreach (FolderInfo folder in folders) { - var folderItem = new ListItem - { - Text = + var folderItem = new ListItem + { + Text = folder.FolderPath == Null.NullString ? Utilities.GetLocalizedString("PortalRoot") - : folder.DisplayPath, - Value = folder.FolderPath, - }; + : folder.DisplayPath, + Value = folder.FolderPath, + }; this._cboFolders.Items.Add(folderItem); } } @@ -633,44 +690,6 @@ private void ShowImage() this._pnlRightDiv.Visible = true; } } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - this.LocalResourceFile = Utilities.GetLocalResourceFile(this); - this.EnsureChildControls(); - } - - /// - /// CreateChildControls overrides the Base class's method to correctly build the - /// control based on the configuration. - /// - protected override void CreateChildControls() - { - // First clear the controls collection - this.Controls.Clear(); - - this._pnlContainer = new Panel { CssClass = "dnnFilePicker" }; - - this._pnlLeftDiv = new Panel { CssClass = "dnnLeft" }; - - this.AddFolderArea(); - this.AddFileAndUploadArea(); - this.AddButtonArea(); - this.AddMessageRow(); - - this._pnlContainer.Controls.Add(this._pnlLeftDiv); - - this._pnlRightDiv = new Panel { CssClass = "dnnLeft" }; - - this.GeneratePreviewImage(); - - this._pnlContainer.Controls.Add(this._pnlRightDiv); - - this.Controls.Add(this._pnlContainer); - - base.CreateChildControls(); - } /// /// OnPreRender runs just before the control is rendered. @@ -867,24 +886,5 @@ private void UploadFile(object sender, EventArgs e) { this.Mode = FileControlMode.UpLoadFile; } - - public bool Localize - { - get - { - return this._localize; - } - - set - { - this._localize = value; - } - } - - public string LocalResourceFile { get; set; } - - public virtual void LocalizeStrings() - { - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs index e8f502513ea..b3d12e336df 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs @@ -26,48 +26,16 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnFilePickerUploader : UserControl, IFilePickerUploader { + protected DnnFileDropDownList FilesComboBox; + protected DnnFolderDropDownList FoldersComboBox; private const string MyFileName = "filepickeruploader.ascx"; private int? _portalId = null; private string _fileFilter; private string _folderPath = string.Empty; private bool _folderPathSet = false; - protected DnnFileDropDownList FilesComboBox; - protected DnnFolderDropDownList FoldersComboBox; protected Label FoldersLabel; protected DnnFileUpload FileUploadControl; - - protected string FolderLabel - { - get - { - return Localization.GetString("Folder", Localization.GetResourceFile(this, MyFileName)); - } - } - - protected string FileLabel - { - get - { - return Localization.GetString("File", Localization.GetResourceFile(this, MyFileName)); - } - } - - protected string UploadFileLabel - { - get - { - return Localization.GetString("UploadFile", Localization.GetResourceFile(this, MyFileName)); - } - } - - protected string DropFileLabel - { - get - { - return Localization.GetString("DropFile", Localization.GetResourceFile(this, MyFileName)); - } - } public bool UsePersonalFolder { get; set; } @@ -108,6 +76,38 @@ public string FilePath } } + protected string FolderLabel + { + get + { + return Localization.GetString("Folder", Localization.GetResourceFile(this, MyFileName)); + } + } + + protected string FileLabel + { + get + { + return Localization.GetString("File", Localization.GetResourceFile(this, MyFileName)); + } + } + + protected string UploadFileLabel + { + get + { + return Localization.GetString("UploadFile", Localization.GetResourceFile(this, MyFileName)); + } + } + + protected string DropFileLabel + { + get + { + return Localization.GetString("DropFile", Localization.GetResourceFile(this, MyFileName)); + } + } + public int FileID { get @@ -223,19 +223,19 @@ protected override void OnPreRender(EventArgs e) var userFolder = FolderManager.Instance.GetUserFolder(this.User ?? UserController.Instance.GetCurrentUserInfo()); if (this.FoldersComboBox.SelectedFolder.FolderID == userFolder.FolderID) { - this.FoldersComboBox.SelectedItem = new ListItem - { - Text = FolderManager.Instance.MyFolderName, - Value = userFolder.FolderID.ToString(CultureInfo.InvariantCulture), - }; + this.FoldersComboBox.SelectedItem = new ListItem + { + Text = FolderManager.Instance.MyFolderName, + Value = userFolder.FolderID.ToString(CultureInfo.InvariantCulture), + }; } else if (this.UsePersonalFolder) // if UserPersonalFolder is true, make sure the file is under the user folder. { - this.FoldersComboBox.SelectedItem = new ListItem - { - Text = FolderManager.Instance.MyFolderName, - Value = userFolder.FolderID.ToString(CultureInfo.InvariantCulture), - }; + this.FoldersComboBox.SelectedItem = new ListItem + { + Text = FolderManager.Instance.MyFolderName, + Value = userFolder.FolderID.ToString(CultureInfo.InvariantCulture), + }; this.FilesComboBox.SelectedFile = null; } @@ -249,10 +249,10 @@ protected override void OnPreRender(EventArgs e) var selectedItem = new SerializableKeyValuePair( this.FoldersComboBox.SelectedItem.Value, this.FoldersComboBox.SelectedItem.Text); - this.FileUploadControl.Options.FolderPicker.InitialState = new DnnDropDownListState - { - SelectedItem = selectedItem, - }; + this.FileUploadControl.Options.FolderPicker.InitialState = new DnnDropDownListState + { + SelectedItem = selectedItem, + }; this.FileUploadControl.Options.FolderPath = this.FoldersComboBox.SelectedFolder.FolderPath; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs index ea05a96f965..272a5e490cc 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs @@ -93,13 +93,13 @@ public class DnnFileUploadResources [DataContract] public class DnnFileUploadOptions { - private const int DefaultWidth = 780; - private const int DefaultHeight = 630; [DataMember(Name = "clientId")] public string ClientId; - [DataMember(Name = "moduleId")] public string ModuleId = string.Empty; + + private const int DefaultWidth = 780; + private const int DefaultHeight = 630; [DataMember(Name = "parentClientId")] public string ParentClientId; @@ -128,36 +128,10 @@ public class DnnFileUploadOptions [DataMember(Name = "height")] public int Height; - private Dictionary _parameters; - - [DataMember(Name = "parameters")] - public Dictionary Parameters - { - get - { - return this._parameters ?? (this._parameters = new Dictionary()); - } - } - [DataMember(Name = "folderPath")] public string FolderPath; - [DataMember(Name = "validationCode")] - public string ValidationCode - { - get - { - var portalSettings = PortalSettings.Current; - var parameters = new List() { this.Extensions }; - if (portalSettings != null) - { - parameters.Add(portalSettings.PortalId); - parameters.Add(portalSettings.UserInfo.UserID); - } - - return ValidationUtils.ComputeValidationCode(parameters); - } - } + private Dictionary _parameters; public DnnFileUploadOptions() { @@ -195,5 +169,31 @@ public DnnFileUploadOptions() UnzipFileSuccessPromptBody = Utilities.GetLocalizedString("FileUpload.UnzipFileSuccessPromptBody.Text"), }; } + + [DataMember(Name = "parameters")] + public Dictionary Parameters + { + get + { + return this._parameters ?? (this._parameters = new Dictionary()); + } + } + + [DataMember(Name = "validationCode")] + public string ValidationCode + { + get + { + var portalSettings = PortalSettings.Current; + var parameters = new List() { this.Extensions }; + if (portalSettings != null) + { + parameters.Add(portalSettings.PortalId); + parameters.Add(portalSettings.UserInfo.UserID); + } + + return ValidationUtils.ComputeValidationCode(parameters); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs index ca100dd0eb2..6754d299db8 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs @@ -22,6 +22,31 @@ namespace DotNetNuke.Web.UI.WebControls [ToolboxData("<{0}:DnnFolderDropDownList runat='server'>")] public class DnnFolderDropDownList : DnnDropDownList { + /// + /// Gets or sets the selected Folder in the control, or selects the Folder in the control. + /// + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public IFolderInfo SelectedFolder + { + get + { + var folderId = this.SelectedItemValueAsInt; + return (folderId == Null.NullInteger) ? null : FolderManager.Instance.GetFolder(folderId); + } + + set + { + var folderName = value != null ? value.FolderName : null; + if (folderName == string.Empty) + { + folderName = PortalSettings.Current.ActiveTab.IsSuperTab ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder; + } + + this.SelectedItem = (value != null) ? new ListItem() { Text = folderName, Value = value.FolderID.ToString(CultureInfo.InvariantCulture) } : null; + } + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -57,30 +82,5 @@ protected override void OnPreRender(EventArgs e) this.ExpandPath = folderLevel.TrimEnd(','); } } - - /// - /// Gets or sets the selected Folder in the control, or selects the Folder in the control. - /// - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public IFolderInfo SelectedFolder - { - get - { - var folderId = this.SelectedItemValueAsInt; - return (folderId == Null.NullInteger) ? null : FolderManager.Instance.GetFolder(folderId); - } - - set - { - var folderName = value != null ? value.FolderName : null; - if (folderName == string.Empty) - { - folderName = PortalSettings.Current.ActiveTab.IsSuperTab ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder; - } - - this.SelectedItem = (value != null) ? new ListItem() { Text = folderName, Value = value.FolderID.ToString(CultureInfo.InvariantCulture) } : null; - } - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs index 880b0ef577b..750ccf2ae3b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs @@ -33,22 +33,6 @@ public DnnFormEditor() this.ViewStateMode = ViewStateMode.Disabled; } - protected string LocalResourceFile - { - get - { - return Utilities.GetLocalResourceFile(this); - } - } - - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - public object DataSource { get @@ -71,6 +55,22 @@ public object DataSource public DnnFormMode FormMode { get; set; } + protected string LocalResourceFile + { + get + { + return Utilities.GetLocalResourceFile(this); + } + } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + public bool EncryptIds { get; set; } public bool IsValid @@ -107,6 +107,35 @@ public bool IsValid [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Tabs { get; private set; } + public override void DataBind() + { + this.OnDataBinding(EventArgs.Empty); + this.Controls.Clear(); + this.ClearChildViewState(); + this.TrackViewState(); + this.CreateControlHierarchy(true); + this.ChildControlsCreated = true; + } + + [Obsolete("Obsoleted in Platform 7.4.1, please add encryptIds. Scheduled removal in v10.0.0.")] + internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile) + { + SetUpItems(items, parentControl, localResourceFile, false); + } + + internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile, bool encryptIds) + { + foreach (DnnFormItemBase item in items) + { + if (encryptIds) + { + item.ID = (Host.GUID.Substring(0, 7) + item.ID + DateTime.Now.Day).GenerateHash(); + } + + parentControl.Controls.Add(item); + } + } + private List GetAllItems() { var items = new List(); @@ -134,22 +163,39 @@ private List GetAllItems() return items; } - [Obsolete("Obsoleted in Platform 7.4.1, please add encryptIds. Scheduled removal in v10.0.0.")] - internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile) + protected override void CreateChildControls() { - SetUpItems(items, parentControl, localResourceFile, false); + // CreateChildControls re-creates the children (the items) + // using the saved view state. + // First clear any existing child controls. + this.Controls.Clear(); + + // Create the items only if there is view state + // corresponding to the children. + if (this._itemCount > 0) + { + this.CreateControlHierarchy(false); + } } - internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile, bool encryptIds) + protected virtual void CreateControlHierarchy(bool useDataSource) { - foreach (DnnFormItemBase item in items) - { - if (encryptIds) - { - item.ID = (Host.GUID.Substring(0, 7) + item.ID + DateTime.Now.Day).GenerateHash(); - } + this.CssClass = string.IsNullOrEmpty(this.CssClass) ? "dnnForm" : this.CssClass.Contains("dnnForm") ? this.CssClass : string.Format("dnnForm {0}", this.CssClass); - parentControl.Controls.Add(item); + this.SetUpTabs(); + + this.SetUpSections(this.Sections, this); + + SetUpItems(this.Items, this, this.LocalResourceFile, this.EncryptIds); + + this.DataBindItems(useDataSource); + } + + protected override void LoadControlState(object state) + { + if (state != null) + { + this._itemCount = (int)state; } } @@ -223,21 +269,6 @@ private void SetUpTabs() } } } - - protected override void CreateChildControls() - { - // CreateChildControls re-creates the children (the items) - // using the saved view state. - // First clear any existing child controls. - this.Controls.Clear(); - - // Create the items only if there is view state - // corresponding to the children. - if (this._itemCount > 0) - { - this.CreateControlHierarchy(false); - } - } private void DataBindItems(bool useDataSource) { @@ -265,37 +296,6 @@ private void DataBindItems(bool useDataSource) this._itemCount = this.GetAllItems().Count; } - protected virtual void CreateControlHierarchy(bool useDataSource) - { - this.CssClass = string.IsNullOrEmpty(this.CssClass) ? "dnnForm" : this.CssClass.Contains("dnnForm") ? this.CssClass : string.Format("dnnForm {0}", this.CssClass); - - this.SetUpTabs(); - - this.SetUpSections(this.Sections, this); - - SetUpItems(this.Items, this, this.LocalResourceFile, this.EncryptIds); - - this.DataBindItems(useDataSource); - } - - public override void DataBind() - { - this.OnDataBinding(EventArgs.Empty); - this.Controls.Clear(); - this.ClearChildViewState(); - this.TrackViewState(); - this.CreateControlHierarchy(true); - this.ChildControlsCreated = true; - } - - protected override void LoadControlState(object state) - { - if (state != null) - { - this._itemCount = (int)state; - } - } - protected override void OnInit(EventArgs e) { this.Page.RegisterRequiresControlState(this); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs index c0a7ed66d61..57e0dc06552 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs @@ -30,6 +30,14 @@ protected DnnFormItemBase() this.Validators = new List(); } + + public object Value + { + get { return this._value; } + set { this._value = value; } + } + + public string DataField { get; set; } protected PropertyInfo ChildProperty { @@ -66,22 +74,14 @@ protected override HtmlTextWriterTag TagKey } } - public object Value - { - get { return this._value; } - set { this._value = value; } - } - - public string DataField { get; set; } - public string DataMember { get; set; } - internal object DataSource { get; set; } - public DnnFormMode FormMode { get; set; } public bool IsValid { get; private set; } + internal object DataSource { get; set; } + public string OnClientClicked { get; set; } public string LocalResourceFile { get; set; } @@ -122,52 +122,6 @@ public string ValidationMessageSuffix public List Validators { get; private set; } public string ValidationExpression { get; set; } - - private void AddValidators(string controlId) - { - var value = this.Value as string; - this.Validators.Clear(); - - // Add Validators - if (this.Required) - { - var requiredValidator = new RequiredFieldValidator - { - ID = this.ID + "_Required", - ErrorMessage = this.ResourceKey + this.RequiredMessageSuffix, - }; - this.Validators.Add(requiredValidator); - } - - if (!string.IsNullOrEmpty(this.ValidationExpression)) - { - var regexValidator = new RegularExpressionValidator - { - ID = this.ID + "_RegEx", - ErrorMessage = this.ResourceKey + this.ValidationMessageSuffix, - ValidationExpression = this.ValidationExpression, - }; - if (!string.IsNullOrEmpty(value)) - { - regexValidator.IsValid = Regex.IsMatch(value, this.ValidationExpression); - this.IsValid = regexValidator.IsValid; - } - - this.Validators.Add(regexValidator); - } - - if (this.Validators.Count > 0) - { - foreach (BaseValidator validator in this.Validators) - { - validator.ControlToValidate = controlId; - validator.Display = ValidatorDisplay.Dynamic; - validator.ErrorMessage = this.LocalizeString(validator.ErrorMessage); - validator.CssClass = "dnnFormMessage dnnFormError"; - this.Controls.Add(validator); - } - } - } public void CheckIsValid() { @@ -183,6 +137,29 @@ public void CheckIsValid() } } + public void DataBindItem(bool useDataSource) + { + if (useDataSource) + { + this.OnDataBinding(EventArgs.Empty); + this.Controls.Clear(); + this.ClearChildViewState(); + this.TrackViewState(); + + this.DataBindInternal(); + + this.CreateControlHierarchy(); + this.ChildControlsCreated = true; + } + else + { + if (!string.IsNullOrEmpty(this.DataField)) + { + this.UpdateDataSourceInternal(null, this._value, this.DataField); + } + } + } + protected virtual void CreateControlHierarchy() { // Load Item Style @@ -195,13 +172,13 @@ protected virtual void CreateControlHierarchy() } // Add Label - var label = new DnnFormLabel - { - LocalResourceFile = this.LocalResourceFile, - ResourceKey = this.ResourceKey + ".Text", - ToolTipKey = this.ResourceKey + ".Help", - ViewStateMode = ViewStateMode.Disabled, - }; + var label = new DnnFormLabel + { + LocalResourceFile = this.LocalResourceFile, + ResourceKey = this.ResourceKey + ".Text", + ToolTipKey = this.ResourceKey + ".Help", + ViewStateMode = ViewStateMode.Disabled, + }; if (this.Required) { @@ -214,6 +191,52 @@ protected virtual void CreateControlHierarchy() label.AssociatedControlID = inputControl.ID; this.AddValidators(inputControl.ID); } + + private void AddValidators(string controlId) + { + var value = this.Value as string; + this.Validators.Clear(); + + // Add Validators + if (this.Required) + { + var requiredValidator = new RequiredFieldValidator + { + ID = this.ID + "_Required", + ErrorMessage = this.ResourceKey + this.RequiredMessageSuffix, + }; + this.Validators.Add(requiredValidator); + } + + if (!string.IsNullOrEmpty(this.ValidationExpression)) + { + var regexValidator = new RegularExpressionValidator + { + ID = this.ID + "_RegEx", + ErrorMessage = this.ResourceKey + this.ValidationMessageSuffix, + ValidationExpression = this.ValidationExpression, + }; + if (!string.IsNullOrEmpty(value)) + { + regexValidator.IsValid = Regex.IsMatch(value, this.ValidationExpression); + this.IsValid = regexValidator.IsValid; + } + + this.Validators.Add(regexValidator); + } + + if (this.Validators.Count > 0) + { + foreach (BaseValidator validator in this.Validators) + { + validator.ControlToValidate = controlId; + validator.Display = ValidatorDisplay.Dynamic; + validator.ErrorMessage = this.LocalizeString(validator.ErrorMessage); + validator.CssClass = "dnnFormMessage dnnFormError"; + this.Controls.Add(validator); + } + } + } /// /// Use container to add custom control hierarchy to. @@ -282,27 +305,18 @@ protected virtual void DataBindInternal() this.DataBindInternal(this.DataField, ref this._value); } - public void DataBindItem(bool useDataSource) + protected void UpdateDataSource(object oldValue, object newValue, string dataField) { - if (useDataSource) - { - this.OnDataBinding(EventArgs.Empty); - this.Controls.Clear(); - this.ClearChildViewState(); - this.TrackViewState(); + this.CheckIsValid(); - this.DataBindInternal(); + this._value = newValue; - this.CreateControlHierarchy(); - this.ChildControlsCreated = true; - } - else - { - if (!string.IsNullOrEmpty(this.DataField)) - { - this.UpdateDataSourceInternal(null, this._value, this.DataField); - } - } + this.UpdateDataSourceInternal(oldValue, newValue, dataField); + } + + protected override void LoadControlState(object state) + { + this._value = state; } private void UpdateDataSourceInternal(object oldValue, object newValue, string dataField) @@ -379,20 +393,6 @@ private void UpdateDataSourceInternal(object oldValue, object newValue, string d } } - protected void UpdateDataSource(object oldValue, object newValue, string dataField) - { - this.CheckIsValid(); - - this._value = newValue; - - this.UpdateDataSourceInternal(oldValue, newValue, dataField); - } - - protected override void LoadControlState(object state) - { - this._value = state; - } - protected string LocalizeString(string key) { return Localization.GetString(key, this.LocalResourceFile); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs index dcefdc244d0..41eb322dd2b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs @@ -43,11 +43,6 @@ public string ContainerCssClass } } - private void TextChanged(object sender, EventArgs e) - { - this.UpdateDataSource(this.Value, this._password.Text, this.DataField); - } - /// /// Use container to add custom control hierarchy to. /// @@ -90,6 +85,11 @@ protected override void OnInit(EventArgs e) JavaScript.RequestRegistration(CommonJs.DnnPlugins); } + private void TextChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this._password.Text, this.DataField); + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs index cb9f863efd1..058e269249c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs @@ -19,8 +19,6 @@ public DnnFormTab() public bool IncludeExpandAll { get; set; } - internal string ExpandAllScript { get; set; } - [Category("Behavior")] [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] @@ -31,6 +29,8 @@ public DnnFormTab() [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Sections { get; private set; } + internal string ExpandAllScript { get; set; } + public string ResourceKey { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs index 56baf13335e..a66604450be 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs @@ -41,11 +41,6 @@ public string TextBoxCssClass /// public bool ClearContentInPasswordMode { get; set; } - private void TextChanged(object sender, EventArgs e) - { - this.UpdateDataSource(this.Value, this._textBox.Text, this.DataField); - } - protected override WebControl CreateControlInternal(Control container) { this._textBox = new TextBox { ID = this.ID + "_TextBox" }; @@ -84,5 +79,10 @@ protected override void OnPreRender(EventArgs e) this._textBox.Attributes.Add("value", Convert.ToString(this.Value)); } } + + private void TextChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this._textBox.Text, this.DataField); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs index 485bc720f95..091df32a75b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs @@ -44,6 +44,12 @@ public bool HasValue get { return this._typedValue != null; } } + public override void RenderControl(HtmlTextWriter writer) + { + this.EnsureValue(); + base.RenderControl(writer); + } + protected override object SaveViewState() { this.EnsureValue(); @@ -67,6 +73,12 @@ protected override bool LoadPostData(string postDataKey, NameValueCollection pos return controlsStateChanged; } + protected override void TrackViewState() + { + this.EnsureValue(); + base.TrackViewState(); + } + private void SetTypedValue() { this._typedValue = string.IsNullOrEmpty(this.Value) ? null : Json.Deserialize(this.Value); @@ -85,17 +97,5 @@ private void SerializeValue() this.Value = this._typedValue == null ? string.Empty : Json.Serialize(this._typedValue); this._isValueSerialized = true; } - - protected override void TrackViewState() - { - this.EnsureValue(); - base.TrackViewState(); - } - - public override void RenderControl(HtmlTextWriter writer) - { - this.EnsureValue(); - base.RenderControl(writer); - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs index c84604c77cc..793ebc8723c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs @@ -18,18 +18,6 @@ public DnnLabel() this.CssClass = "dnnFormLabel"; } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - this.LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - this.LocalizeStrings(); - base.Render(writer); - } - public bool Localize { get @@ -67,5 +55,17 @@ public virtual void LocalizeStrings() } } } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); + } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs index a39c48c3de0..71d8bdc1b15 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs @@ -37,6 +37,14 @@ public string Language } } + public bool Localize { get; set; } + + public string LocalResourceFile { get; set; } + + public virtual void LocalizeStrings() + { + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -117,13 +125,5 @@ protected override void OnPreRender(EventArgs e) this._Label.Text = localeName; this._Flag.AlternateText = localeName; } - - public bool Localize { get; set; } - - public string LocalResourceFile { get; set; } - - public virtual void LocalizeStrings() - { - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs index 46429c62bd7..3728f5e58e8 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs @@ -13,18 +13,6 @@ public class DnnLiteral : Literal, ILocalizable { private bool _Localize = true; - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - this.LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - this.LocalizeStrings(); - base.Render(writer); - } - public bool Localize { get @@ -50,5 +38,17 @@ public virtual void LocalizeStrings() } } } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); + } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs index 91bfdaea99f..e103b5a029b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs @@ -22,6 +22,22 @@ namespace DotNetNuke.Web.UI.WebControls [ToolboxData("<{0}:DnnPageDropDownList runat='server'>")] public class DnnPageDropDownList : DnnDropDownList { + /// + /// Gets or sets a value indicating whether whether disabled pages are not selectable + /// Please note: IncludeDisabledTabs needs also be set to true to include disabled pages. + /// + public bool DisabledNotSelectable { get; set; } + + /// + /// Gets or sets a value indicating whether whether include active page. + /// + public bool IncludeActiveTab { get; set; } + + /// + /// Gets or sets a value indicating whether whether include pages which are disabled. + /// + public bool IncludeDisabledTabs { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -70,22 +86,6 @@ protected override void OnPreRender(EventArgs e) } } - /// - /// Gets or sets a value indicating whether whether disabled pages are not selectable - /// Please note: IncludeDisabledTabs needs also be set to true to include disabled pages. - /// - public bool DisabledNotSelectable { get; set; } - - /// - /// Gets or sets a value indicating whether whether include active page. - /// - public bool IncludeActiveTab { get; set; } - - /// - /// Gets or sets a value indicating whether whether include pages which are disabled. - /// - public bool IncludeDisabledTabs { get; set; } - /// /// Gets or sets a value indicating whether whether include pages which tab type is not normal. /// @@ -114,19 +114,6 @@ public int PortalId } } - private int? InternalPortalId - { - get - { - return this.ViewState.GetValue("PortalId", null); - } - - set - { - this.ViewState.SetValue("PortalId", value, null); - } - } - /// /// Gets or sets the selected Page in the control, or selects the Page in the control. /// @@ -150,5 +137,18 @@ public TabInfo SelectedPage /// Gets or sets specific to only show tabs which have view permission on these roles. /// public IList Roles { get; set; } + + private int? InternalPortalId + { + get + { + return this.ViewState.GetValue("PortalId", null); + } + + set + { + this.ViewState.SetValue("PortalId", value, null); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs index e5ff39cc062..24cfbac9bf3 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs @@ -21,25 +21,6 @@ public class DnnPortalPageDropDownList : DnnDropDownList { private readonly Lazy _portalId = new Lazy(() => PortalSettings.Current.ActiveTab.IsSuperTab ? -1 : PortalSettings.Current.PortalId); - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectWebPageDefaultText", Localization.SharedResourceFile); - this.Services.GetTreeMethod = "ItemListService/GetPagesInPortalGroup"; - this.Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendantsInPortalGroup"; - this.Services.SearchTreeMethod = "ItemListService/SearchPagesInPortalGroup"; - this.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPageInPortalGroup"; - this.Services.SortTreeMethod = "ItemListService/SortPagesInPortalGroup"; - this.Services.ServiceRoot = "InternalServices"; - } - - protected override void OnPreRender(EventArgs e) - { - this.AddCssClass("page"); - base.OnPreRender(e); - } - /// /// Gets or sets the selected Page in the control, or selects the Page in the control. /// @@ -58,5 +39,24 @@ public TabInfo SelectedPage this.SelectedItem = (value != null) ? new ListItem() { Text = value.IndentedTabName, Value = value.TabID.ToString(CultureInfo.InvariantCulture) } : null; } } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectWebPageDefaultText", Localization.SharedResourceFile); + this.Services.GetTreeMethod = "ItemListService/GetPagesInPortalGroup"; + this.Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendantsInPortalGroup"; + this.Services.SearchTreeMethod = "ItemListService/SearchPagesInPortalGroup"; + this.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPageInPortalGroup"; + this.Services.SortTreeMethod = "ItemListService/SortPagesInPortalGroup"; + this.Services.ServiceRoot = "InternalServices"; + } + + protected override void OnPreRender(EventArgs e) + { + this.AddCssClass("page"); + base.OnPreRender(e); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs index 8f9dc2cb5cc..de0b5ab76de 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs @@ -18,18 +18,6 @@ public DnnRadioButton() this.CssClass = "SubHead dnnLabel"; } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - this.LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - this.LocalizeStrings(); - base.Render(writer); - } - public bool Localize { get @@ -65,5 +53,17 @@ public virtual void LocalizeStrings() } } } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); + } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs index d191bf4d2ac..b86f37fc4bd 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs @@ -47,6 +47,22 @@ public virtual bool CheckToolVisibility } } + public override Control FindControl(string id) + { + this.EnsureChildControls(); + return base.FindControl(id); + } + + public override void RenderControl(HtmlTextWriter writer) + { + if (this.CheckVisibility()) + { + this.RenderBeginTag(writer); + this.RenderChildren(writer); + this.RenderEndTag(writer); + } + } + protected override void CreateChildControls() { this.Controls.Clear(); @@ -135,21 +151,5 @@ private bool AreChildToolsVisible(ref ControlCollection children, ref bool found return returnValue; } - - public override Control FindControl(string id) - { - this.EnsureChildControls(); - return base.FindControl(id); - } - - public override void RenderControl(HtmlTextWriter writer) - { - if (this.CheckVisibility()) - { - this.RenderBeginTag(writer); - this.RenderChildren(writer); - this.RenderEndTag(writer); - } - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs index cfc2a6a806c..6cdee9ac980 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs @@ -27,16 +27,16 @@ namespace DotNetNuke.Web.UI.WebControls [ParseChildren(true)] public class DnnRibbonBarTool : Control, IDnnRibbonBarTool { - protected INavigationManager NavigationManager { get; } + private IDictionary _allTools; + private DnnTextLink _dnnLink; + private DnnTextButton _dnnLinkButton; public DnnRibbonBarTool() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } - private IDictionary _allTools; - private DnnTextLink _dnnLink; - private DnnTextButton _dnnLinkButton; + protected INavigationManager NavigationManager { get; } public virtual RibbonBarToolInfo ToolInfo { @@ -108,6 +108,26 @@ public virtual string ToolTip } } + public virtual string ToolName + { + get + { + return this.ToolInfo.ToolName; + } + + set + { + if (this.AllTools.ContainsKey(value)) + { + this.ToolInfo = this.AllTools[value]; + } + else + { + throw new NotSupportedException("Tool not found [" + value + "]"); + } + } + } + protected virtual DnnTextButton DnnLinkButton { get @@ -177,46 +197,6 @@ private static PortalSettings PortalSettings } } - public virtual string ToolName - { - get - { - return this.ToolInfo.ToolName; - } - - set - { - if (this.AllTools.ContainsKey(value)) - { - this.ToolInfo = this.AllTools[value]; - } - else - { - throw new NotSupportedException("Tool not found [" + value + "]"); - } - } - } - - protected override void CreateChildControls() - { - this.Controls.Clear(); - this.Controls.Add(this.DnnLinkButton); - this.Controls.Add(this.DnnLink); - } - - protected override void OnInit(EventArgs e) - { - this.EnsureChildControls(); - this.DnnLinkButton.Click += this.ControlPanelTool_OnClick; - } - - protected override void OnPreRender(EventArgs e) - { - this.ProcessTool(); - this.Visible = this.DnnLink.Visible || this.DnnLinkButton.Visible; - base.OnPreRender(e); - } - public virtual void ControlPanelTool_OnClick(object sender, EventArgs e) { switch (this.ToolInfo.ToolName) @@ -265,6 +245,26 @@ public virtual void ControlPanelTool_OnClick(object sender, EventArgs e) } } + protected override void CreateChildControls() + { + this.Controls.Clear(); + this.Controls.Add(this.DnnLinkButton); + this.Controls.Add(this.DnnLink); + } + + protected override void OnInit(EventArgs e) + { + this.EnsureChildControls(); + this.DnnLinkButton.Click += this.ControlPanelTool_OnClick; + } + + protected override void OnPreRender(EventArgs e) + { + this.ProcessTool(); + this.Visible = this.DnnLink.Visible || this.DnnLinkButton.Visible; + base.OnPreRender(e); + } + protected virtual void ProcessTool() { this.DnnLink.Visible = false; @@ -595,11 +595,6 @@ protected virtual string GetString(string key) return Utilities.GetLocalizedStringFromParent(key, this); } - private static ModuleInfo GetInstalledModule(int portalID, string friendlyName) - { - return ModuleController.Instance.GetModuleByDefinition(portalID, friendlyName); - } - protected virtual void ClearCache() { DataCache.ClearCache(); @@ -612,5 +607,10 @@ protected virtual void RestartApplication() LogController.Instance.AddLog(log); Config.Touch(); } + + private static ModuleInfo GetInstalledModule(int portalID, string friendlyName) + { + return ModuleController.Instance.GetModuleByDefinition(portalID, friendlyName); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs index 9ff4c53b636..7d17418df2a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs @@ -29,6 +29,12 @@ public override ControlCollection Controls [TemplateInstance(TemplateInstance.Single)] public virtual ITemplate Content { get; set; } + public override Control FindControl(string id) + { + this.EnsureChildControls(); + return base.FindControl(id); + } + protected override void CreateChildControls() { this.Controls.Clear(); @@ -39,12 +45,6 @@ protected override void CreateChildControls() } } - public override Control FindControl(string id) - { - this.EnsureChildControls(); - return base.FindControl(id); - } - protected override void Render(HtmlTextWriter writer) { this.RenderBeginTag(writer); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs index 2e6690cd5ad..ee218de93b7 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs @@ -82,25 +82,6 @@ public override string CssClass } } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - this.LocalResourceFile = Utilities.GetLocalResourceFile(this); - } - - protected override void Render(HtmlTextWriter writer) - { - this.LocalizeStrings(); - if (!this.Enabled && !string.IsNullOrEmpty(this.DisabledCssClass)) - { - this.CssClass = this.DisabledCssClass; - } - - writer.AddAttribute("class", this.CssClass.Trim()); - base.Render(writer); - } - public bool Localize { get @@ -141,5 +122,24 @@ public virtual void LocalizeStrings() } } } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + this.LocalResourceFile = Utilities.GetLocalResourceFile(this); + } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + if (!this.Enabled && !string.IsNullOrEmpty(this.DisabledCssClass)) + { + this.CssClass = this.DisabledCssClass; + } + + writer.AddAttribute("class", this.CssClass.Trim()); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs index 9472bcaacd4..6c7732be3e0 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs @@ -106,6 +106,21 @@ public string Target this.ViewState["DisabledCssClass"] = value; } } + + public bool Localize + { + get + { + return this._localize; + } + + set + { + this._localize = value; + } + } + + public string LocalResourceFile { get; set; } private HyperLink TextHyperlinkControl { @@ -120,6 +135,32 @@ private HyperLink TextHyperlinkControl } } + public virtual void LocalizeStrings() + { + if (this.Localize) + { + if (!string.IsNullOrEmpty(this.ToolTip)) + { + this.ToolTip = Localization.GetString(this.ToolTip, this.LocalResourceFile); + } + + if (!string.IsNullOrEmpty(this.Text)) + { + this.Text = Localization.GetString(this.Text, this.LocalResourceFile); + + if (string.IsNullOrEmpty(this.ToolTip)) + { + this.ToolTip = Localization.GetString(string.Format("{0}.ToolTip", this.Text), this.LocalResourceFile); + } + + if (string.IsNullOrEmpty(this.ToolTip)) + { + this.ToolTip = this.Text; + } + } + } + } + protected override void CreateChildControls() { this.Controls.Clear(); @@ -150,46 +191,5 @@ protected override void Render(HtmlTextWriter writer) this.RenderChildren(writer); this.RenderEndTag(writer); } - - public bool Localize - { - get - { - return this._localize; - } - - set - { - this._localize = value; - } - } - - public string LocalResourceFile { get; set; } - - public virtual void LocalizeStrings() - { - if (this.Localize) - { - if (!string.IsNullOrEmpty(this.ToolTip)) - { - this.ToolTip = Localization.GetString(this.ToolTip, this.LocalResourceFile); - } - - if (!string.IsNullOrEmpty(this.Text)) - { - this.Text = Localization.GetString(this.Text, this.LocalResourceFile); - - if (string.IsNullOrEmpty(this.ToolTip)) - { - this.ToolTip = Localization.GetString(string.Format("{0}.ToolTip", this.Text), this.LocalResourceFile); - } - - if (string.IsNullOrEmpty(this.ToolTip)) - { - this.ToolTip = this.Text; - } - } - } - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs index 7cda3f7c275..85608ee10eb 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs @@ -26,17 +26,6 @@ public override string EditControlClientId return this.TimeZones.ClientID; } } - - protected override void CreateChildControls() - { - this.TimeZones = new DnnTimeZoneComboBox(); - this.TimeZones.ViewStateMode = ViewStateMode.Disabled; - - this.Controls.Clear(); - this.Controls.Add(this.TimeZones); - - base.CreateChildControls(); - } public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { @@ -51,6 +40,17 @@ public override bool LoadPostData(string postDataKey, System.Collections.Special return dataChanged; } + + protected override void CreateChildControls() + { + this.TimeZones = new DnnTimeZoneComboBox(); + this.TimeZones.ViewStateMode = ViewStateMode.Disabled; + + this.Controls.Clear(); + this.Controls.Add(this.TimeZones); + + base.CreateChildControls(); + } protected override void OnDataChanged(EventArgs e) { diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs index e659f3b45b6..8ec9bbd1360 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs @@ -27,11 +27,6 @@ public DnnUnsortedList() { } - protected override sealed ControlCollection CreateControlCollection() - { - return new TypedControlCollection(this); - } - [PersistenceMode(PersistenceMode.InnerDefaultProperty)] [MergableProperty(false)] public virtual UniformControlCollection ListItems @@ -42,15 +37,6 @@ public virtual UniformControlCollection Li } } - protected override void AddAttributesToRender(HtmlTextWriter writer) - { - writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); - if (!string.IsNullOrEmpty(this.CssClass)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); - } - } - /// /// A "macro" that adds a set of controls or control as a single list item (li). Use ListItems.Add(UnsortedListItem) method. /// @@ -63,5 +49,19 @@ public void AddListItem(params Control[] listItemControls) listItem.AddControls(listItemControls); this.ListItems.Add(listItem); } + + protected override sealed ControlCollection CreateControlCollection() + { + return new TypedControlCollection(this); + } + + protected override void AddAttributesToRender(HtmlTextWriter writer) + { + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + if (!string.IsNullOrEmpty(this.CssClass)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs index 7e943c98935..a9f3f42e691 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs @@ -33,13 +33,13 @@ public abstract class DnnUrlControl : UserControlBase protected Panel TypeRow; protected Panel URLRow; protected Panel UserRow; + protected DropDownList cboImages; + protected DnnPageDropDownList cboTabs; private bool _doChangeURL; private bool _doRenderTypeControls; private bool _doRenderTypes; private string _localResourceFile; private PortalInfo _objPortal; - protected DropDownList cboImages; - protected DnnPageDropDownList cboTabs; protected DropDownList cboUrls; protected CheckBox chkLog; protected CheckBox chkNewWindow; @@ -562,6 +562,61 @@ public string Width } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + // prevent unauthorized access + if (this.Request.IsAuthenticated == false) + { + this.Visible = false; + } + + ClientResourceManager.EnableAsyncPostBackHandler(); + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.optType.SelectedIndexChanged += this.optType_SelectedIndexChanged; + this.cmdAdd.Click += this.cmdAdd_Click; + this.cmdDelete.Click += this.cmdDelete_Click; + this.cmdSelect.Click += this.cmdSelect_Click; + + this.ErrorRow.Visible = false; + + try + { + 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"])); + } + else + { + this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); + } + + if (this.ViewState["IsUrlControlLoaded"] == null) + { + // If Not Page.IsPostBack Then + // let's make at least an initialization + // The type radio button must be initialized + // The url must be initialized no matter its value + this._doRenderTypes = true; + this._doChangeURL = true; + ClientAPI.AddButtonConfirm(this.cmdDelete, Localization.GetString("DeleteItem")); + + // The following line was mover to the pre-render event to ensure render for the first time + // ViewState("IsUrlControlLoaded") = "Loaded" + } + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private void LoadUrls() { var objUrls = new UrlController(); @@ -985,61 +1040,6 @@ private void DoRenderTypeControls() this.UserRow.Visible = false; } } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - // prevent unauthorized access - if (this.Request.IsAuthenticated == false) - { - this.Visible = false; - } - - ClientResourceManager.EnableAsyncPostBackHandler(); - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.optType.SelectedIndexChanged += this.optType_SelectedIndexChanged; - this.cmdAdd.Click += this.cmdAdd_Click; - this.cmdDelete.Click += this.cmdDelete_Click; - this.cmdSelect.Click += this.cmdSelect_Click; - - this.ErrorRow.Visible = false; - - try - { - 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"])); - } - else - { - this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); - } - - if (this.ViewState["IsUrlControlLoaded"] == null) - { - // If Not Page.IsPostBack Then - // let's make at least an initialization - // The type radio button must be initialized - // The url must be initialized no matter its value - this._doRenderTypes = true; - this._doChangeURL = true; - ClientAPI.AddButtonConfirm(this.cmdDelete, Localization.GetString("DeleteItem")); - - // The following line was mover to the pre-render event to ensure render for the first time - // ViewState("IsUrlControlLoaded") = "Loaded" - } - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } protected override void OnPreRender(EventArgs e) { diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs index 938ae69195d..df929f7ffe0 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs @@ -18,12 +18,6 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// public class DnnCheckBoxList : CheckBoxList { - protected override void OnInit(EventArgs e) - { - this.RepeatColumns = 1; - base.OnInit(e); - } - private string _initValue; public override string SelectedValue @@ -46,14 +40,6 @@ public override string SelectedValue } } - protected override void OnPreRender(EventArgs e) - { - Utilities.ApplySkin(this); - this.RegisterRequestResources(); - - base.OnPreRender(e); - } - public override void DataBind() { if (!string.IsNullOrEmpty(this._initValue)) @@ -70,6 +56,20 @@ public void AddItem(string text, string value) { this.Items.Add(new ListItem(text, value)); } + + protected override void OnInit(EventArgs e) + { + this.RepeatColumns = 1; + base.OnInit(e); + } + + protected override void OnPreRender(EventArgs e) + { + Utilities.ApplySkin(this); + this.RegisterRequestResources(); + + base.OnPreRender(e); + } public void InsertItem(int index, string text, string value) { diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs index e64b65f457a..717218b8def 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs @@ -75,6 +75,8 @@ public string Value } } + public DnnComboBoxOption Options { get; set; } = new DnnComboBoxOption(); + protected override HtmlTextWriterTag TagKey { get @@ -83,7 +85,22 @@ protected override HtmlTextWriterTag TagKey } } - public DnnComboBoxOption Options { get; set; } = new DnnComboBoxOption(); + public override void DataBind() + { + if (!string.IsNullOrEmpty(this._initValue)) + { + this.DataBind(this._initValue); + } + else + { + base.DataBind(); + } + } + + public void AddItem(string text, string value) + { + this.Items.Add(new ListItem(text, value)); + } protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -139,23 +156,6 @@ protected override void OnPreRender(EventArgs e) base.OnPreRender(e); } - public override void DataBind() - { - if (!string.IsNullOrEmpty(this._initValue)) - { - this.DataBind(this._initValue); - } - else - { - base.DataBind(); - } - } - - public void AddItem(string text, string value) - { - this.Items.Add(new ListItem(text, value)); - } - public void InsertItem(int index, string text, string value) { this.Items.Insert(index, new ListItem(text, value)); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs index 3720bed060f..cc3cca1c93e 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs @@ -18,10 +18,6 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// public class DnnDatePicker : TextBox { - protected virtual string Format => "yyyy-MM-dd"; - - protected virtual string ClientFormat => "YYYY-MM-DD"; - public DateTime? SelectedDate { get @@ -42,6 +38,10 @@ public DateTime? SelectedDate } public DateTime MinDate { get; set; } = new DateTime(1900, 1, 1); + + protected virtual string Format => "yyyy-MM-dd"; + + protected virtual string ClientFormat => "YYYY-MM-DD"; public DateTime MaxDate { get; set; } = DateTime.MaxValue; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs index b2e54557d09..84feff33b24 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs @@ -19,16 +19,6 @@ public class DnnFormComboBoxItem : DnnFormListItemBase // public DropDownList ComboBox { get; set; } public DnnComboBox ComboBox { get; set; } - private void IndexChanged(object sender, EventArgs e) - { - this.UpdateDataSource(this.Value, this.ComboBox.SelectedValue, this.DataField); - } - - protected override void BindList() - { - BindListInternal(this.ComboBox, this.Value, this.ListSource, this.ListTextField, this.ListValueField); - } - // internal static void BindListInternal(DropDownList comboBox, object value, IEnumerable listSource, string textField, string valueField) internal static void BindListInternal(DnnComboBox comboBox, object value, IEnumerable listSource, string textField, string valueField) { @@ -64,6 +54,11 @@ internal static void BindListInternal(DnnComboBox comboBox, object value, IEnume } } + protected override void BindList() + { + BindListInternal(this.ComboBox, this.Value, this.ListSource, this.ListTextField, this.ListValueField); + } + protected override WebControl CreateControlInternal(Control container) { // ComboBox = new DropDownList { ID = ID + "_ComboBox" }; @@ -78,5 +73,10 @@ protected override WebControl CreateControlInternal(Control container) return this.ComboBox; } + + private void IndexChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this.ComboBox.SelectedValue, this.DataField); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs index 06d7a64ec45..f9b507716d4 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs @@ -14,13 +14,6 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// public class DnnFormToggleButtonItem : DnnFormItemBase { - public enum CheckBoxMode - { - TrueFalse = 0, - YN = 1, - YesNo = 2, - } - // private DnnRadButton _checkBox; private CheckBox _checkBox; @@ -28,28 +21,16 @@ public DnnFormToggleButtonItem() { this.Mode = CheckBoxMode.TrueFalse; } + + public enum CheckBoxMode + { + TrueFalse = 0, + YN = 1, + YesNo = 2, + } public CheckBoxMode Mode { get; set; } - private void CheckedChanged(object sender, EventArgs e) - { - string newValue; - switch (this.Mode) - { - case CheckBoxMode.YN: - newValue = this._checkBox.Checked ? "Y" : "N"; - break; - case CheckBoxMode.YesNo: - newValue = this._checkBox.Checked ? "Yes" : "No"; - break; - default: - newValue = this._checkBox.Checked ? "true" : "false"; - break; - } - - this.UpdateDataSource(this.Value, newValue, this.DataField); - } - protected override WebControl CreateControlInternal(Control container) { // _checkBox = new DnnRadButton {ID = ID + "_CheckBox", ButtonType = RadButtonType.ToggleButton, ToggleType = ButtonToggleType.CheckBox, AutoPostBack = false}; @@ -88,5 +69,24 @@ protected override void OnInit(EventArgs e) this.FormMode = DnnFormMode.Short; } + + private void CheckedChanged(object sender, EventArgs e) + { + string newValue; + switch (this.Mode) + { + case CheckBoxMode.YN: + newValue = this._checkBox.Checked ? "Y" : "N"; + break; + case CheckBoxMode.YesNo: + newValue = this._checkBox.Checked ? "Yes" : "No"; + break; + default: + newValue = this._checkBox.Checked ? "true" : "false"; + break; + } + + this.UpdateDataSource(this.Value, newValue, this.DataField); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs index 5959ac7f512..cb15f0e3056 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs @@ -22,6 +22,9 @@ public class DnnModuleComboBox : DnnComboBox { private const string DefaultExtensionImage = "icon_extensions_32px.png"; + private DnnComboBox _moduleCombo; + private string _originalValue; + public event EventHandler ItemChanged; public Func, bool> Filter { get; set; } @@ -63,25 +66,35 @@ public override bool Enabled } } - private Dictionary GetPortalDesktopModules() + public void BindAllPortalDesktopModules() { - IOrderedEnumerable> portalModulesList; - if (this.Filter == null) - { - portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) - .Where((kvp) => kvp.Value.DesktopModule.Category == "Uncategorised" || string.IsNullOrEmpty(kvp.Value.DesktopModule.Category)) - .OrderBy(c => c.Key); - } - else - { - portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) - .Where(this.Filter) - .OrderBy(c => c.Key); - } + this._moduleCombo.SelectedValue = null; + this._moduleCombo.DataSource = this.GetPortalDesktopModules(); + this._moduleCombo.DataBind(); + this.BindPortalDesktopModuleImages(); + } - return portalModulesList.ToDictionary( - portalModule => portalModule.Value.DesktopModuleID, - portalModule => portalModule.Key); + public void BindTabModulesByTabID(int tabID) + { + this._moduleCombo.SelectedValue = null; + this._moduleCombo.DataSource = GetTabModules(tabID); + this._moduleCombo.DataBind(); + this.BindTabModuleImages(tabID); + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this._moduleCombo = new DnnComboBox(); + this._moduleCombo.DataValueField = "key"; + this._moduleCombo.DataTextField = "value"; + this.Controls.Add(this._moduleCombo); + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this._originalValue = this.SelectedValue; } private static Dictionary GetTabModules(int tabID) @@ -107,6 +120,27 @@ private static bool ModuleSuportsSharing(ModuleInfo moduleInfo) return false; } } + + private Dictionary GetPortalDesktopModules() + { + IOrderedEnumerable> portalModulesList; + if (this.Filter == null) + { + portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) + .Where((kvp) => kvp.Value.DesktopModule.Category == "Uncategorised" || string.IsNullOrEmpty(kvp.Value.DesktopModule.Category)) + .OrderBy(c => c.Key); + } + else + { + portalModulesList = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) + .Where(this.Filter) + .OrderBy(c => c.Key); + } + + return portalModulesList.ToDictionary( + portalModule => portalModule.Value.DesktopModuleID, + portalModule => portalModule.Key); + } private void BindPortalDesktopModuleImages() { @@ -144,21 +178,6 @@ private void BindTabModuleImages(int tabID) // item.ImageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; // } } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - this._moduleCombo = new DnnComboBox(); - this._moduleCombo.DataValueField = "key"; - this._moduleCombo.DataTextField = "value"; - this.Controls.Add(this._moduleCombo); - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - this._originalValue = this.SelectedValue; - } protected virtual void OnItemChanged() { @@ -178,29 +197,10 @@ protected override void OnPreRender(EventArgs e) this._moduleCombo.Width = this.Width; base.OnPreRender(e); } - - public void BindAllPortalDesktopModules() - { - this._moduleCombo.SelectedValue = null; - this._moduleCombo.DataSource = this.GetPortalDesktopModules(); - this._moduleCombo.DataBind(); - this.BindPortalDesktopModuleImages(); - } - - public void BindTabModulesByTabID(int tabID) - { - this._moduleCombo.SelectedValue = null; - this._moduleCombo.DataSource = GetTabModules(tabID); - this._moduleCombo.DataBind(); - this.BindTabModuleImages(tabID); - } public void SetModule(string code) { this._moduleCombo.SelectedIndex = this._moduleCombo.FindItemIndexByValue(code); } - - private DnnComboBox _moduleCombo; - private string _originalValue; } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs index da8dc9d254e..85703c9435c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs @@ -21,6 +21,11 @@ namespace DotNetNuke.Web.UI.WebControls.Internal [ToolboxData("<{0}:DnnSkinComboBox runat='server'>")] public class DnnSkinComboBox : DnnComboBox { + public DnnSkinComboBox() + { + this.PortalId = Null.NullInteger; + } + public int PortalId { get; set; } public string RootPath { get; set; } @@ -36,11 +41,6 @@ private PortalInfo Portal get { return this.PortalId == Null.NullInteger ? null : PortalController.Instance.GetPortal(this.PortalId); } } - public DnnSkinComboBox() - { - this.PortalId = Null.NullInteger; - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs index 7416926ed7f..46b0549d2b1 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs @@ -28,6 +28,28 @@ public class DateEditControl : EditControl private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateEditControl)); private DnnDatePicker _dateControl; + public override string ID + { + get + { + return base.ID + "_control"; + } + + set + { + base.ID = value; + } + } + + public override string EditControlClientId + { + get + { + this.EnsureChildControls(); + return this.DateControl.ClientID; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets dateValue returns the Date representation of the Value. @@ -149,28 +171,6 @@ protected override string StringValue } } - public override string ID - { - get - { - return base.ID + "_control"; - } - - set - { - base.ID = value; - } - } - - public override string EditControlClientId - { - get - { - this.EnsureChildControls(); - return this.DateControl.ClientID; - } - } - private DnnDatePicker DateControl { get @@ -183,24 +183,6 @@ private DnnDatePicker DateControl return this._dateControl; } } - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); - this.DateControl.ID = base.ID + "_control"; - - this.Controls.Add(this.DateControl); - } - - protected virtual void LoadDateControls() - { - if (this.DateValue != Null.NullDate) - { - this.DateControl.SelectedDate = this.DateValue.Date; - } - } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -225,6 +207,24 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo this.LoadDateControls(); return dataChanged; } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); + this.DateControl.ID = base.ID + "_control"; + + this.Controls.Add(this.DateControl); + } + + protected virtual void LoadDateControls() + { + if (this.DateValue != Null.NullDate) + { + this.DateControl.SelectedDate = this.DateValue.Date; + } + } /// /// OnDataChanged is called by the PostBack Handler when the Data has changed. diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs index c24ceb01226..a3d7debca7f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs @@ -32,6 +32,19 @@ public class DateTimeEditControl : EditControl private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateTimeEditControl)); private DnnDateTimePicker _dateControl; + public override string ID + { + get + { + return base.ID + "_control"; + } + + set + { + base.ID = value; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets dateValue returns the Date representation of the Value. @@ -153,19 +166,6 @@ protected override string StringValue } } - public override string ID - { - get - { - return base.ID + "_control"; - } - - set - { - base.ID = value; - } - } - private DnnDateTimePicker DateControl { get @@ -178,24 +178,6 @@ private DnnDateTimePicker DateControl return this._dateControl; } } - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); - this.DateControl.ID = base.ID + "_control"; - - this.Controls.Add(this.DateControl); - } - - protected virtual void LoadDateControls() - { - if (this.DateValue != Null.NullDate) - { - this.DateControl.SelectedDate = this.DateValue; - } - } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -225,6 +207,24 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo this.LoadDateControls(); return dataChanged; } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); + this.DateControl.ID = base.ID + "_control"; + + this.Controls.Add(this.DateControl); + } + + protected virtual void LoadDateControls() + { + if (this.DateValue != Null.NullDate) + { + this.DateControl.SelectedDate = this.DateValue; + } + } /// /// OnDataChanged is called by the PostBack Handler when the Data has changed. diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs index f6e2f977b8d..2379701fcd5 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs @@ -83,10 +83,10 @@ protected override void OnInit(EventArgs e) this.Options.Preload = "focus"; this.Options.Plugins.Add("remove_button"); - this.Options.Render = new RenderOption - { - Option = "function(item, escape) {return '
' + item.text + '
';}", - }; + this.Options.Render = new RenderOption + { + Option = "function(item, escape) {return '
' + item.text + '
';}", + }; this.Options.Load = $@"function(query, callback) {{ $.ajax({{ diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListServicesOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListServicesOptions.cs index 6c66639d5f1..24c428d5839 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListServicesOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/ItemListServicesOptions.cs @@ -31,6 +31,9 @@ public class ItemListServicesOptions [DataMember(Name = "getTreeWithNodeMethod")] public string GetTreeWithNodeMethod; + [DataMember(Name = "rootId")] + public string RootId = "Root"; // should not be (-1), as (-1) can be treated as Null.Integer + private Dictionary _parameters; [DataMember(Name = "parameters")] @@ -41,8 +44,5 @@ public Dictionary Parameters return this._parameters ?? (this._parameters = new Dictionary()); } } - - [DataMember(Name = "rootId")] - public string RootId = "Root"; // should not be (-1), as (-1) can be treated as Null.Integer } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs index 7cc6783373f..36cc677edc4 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs @@ -23,6 +23,12 @@ public class Tags : WebControl, IPostBackEventHandler, IPostBackDataHandler private string _Separator = ", "; private string _Tags; + + public event EventHandler TagsUpdated; + + public string AddImageUrl { get; set; } + + public bool AllowTagging { get; set; } private Vocabulary TagVocabulary { @@ -32,10 +38,6 @@ private Vocabulary TagVocabulary return (from v in vocabularyController.GetVocabularies() where v.IsSystem && v.Name == "Tags" select v).SingleOrDefault(); } } - - public string AddImageUrl { get; set; } - - public bool AllowTagging { get; set; } public string CancelImageUrl { get; set; } @@ -94,132 +96,6 @@ public string Separator public bool ShowTags { get; set; } - private string LocalizeString(string key) - { - string LocalResourceFile = Utilities.GetLocalResourceFile(this); - string localizedString = null; - if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(LocalResourceFile)) - { - localizedString = Localization.GetString(key, LocalResourceFile); - } - else - { - localizedString = Null.NullString; - } - - return localizedString; - } - - private void RenderButton(HtmlTextWriter writer, string buttonType, string imageUrl) - { - writer.AddAttribute(HtmlTextWriterAttribute.Title, this.LocalizeString(string.Format("{0}.ToolTip", buttonType))); - writer.AddAttribute(HtmlTextWriterAttribute.Href, this.Page.ClientScript.GetPostBackClientHyperlink(this, buttonType)); - writer.RenderBeginTag(HtmlTextWriterTag.A); - - // Image - if (!string.IsNullOrEmpty(imageUrl)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Src, this.ResolveUrl(imageUrl)); - writer.RenderBeginTag(HtmlTextWriterTag.Img); - writer.RenderEndTag(); - } - - writer.Write(this.LocalizeString(buttonType)); - writer.RenderEndTag(); - } - - private void RenderTerm(HtmlTextWriter writer, Term term, bool renderSeparator) - { - writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format(this.NavigateUrlFormatString, term.Name)); - writer.AddAttribute(HtmlTextWriterAttribute.Title, term.Name); - writer.AddAttribute(HtmlTextWriterAttribute.Rel, "tag"); - writer.RenderBeginTag(HtmlTextWriterTag.A); - writer.Write(term.Name); - writer.RenderEndTag(); - - if (renderSeparator) - { - writer.Write(this.Separator); - } - } - - private void SaveTags() - { - string tags = this._Tags; - - if (!string.IsNullOrEmpty(tags)) - { - foreach (string t in tags.Split(',')) - { - if (!string.IsNullOrEmpty(t)) - { - string tagName = t.Trim(' '); - Term existingTerm = (from term in this.ContentItem.Terms.AsQueryable() where term.Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase) select term).SingleOrDefault(); - - if (existingTerm == null) - { - // Not tagged - TermController termController = new TermController(); - Term term = - (from te in termController.GetTermsByVocabulary(this.TagVocabulary.VocabularyId) where te.Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase) select te). - SingleOrDefault(); - if (term == null) - { - // Add term - term = new Term(this.TagVocabulary.VocabularyId); - term.Name = tagName; - termController.AddTerm(term); - } - - // Add term to content - this.ContentItem.Terms.Add(term); - termController.AddTermToContent(term, this.ContentItem); - } - } - } - } - - this.IsEditMode = false; - - // Raise the Tags Updated Event - this.OnTagsUpdate(EventArgs.Empty); - } - - public event EventHandler TagsUpdated; - - protected void OnTagsUpdate(EventArgs e) - { - if (this.TagsUpdated != null) - { - this.TagsUpdated(this, e); - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.UniqueID)) - { - StringBuilder sb = new StringBuilder(); - - sb.Append(""); - - this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.UniqueID, sb.ToString()); - } - } - public override void RenderControl(HtmlTextWriter writer) { // Render Outer Div @@ -336,6 +212,130 @@ public bool LoadPostData(string postDataKey, NameValueCollection postCollection) return true; } + + protected void OnTagsUpdate(EventArgs e) + { + if (this.TagsUpdated != null) + { + this.TagsUpdated(this, e); + } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.UniqueID)) + { + StringBuilder sb = new StringBuilder(); + + sb.Append(""); + + this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.UniqueID, sb.ToString()); + } + } + + private string LocalizeString(string key) + { + string LocalResourceFile = Utilities.GetLocalResourceFile(this); + string localizedString = null; + if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(LocalResourceFile)) + { + localizedString = Localization.GetString(key, LocalResourceFile); + } + else + { + localizedString = Null.NullString; + } + + return localizedString; + } + + private void RenderButton(HtmlTextWriter writer, string buttonType, string imageUrl) + { + writer.AddAttribute(HtmlTextWriterAttribute.Title, this.LocalizeString(string.Format("{0}.ToolTip", buttonType))); + writer.AddAttribute(HtmlTextWriterAttribute.Href, this.Page.ClientScript.GetPostBackClientHyperlink(this, buttonType)); + writer.RenderBeginTag(HtmlTextWriterTag.A); + + // Image + if (!string.IsNullOrEmpty(imageUrl)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Src, this.ResolveUrl(imageUrl)); + writer.RenderBeginTag(HtmlTextWriterTag.Img); + writer.RenderEndTag(); + } + + writer.Write(this.LocalizeString(buttonType)); + writer.RenderEndTag(); + } + + private void RenderTerm(HtmlTextWriter writer, Term term, bool renderSeparator) + { + writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format(this.NavigateUrlFormatString, term.Name)); + writer.AddAttribute(HtmlTextWriterAttribute.Title, term.Name); + writer.AddAttribute(HtmlTextWriterAttribute.Rel, "tag"); + writer.RenderBeginTag(HtmlTextWriterTag.A); + writer.Write(term.Name); + writer.RenderEndTag(); + + if (renderSeparator) + { + writer.Write(this.Separator); + } + } + + private void SaveTags() + { + string tags = this._Tags; + + if (!string.IsNullOrEmpty(tags)) + { + foreach (string t in tags.Split(',')) + { + if (!string.IsNullOrEmpty(t)) + { + string tagName = t.Trim(' '); + Term existingTerm = (from term in this.ContentItem.Terms.AsQueryable() where term.Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase) select term).SingleOrDefault(); + + if (existingTerm == null) + { + // Not tagged + TermController termController = new TermController(); + Term term = + (from te in termController.GetTermsByVocabulary(this.TagVocabulary.VocabularyId) where te.Name.Equals(tagName, StringComparison.CurrentCultureIgnoreCase) select te). + SingleOrDefault(); + if (term == null) + { + // Add term + term = new Term(this.TagVocabulary.VocabularyId); + term.Name = tagName; + termController.AddTerm(term); + } + + // Add term to content + this.ContentItem.Terms.Add(term); + termController.AddTermToContent(term, this.ContentItem); + } + } + } + } + + this.IsEditMode = false; + + // Raise the Tags Updated Event + this.OnTagsUpdate(EventArgs.Empty); + } public void RaisePostDataChangedEvent() { diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs index 33a39236d27..81d63e8ca20 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs @@ -21,6 +21,62 @@ internal UniformControlCollection(TOwner owner) this._owner = owner; } + /// + /// Gets the number of elements contained in the . + /// + /// + /// The number of elements contained in the . + /// + public int Count + { + get + { + return this._owner.HasControls() ? this._owner.Controls.Count : 0; + } + } + + /// + /// Gets a value indicating whether the is read-only. + /// + /// + /// true if the is read-only; otherwise, false. + /// + public bool IsReadOnly + { + get + { + return false; + } + } + + /// + /// Gets or sets the element at the specified index. + /// + /// + /// The element at the specified index. + /// + /// + /// The zero-based index of the element to get or set. + /// + /// is not a valid index in the . + /// + /// + /// The property is set and the is read-only. + /// + public TChildren this[int index] + { + get + { + return this._owner.Controls[index] as TChildren; + } + + set + { + this.RemoveAt(index); + this.AddAt(index, value); + } + } + public void AddAt(int index, TChildren childControl) { this._owner.Controls.AddAt(index, childControl); @@ -75,48 +131,6 @@ public void RemoveAt(int index) this._owner.Controls.RemoveAt(index); } - /// - /// Gets or sets the element at the specified index. - /// - /// - /// The element at the specified index. - /// - /// - /// The zero-based index of the element to get or set. - /// - /// is not a valid index in the . - /// - /// - /// The property is set and the is read-only. - /// - public TChildren this[int index] - { - get - { - return this._owner.Controls[index] as TChildren; - } - - set - { - this.RemoveAt(index); - this.AddAt(index, value); - } - } - - /// - /// Gets the number of elements contained in the . - /// - /// - /// The number of elements contained in the . - /// - public int Count - { - get - { - return this._owner.HasControls() ? this._owner.Controls.Count : 0; - } - } - /// /// Removes the first occurrence of a specific object from the . /// @@ -135,20 +149,6 @@ public bool Remove(TChildren item) return true; } - /// - /// Gets a value indicating whether the is read-only. - /// - /// - /// true if the is read-only; otherwise, false. - /// - public bool IsReadOnly - { - get - { - return false; - } - } - /// /// Returns an enumerator that iterates through the collection. /// @@ -237,6 +237,11 @@ public bool Contains(TChildren item) return this._owner.Controls.Contains(item); } + IEnumerator IEnumerable.GetEnumerator() + { + return this.EnumerableGetEnumerator(); + } + /// /// Returns an enumerator that iterates through a collection. /// @@ -248,10 +253,5 @@ private IEnumerator EnumerableGetEnumerator() { return this._owner.Controls.GetEnumerator(); } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.EnumerableGetEnumerator(); - } } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs b/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs index 810c64c5990..a5c51dacd25 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs @@ -22,6 +22,14 @@ public ValidationResult(IEnumerable errors) Requires.NotNull("errors", errors); this._Errors = errors; } + + public static ValidationResult Successful + { + get + { + return new ValidationResult(); + } + } public IEnumerable Errors { @@ -38,14 +46,6 @@ public bool IsValid return this._Errors.Count() == 0; } } - - public static ValidationResult Successful - { - get - { - return new ValidationResult(); - } - } public ValidationResult CombineWith(ValidationResult other) { diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs index d75524a223b..b13c073fdc3 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs @@ -39,14 +39,53 @@ namespace DotNetNuke.UI.ControlPanel public partial class AddModule : UserControlBase, IDnnRibbonBarTool { - private readonly INavigationManager _navigationManager; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AddModule)); + private readonly INavigationManager _navigationManager; private bool _enabled = true; public AddModule() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public override bool Visible + { + get + { + return base.Visible && TabPermissionController.CanAddContentToPage(); + } + + set + { + base.Visible = value; + } + } + + public bool Enabled + { + get + { + return this._enabled && this.CanAddModuleToPage(); + } + + set + { + this._enabled = value; + } + } + + public string ToolName + { + get + { + return "QuickAddModule"; + } + + set + { + throw new NotSupportedException("Set ToolName not supported"); + } + } /// /// Gets return the for the selected portal (from the Site list), unless @@ -171,22 +210,6 @@ protected override void OnLoad(EventArgs e) } } - private void CmdConfirmAddModuleClick(object sender, EventArgs e) - { - this.CmdAddModuleClick(sender, e); - } - - private void SiteList_SelectedIndexChanged(object sender, EventArgs e) - { - this.LoadModuleList(); - this.LoadPageList(); - } - - private void CategoryListSelectedIndexChanged(object sender, EventArgs e) - { - this.LoadModuleList(); - } - protected void CmdAddModuleClick(object sender, EventArgs e) { if (TabPermissionController.CanAddContentToPage() && this.CanAddModuleToPage()) @@ -302,44 +325,21 @@ protected void CmdAddModuleClick(object sender, EventArgs e) this.Response.Redirect(this.Request.RawUrl, true); } } - - public override bool Visible + + private void CmdConfirmAddModuleClick(object sender, EventArgs e) { - get - { - return base.Visible && TabPermissionController.CanAddContentToPage(); - } - - set - { - base.Visible = value; - } + this.CmdAddModuleClick(sender, e); } - public bool Enabled + private void SiteList_SelectedIndexChanged(object sender, EventArgs e) { - get - { - return this._enabled && this.CanAddModuleToPage(); - } - - set - { - this._enabled = value; - } + this.LoadModuleList(); + this.LoadPageList(); } - public string ToolName + private void CategoryListSelectedIndexChanged(object sender, EventArgs e) { - get - { - return "QuickAddModule"; - } - - set - { - throw new NotSupportedException("Set ToolName not supported"); - } + this.LoadModuleList(); } /// Gets the currently-selected module. @@ -396,6 +396,30 @@ protected DesktopModuleInfo SelectedModule return null; } } + + private string LocalResourceFile + { + get + { + return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); + } + } + + public bool CanAddModuleToPage() + { + if (HttpContext.Current == null) + { + return false; + } + + // If we are not in an edit page + return string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"]) && string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"]); + } + + protected string GetString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } private static ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess) { @@ -418,6 +442,82 @@ private static ModulePermissionInfo AddModulePermission(ModuleInfo objModule, Pe return objModulePermission; } + private static void SetCloneModuleContext(bool cloneModuleContext) + { + Thread.SetData( + Thread.GetNamedDataSlot("CloneModuleContext"), + cloneModuleContext ? bool.TrueString : bool.FalseString); + } + + private static void DoAddNewModule(string title, int desktopModuleId, string paneName, int position, int permissionType, string align) + { + try + { + DesktopModuleInfo desktopModule; + if (!DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId).TryGetValue(desktopModuleId, out desktopModule)) + { + throw new ArgumentException("desktopModuleId"); + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + foreach (ModuleDefinitionInfo objModuleDefinition in + ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values) + { + var objModule = new ModuleInfo(); + objModule.Initialize(PortalSettings.Current.ActiveTab.PortalID); + + objModule.PortalID = PortalSettings.Current.ActiveTab.PortalID; + objModule.TabID = PortalSettings.Current.ActiveTab.TabID; + objModule.ModuleOrder = position; + objModule.ModuleTitle = string.IsNullOrEmpty(title) ? objModuleDefinition.FriendlyName : title; + objModule.PaneName = paneName; + objModule.ModuleDefID = objModuleDefinition.ModuleDefID; + if (objModuleDefinition.DefaultCacheTime > 0) + { + objModule.CacheTime = objModuleDefinition.DefaultCacheTime; + if (PortalSettings.Current.DefaultModuleId > Null.NullInteger && PortalSettings.Current.DefaultTabId > Null.NullInteger) + { + ModuleInfo defaultModule = ModuleController.Instance.GetModule(PortalSettings.Current.DefaultModuleId, PortalSettings.Current.DefaultTabId, true); + if (defaultModule != null) + { + objModule.CacheTime = defaultModule.CacheTime; + } + } + } + + ModuleController.Instance.InitialModulePermission(objModule, objModule.TabID, permissionType); + + if (PortalSettings.Current.ContentLocalizationEnabled) + { + Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId); + + // check whether original tab is exists, if true then set culture code to default language, + // otherwise set culture code to current. + if (TabController.Instance.GetTabByCulture(objModule.TabID, PortalSettings.Current.PortalId, defaultLocale) != null) + { + objModule.CultureCode = defaultLocale.Code; + } + else + { + objModule.CultureCode = PortalSettings.Current.CultureCode; + } + } + else + { + objModule.CultureCode = Null.NullString; + } + + objModule.AllTabs = false; + objModule.Alignment = align; + + ModuleController.Instance.AddModule(objModule); + } + } + private void DoAddExistingModule(int moduleId, int tabId, string paneName, int position, string align, bool cloneModule) { ModuleInfo moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); @@ -539,101 +639,6 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p } } - private static void SetCloneModuleContext(bool cloneModuleContext) - { - Thread.SetData( - Thread.GetNamedDataSlot("CloneModuleContext"), - cloneModuleContext ? bool.TrueString : bool.FalseString); - } - - private static void DoAddNewModule(string title, int desktopModuleId, string paneName, int position, int permissionType, string align) - { - try - { - DesktopModuleInfo desktopModule; - if (!DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId).TryGetValue(desktopModuleId, out desktopModule)) - { - throw new ArgumentException("desktopModuleId"); - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - - foreach (ModuleDefinitionInfo objModuleDefinition in - ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values) - { - var objModule = new ModuleInfo(); - objModule.Initialize(PortalSettings.Current.ActiveTab.PortalID); - - objModule.PortalID = PortalSettings.Current.ActiveTab.PortalID; - objModule.TabID = PortalSettings.Current.ActiveTab.TabID; - objModule.ModuleOrder = position; - objModule.ModuleTitle = string.IsNullOrEmpty(title) ? objModuleDefinition.FriendlyName : title; - objModule.PaneName = paneName; - objModule.ModuleDefID = objModuleDefinition.ModuleDefID; - if (objModuleDefinition.DefaultCacheTime > 0) - { - objModule.CacheTime = objModuleDefinition.DefaultCacheTime; - if (PortalSettings.Current.DefaultModuleId > Null.NullInteger && PortalSettings.Current.DefaultTabId > Null.NullInteger) - { - ModuleInfo defaultModule = ModuleController.Instance.GetModule(PortalSettings.Current.DefaultModuleId, PortalSettings.Current.DefaultTabId, true); - if (defaultModule != null) - { - objModule.CacheTime = defaultModule.CacheTime; - } - } - } - - ModuleController.Instance.InitialModulePermission(objModule, objModule.TabID, permissionType); - - if (PortalSettings.Current.ContentLocalizationEnabled) - { - Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId); - - // check whether original tab is exists, if true then set culture code to default language, - // otherwise set culture code to current. - if (TabController.Instance.GetTabByCulture(objModule.TabID, PortalSettings.Current.PortalId, defaultLocale) != null) - { - objModule.CultureCode = defaultLocale.Code; - } - else - { - objModule.CultureCode = PortalSettings.Current.CultureCode; - } - } - else - { - objModule.CultureCode = Null.NullString; - } - - objModule.AllTabs = false; - objModule.Alignment = align; - - ModuleController.Instance.AddModule(objModule); - } - } - - private IEnumerable GetCurrentPortalsGroup() - { - var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); - - var result = (from @group in groups - select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); - - // Are we in a group of one? - if (result == null || result.Length == 0) - { - result = new[] { PortalController.Instance.GetPortal(PortalSettings.Current.PortalId) }; - } - - return result; - } - private static bool GetIsPortable(string moduleID, string tabID) { bool isPortable = false; @@ -659,9 +664,23 @@ private static bool GetIsPortable(string moduleID, string tabID) return isPortable; } - protected string GetString(string key) + private IEnumerable GetCurrentPortalsGroup() { - return Localization.GetString(key, this.LocalResourceFile); + var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); + + var result = (from @group in groups + select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); + + // Are we in a group of one? + if (result == null || result.Length == 0) + { + result = new[] { PortalController.Instance.GetPortal(PortalSettings.Current.PortalId) }; + } + + return result; } private void LoadAllLists() @@ -876,14 +895,6 @@ private void LoadVisibilityList() } } - private string LocalResourceFile - { - get - { - return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); - } - } - private void SetCopyModuleMessage(bool isPortable) { if (isPortable) @@ -897,16 +908,5 @@ private void SetCopyModuleMessage(bool isPortable) this.chkCopyModule.ToolTip = Localization.GetString("CopyModuleWOcontent.ToolTip", this.LocalResourceFile); } } - - public bool CanAddModuleToPage() - { - if (HttpContext.Current == null) - { - return false; - } - - // If we are not in an edit page - return string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"]) && string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"]); - } } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs index 2de4fa8ed60..86d913c6d7b 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs @@ -27,11 +27,52 @@ public partial class AddPage : UserControl, IDnnRibbonBarTool { private readonly INavigationManager _navigationManager; + private TabInfo _newTabObject; + public AddPage() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + public override bool Visible + { + get + { + return base.Visible && TabPermissionController.CanAddPage(); + } + + set + { + base.Visible = value; + } + } + + public string ToolName + { + get + { + return "QuickAddPage"; + } + + set + { + throw new NotSupportedException("Set ToolName not supported"); + } + } + + protected TabInfo NewTabObject + { + get + { + if (this._newTabObject == null) + { + this._newTabObject = RibbonBarManager.InitTabInfoObject(PortalSettings.ActiveTab); + } + + return this._newTabObject; + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -110,45 +151,12 @@ protected void CmdAddPageClick(object sender, EventArgs e) Web.UI.Utilities.RegisterAlertOnPageLoad(this, new MessageWindowParameters(errMsg) { Title = this.GetString("Err.Title") }); } } - - public override bool Visible - { - get - { - return base.Visible && TabPermissionController.CanAddPage(); - } - - set - { - base.Visible = value; - } - } - - public string ToolName - { - get - { - return "QuickAddPage"; - } - - set - { - throw new NotSupportedException("Set ToolName not supported"); - } - } - - private TabInfo _newTabObject; - protected TabInfo NewTabObject + private static PortalSettings PortalSettings { get { - if (this._newTabObject == null) - { - this._newTabObject = RibbonBarManager.InitTabInfoObject(PortalSettings.ActiveTab); - } - - return this._newTabObject; + return PortalSettings.Current; } } @@ -160,14 +168,6 @@ private string LocalResourceFile } } - private static PortalSettings PortalSettings - { - get - { - return PortalSettings.Current; - } - } - private void LoadAllLists() { this.LoadLocationList(); diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs index c9b9cb1a8c3..53983b3dcc1 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs @@ -44,12 +44,9 @@ namespace DotNetNuke.UI.ControlPanels public partial class ControlBar : ControlPanelBase { - private readonly INavigationManager _navigationManager; + protected DnnFileUpload FileUploader; - public ControlBar() - { - this._navigationManager = Globals.DependencyProvider.GetRequiredService(); - } + private readonly INavigationManager _navigationManager; private readonly IList _adminCommonTabs = new List { @@ -71,8 +68,29 @@ public ControlBar() "Knowledge Base", "Software and Documentation", }; + + private List _adminBookmarkItems; + + public ControlBar() + { + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } - protected DnnFileUpload FileUploader; + private List _hostBookmarkItems; + + private List _adminTabs; + private List _adminBaseTabs; + private List _adminAdvancedTabs; + + public override bool IsDockable { get; set; } + + public override bool IncludeInControlHierarchy + { + get + { + return base.IncludeInControlHierarchy && (this.IsPageAdmin() || this.IsModuleAdmin()); + } + } protected string CurrentUICulture { get; set; } @@ -101,16 +119,48 @@ protected string BookmarkedModuleKeys return bookmarkModules.ToString(); } } + + protected List AdminBookmarkItems + { + get + { + if (this._adminBookmarkItems == null) + { + var bookmarkItems = Personalization.GetProfile("ControlBar", "admin" + this.PortalSettings.PortalId); - public override bool IsDockable { get; set; } + this._adminBookmarkItems = bookmarkItems != null + ? bookmarkItems.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() + : new List(); + } - public override bool IncludeInControlHierarchy + return this._adminBookmarkItems; + } + } + + protected List HostBookmarkItems { get { - return base.IncludeInControlHierarchy && (this.IsPageAdmin() || this.IsModuleAdmin()); + if (this._hostBookmarkItems == null) + { + var bookmarkItems = Personalization.GetProfile("ControlBar", "host" + this.PortalSettings.PortalId); + + this._hostBookmarkItems = bookmarkItems != null + ? bookmarkItems.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() + : new List(); + } + + return this._hostBookmarkItems; } - } + } + + private new string LocalResourceFile + { + get + { + return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType?.Name); + } + } protected override void OnInit(EventArgs e) { @@ -197,29 +247,6 @@ protected string GetUpgradeIndicator() return string.Empty; } - private void LoadCustomMenuItems() - { - foreach (var menuItem in ControlBarController.Instance.GetCustomMenuItems()) - { - var liElement = new HtmlGenericControl("li"); - liElement.Attributes.Add("id", menuItem.ID + "_tab"); - - var control = this.Page.LoadControl(menuItem.Source); - control.ID = menuItem.ID; - - liElement.Controls.Add(control); - - this.CustomMenuItems.Controls.Add(liElement); - } - } - - private string GetUpgradeIndicatorButton(UpgradeIndicatorViewModel upgradeIndicator) - { - return string.Format( - "\"{4}\"", - upgradeIndicator.ID, upgradeIndicator.WebAction, upgradeIndicator.CssClass, this.ResolveClientUrl(upgradeIndicator.ImageUrl), upgradeIndicator.AltText, upgradeIndicator.ToolTip); - } - protected string PreviewPopup() { var previewUrl = string.Format( @@ -280,6 +307,29 @@ protected IEnumerable LoadPaneList() return resultPanes; } + + private void LoadCustomMenuItems() + { + foreach (var menuItem in ControlBarController.Instance.GetCustomMenuItems()) + { + var liElement = new HtmlGenericControl("li"); + liElement.Attributes.Add("id", menuItem.ID + "_tab"); + + var control = this.Page.LoadControl(menuItem.Source); + control.ID = menuItem.ID; + + liElement.Controls.Add(control); + + this.CustomMenuItems.Controls.Add(liElement); + } + } + + private string GetUpgradeIndicatorButton(UpgradeIndicatorViewModel upgradeIndicator) + { + return string.Format( + "\"{4}\"", + upgradeIndicator.ID, upgradeIndicator.WebAction, upgradeIndicator.CssClass, this.ResolveClientUrl(upgradeIndicator.ImageUrl), upgradeIndicator.AltText, upgradeIndicator.ToolTip); + } protected string GetString(string key) { @@ -728,29 +778,29 @@ protected IEnumerable LoadLanguagesList() } protected bool ShowSwitchLanguagesPanel() - { - if (this.PortalSettings.AllowUserUICulture && this.PortalSettings.ContentLocalizationEnabled) - { - if (this.CurrentUICulture == null) - { - object oCulture = Personalization.GetProfile("Usability", "UICulture"); - - if (oCulture != null) - { - this.CurrentUICulture = oCulture.ToString(); - } - else - { - var l = new Localization(); - this.CurrentUICulture = l.CurrentUICulture; - } - } - - IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, this.CurrentUICulture, string.Empty, false); - return cultureListItems.Count() > 1; - } - - return false; + { + if (this.PortalSettings.AllowUserUICulture && this.PortalSettings.ContentLocalizationEnabled) + { + if (this.CurrentUICulture == null) + { + object oCulture = Personalization.GetProfile("Usability", "UICulture"); + + if (oCulture != null) + { + this.CurrentUICulture = oCulture.ToString(); + } + else + { + var l = new Localization(); + this.CurrentUICulture = l.CurrentUICulture; + } + } + + IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, this.CurrentUICulture, string.Empty, false); + return cultureListItems.Count() > 1; + } + + return false; } protected string CheckedWhenInLayoutMode() @@ -806,13 +856,24 @@ protected bool IsLanguageModuleInstalled() { return DesktopModuleController.GetDesktopModuleByFriendlyName("Languages") != null; } - - private new string LocalResourceFile + + private static IEnumerable GetCurrentPortalsGroup() { - get + var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); + + var result = (from @group in groups + select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); + + // Are we in a group of one? + if (result == null || result.Length == 0) { - return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType?.Name); + result = new[] { PortalController.Instance.GetPortal(PortalSettings.Current.PortalId) }; } + + return result; } private void LoadCategoryList() @@ -858,25 +919,6 @@ private void LoadVisibilityList() this.VisibilityLst.DataBind(); } - private static IEnumerable GetCurrentPortalsGroup() - { - var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); - - var result = (from @group in groups - select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); - - // Are we in a group of one? - if (result == null || result.Length == 0) - { - result = new[] { PortalController.Instance.GetPortal(PortalSettings.Current.PortalId) }; - } - - return result; - } - private void AutoSetUserMode() { int tabId = this.PortalSettings.ActiveTab.TabID; @@ -966,48 +1008,6 @@ private void BindLanguagesList() } } } - - private List _adminBookmarkItems; - - protected List AdminBookmarkItems - { - get - { - if (this._adminBookmarkItems == null) - { - var bookmarkItems = Personalization.GetProfile("ControlBar", "admin" + this.PortalSettings.PortalId); - - this._adminBookmarkItems = bookmarkItems != null - ? bookmarkItems.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() - : new List(); - } - - return this._adminBookmarkItems; - } - } - - private List _hostBookmarkItems; - - protected List HostBookmarkItems - { - get - { - if (this._hostBookmarkItems == null) - { - var bookmarkItems = Personalization.GetProfile("ControlBar", "host" + this.PortalSettings.PortalId); - - this._hostBookmarkItems = bookmarkItems != null - ? bookmarkItems.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() - : new List(); - } - - return this._hostBookmarkItems; - } - } - - private List _adminTabs; - private List _adminBaseTabs; - private List _adminAdvancedTabs; private List _hostTabs; private List _hostBaseTabs; private List _hostAdvancedTabs; @@ -1064,6 +1064,23 @@ protected List HostAdvancedTabs } } + protected bool IsBeaconEnabled + { + get + { + var user = UserController.Instance.GetCurrentUserInfo(); + return BeaconService.Instance.IsBeaconEnabledForControlBar(user); + } + } + + protected string GetBeaconUrl() + { + var beaconService = BeaconService.Instance; + var user = UserController.Instance.GetCurrentUserInfo(); + var path = this.PortalSettings.ActiveTab.TabPath; + return beaconService.GetBeaconUrl(user, path); + } + private void GetHostTabs() { var hostTab = TabController.GetTabByTabPath(Null.NullInteger, "//Host", string.Empty); @@ -1126,22 +1143,5 @@ private bool IsCommonTab(TabInfo tab, bool isHost = false) return isHost ? this._hostCommonTabs.Contains(tab.TabName) : this._adminCommonTabs.Contains(tab.TabName); } - - protected string GetBeaconUrl() - { - var beaconService = BeaconService.Instance; - var user = UserController.Instance.GetCurrentUserInfo(); - var path = this.PortalSettings.ActiveTab.TabPath; - return beaconService.GetBeaconUrl(user, path); - } - - protected bool IsBeaconEnabled - { - get - { - var user = UserController.Instance.GetCurrentUserInfo(); - return BeaconService.Instance.IsBeaconEnabledForControlBar(user); - } - } } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs index 1e759406b5e..3e40b27b082 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs @@ -39,6 +39,45 @@ public override bool IncludeInControlHierarchy return base.IncludeInControlHierarchy && (this.IsPageAdmin() || this.IsModuleAdmin()); } } + + protected string GetButtonConfirmMessage(string toolName) + { + if (toolName == "DeletePage") + { + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.DeletePage.Confirm", this.LocalResourceFile)); + } + + if (toolName == "CopyPermissionsToChildren") + { + if (PortalSecurity.IsInRole("Administrators")) + { + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyPermissionsToChildren.Confirm", this.LocalResourceFile)); + } + + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyPermissionsToChildrenPageEditor.Confirm", this.LocalResourceFile)); + } + + if (toolName == "CopyDesignToChildren") + { + if (PortalSecurity.IsInRole("Administrators")) + { + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyDesignToChildren.Confirm", this.LocalResourceFile)); + } + + return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyDesignToChildrenPageEditor.Confirm", this.LocalResourceFile)); + } + + return string.Empty; + } + + protected void DetermineNodesToInclude(object sender, EventArgs e) + { + var skinObject = (Web.DDRMenu.SkinObject)sender; + string admin = this.StripLocalizationPrefix(Localization.GetString("//Admin.String", Localization.GlobalResourceFile)).Trim(); + string host = this.StripLocalizationPrefix(Localization.GetString("//Host.String", Localization.GlobalResourceFile)).Trim(); + + skinObject.IncludeNodes = admin + ", " + host; + } private void Localize() { @@ -98,57 +137,6 @@ private void SetLanguage(bool update) DotNetNuke.Services.Personalization.Personalization.SetProfile("Usability", "UICulture", this.ddlUICulture.SelectedValue); } } - - protected string GetButtonConfirmMessage(string toolName) - { - if (toolName == "DeletePage") - { - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.DeletePage.Confirm", this.LocalResourceFile)); - } - - if (toolName == "CopyPermissionsToChildren") - { - if (PortalSecurity.IsInRole("Administrators")) - { - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyPermissionsToChildren.Confirm", this.LocalResourceFile)); - } - - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyPermissionsToChildrenPageEditor.Confirm", this.LocalResourceFile)); - } - - if (toolName == "CopyDesignToChildren") - { - if (PortalSecurity.IsInRole("Administrators")) - { - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyDesignToChildren.Confirm", this.LocalResourceFile)); - } - - return ClientAPI.GetSafeJSString(Localization.GetString("Tool.CopyDesignToChildrenPageEditor.Confirm", this.LocalResourceFile)); - } - - return string.Empty; - } - - protected void DetermineNodesToInclude(object sender, EventArgs e) - { - var skinObject = (Web.DDRMenu.SkinObject)sender; - string admin = this.StripLocalizationPrefix(Localization.GetString("//Admin.String", Localization.GlobalResourceFile)).Trim(); - string host = this.StripLocalizationPrefix(Localization.GetString("//Host.String", Localization.GlobalResourceFile)).Trim(); - - skinObject.IncludeNodes = admin + ", " + host; - } - - private string StripLocalizationPrefix(string s) - { - const string prefix = "[L]"; - - if (s.StartsWith(prefix)) - { - return s.Substring(prefix.Length); - } - - return s; - } protected override void OnInit(EventArgs e) { @@ -309,27 +297,28 @@ protected override void OnLoad(EventArgs e) } } - protected void ddlMode_SelectedIndexChanged(object sender, EventArgs e) + private string StripLocalizationPrefix(string s) { - if (this.Page.IsCallback) + const string prefix = "[L]"; + + if (s.StartsWith(prefix)) { - return; + return s.Substring(prefix.Length); } - - this.SetMode(true); - this.Response.Redirect(this.Request.RawUrl, true); - } - private void ddlUICulture_SelectedIndexChanged(object sender, EventArgs e) + return s; + } + + protected void ddlMode_SelectedIndexChanged(object sender, EventArgs e) { if (this.Page.IsCallback) { return; } - this.SetLanguage(true); + this.SetMode(true); this.Response.Redirect(this.Request.RawUrl, true); - } + } protected string PreviewPopup() { @@ -348,5 +337,16 @@ protected string PreviewPopup() return string.Format("location.href = \"{0}\"", previewUrl); } } + + private void ddlUICulture_SelectedIndexChanged(object sender, EventArgs e) + { + if (this.Page.IsCallback) + { + return; + } + + this.SetLanguage(true); + this.Response.Redirect(this.Request.RawUrl, true); + } } } diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs index 567d29f6bd3..e25d0474f03 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs @@ -18,6 +18,37 @@ namespace DotNetNuke.UI.ControlPanel public partial class SwitchSite : UserControl, IDnnRibbonBarTool { + public override bool Visible + { + get + { + if (PortalSettings.Current.UserId == Null.NullInteger) + { + return false; + } + + return PortalSettings.Current.UserInfo.IsSuperUser && base.Visible; + } + + set + { + base.Visible = value; + } + } + + public string ToolName + { + get + { + return "QuickSwitchSite"; + } + + set + { + throw new NotSupportedException("Set ToolName not supported"); + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -53,8 +84,8 @@ protected void CmdSwitchClick(object sender, EventArgs e) } } catch (ThreadAbortException) - { - // Do nothing we are not logging ThreadAbortxceptions caused by redirects + { + // Do nothing we are not logging ThreadAbortxceptions caused by redirects } catch (Exception ex) { @@ -62,37 +93,6 @@ protected void CmdSwitchClick(object sender, EventArgs e) } } - public override bool Visible - { - get - { - if (PortalSettings.Current.UserId == Null.NullInteger) - { - return false; - } - - return PortalSettings.Current.UserInfo.IsSuperUser && base.Visible; - } - - set - { - base.Visible = value; - } - } - - public string ToolName - { - get - { - return "QuickSwitchSite"; - } - - set - { - throw new NotSupportedException("Set ToolName not supported"); - } - } - private void LoadPortalsList() { var portals = PortalController.Instance.GetPortals(); diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs index b7ebbc2b7c6..567e46e6c0e 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs @@ -27,11 +27,61 @@ public partial class UpdatePage : UserControl, IDnnRibbonBarTool { private readonly INavigationManager _navigationManager; + private TabInfo _currentTab; + public UpdatePage() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + public override bool Visible + { + get + { + return base.Visible && TabPermissionController.CanManagePage(); + } + + set + { + base.Visible = value; + } + } + + public string ToolName + { + get + { + return "QuickUpdatePage"; + } + + set + { + throw new NotSupportedException("Set ToolName not supported"); + } + } + + private static PortalSettings PortalSettings + { + get + { + return PortalSettings.Current; + } + } + + private TabInfo CurrentTab + { + get + { + // Weird - but the activetab has different skin src value than getting from the db + if (this._currentTab == null) + { + this._currentTab = TabController.Instance.GetTab(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID, false); + } + + return this._currentTab; + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -119,48 +169,6 @@ protected void CmdUpdateClick(object sender, EventArgs e) } } } - - public override bool Visible - { - get - { - return base.Visible && TabPermissionController.CanManagePage(); - } - - set - { - base.Visible = value; - } - } - - public string ToolName - { - get - { - return "QuickUpdatePage"; - } - - set - { - throw new NotSupportedException("Set ToolName not supported"); - } - } - - private TabInfo _currentTab; - - private TabInfo CurrentTab - { - get - { - // Weird - but the activetab has different skin src value than getting from the db - if (this._currentTab == null) - { - this._currentTab = TabController.Instance.GetTab(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID, false); - } - - return this._currentTab; - } - } private string LocalResourceFile { @@ -170,11 +178,21 @@ private string LocalResourceFile } } - private static PortalSettings PortalSettings + private static string FormatSkinName(string strSkinFolder, string strSkinFile) { - get + if (strSkinFolder.ToLowerInvariant() == "_default") { - return PortalSettings.Current; + return strSkinFile; + } + + switch (strSkinFile.ToLowerInvariant()) + { + case "skin": + case "container": + case "default": + return strSkinFolder; + default: + return strSkinFolder + " - " + strSkinFile; } } @@ -288,24 +306,6 @@ private RadComboBoxItem GetSeparatorItem() return new RadComboBoxItem(this.GetString("SkinLstSeparator"), string.Empty) { CssClass = "SkinLstSeparator", Enabled = false }; } - private static string FormatSkinName(string strSkinFolder, string strSkinFile) - { - if (strSkinFolder.ToLowerInvariant() == "_default") - { - return strSkinFile; - } - - switch (strSkinFile.ToLowerInvariant()) - { - case "skin": - case "container": - case "default": - return strSkinFolder; - default: - return strSkinFolder + " - " + strSkinFile; - } - } - private void LoadLocationList() { this.LocationLst.ClearSelection(); diff --git a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs index 7911fb57556..8f4f0a38340 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs @@ -43,14 +43,14 @@ public partial class WebUpload : PortalModuleBase private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(WebUpload)); private readonly INavigationManager _navigationManager; + private string _DestinationFolder; + private UploadType _FileType; + private string _FileTypeName; + public WebUpload() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - - private string _DestinationFolder; - private UploadType _FileType; - private string _FileTypeName; private string _RootFolder; private string _UploadRoles; @@ -157,6 +157,34 @@ public string UploadRoles } } + /// ----------------------------------------------------------------------------- + /// + /// This routine determines the Return Url. + /// + /// + /// + /// + /// ----------------------------------------------------------------------------- + public string ReturnURL() + { + int TabID = this.PortalSettings.HomeTabId; + + if (this.Request.Params["rtab"] != null) + { + TabID = int.Parse(this.Request.Params["rtab"]); + } + + return this._navigationManager.NavigateURL(TabID); + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + // Customise the Control Title + this.ModuleConfiguration.ModuleTitle = Localization.GetString("UploadType" + this.FileType, this.LocalResourceFile); + } + /// ----------------------------------------------------------------------------- /// /// This routine checks the Access Security. @@ -199,34 +227,6 @@ private void LoadFolders() } } } - - /// ----------------------------------------------------------------------------- - /// - /// This routine determines the Return Url. - /// - /// - /// - /// - /// ----------------------------------------------------------------------------- - public string ReturnURL() - { - int TabID = this.PortalSettings.HomeTabId; - - if (this.Request.Params["rtab"] != null) - { - TabID = int.Parse(this.Request.Params["rtab"]); - } - - return this._navigationManager.NavigateURL(TabID); - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - // Customise the Control Title - this.ModuleConfiguration.ModuleTitle = Localization.GetString("UploadType" + this.FileType, this.LocalResourceFile); - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs index faa7b9451f1..dca96466c54 100644 --- a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs +++ b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs @@ -64,13 +64,13 @@ public static AnalyticsEngineConfiguration GetConfig() foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsEngineConfig/Engines/AnalyticsEngine")) { - var analyticsEngine = new AnalyticsEngine - { - EngineType = nav.SelectSingleNode("EngineType").Value, - ElementId = nav.SelectSingleNode("ElementId").Value, - InjectTop = Convert.ToBoolean(nav.SelectSingleNode("InjectTop").Value), - ScriptTemplate = nav.SelectSingleNode("ScriptTemplate").Value, - }; + var analyticsEngine = new AnalyticsEngine + { + EngineType = nav.SelectSingleNode("EngineType").Value, + ElementId = nav.SelectSingleNode("ElementId").Value, + InjectTop = Convert.ToBoolean(nav.SelectSingleNode("InjectTop").Value), + ScriptTemplate = nav.SelectSingleNode("ScriptTemplate").Value, + }; config.AnalyticsEngines.Add(analyticsEngine); } diff --git a/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs b/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs index f5a961cbf31..c73dc96310c 100644 --- a/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs @@ -15,15 +15,15 @@ protected HttpOutputFilter(Stream baseStream) this._sink = baseStream; } - protected Stream BaseStream + public override bool CanRead { get { - return this._sink; + return false; } } - public override bool CanRead + public override bool CanSeek { get { @@ -31,11 +31,11 @@ public override bool CanRead } } - public override bool CanSeek + protected Stream BaseStream { get { - return false; + return this._sink; } } diff --git a/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs b/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs index 50085ebbc9d..e9eadf74035 100644 --- a/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs +++ b/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs @@ -15,35 +15,22 @@ namespace DotNetNuke.HttpModules.DependencyInjection { public class ServiceRequestScopeModule : IHttpModule { + private static IServiceProvider _serviceProvider; + public static void InitModule() { DynamicModuleUtility.RegisterModule(typeof(ServiceRequestScopeModule)); } - private static IServiceProvider _serviceProvider; - - public void Init(HttpApplication context) - { - context.BeginRequest += this.Context_BeginRequest; - context.EndRequest += this.Context_EndRequest; - } - public static void SetServiceProvider(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } - private void Context_BeginRequest(object sender, EventArgs e) - { - var context = ((HttpApplication)sender).Context; - context.SetScope(_serviceProvider.CreateScope()); - } - - private void Context_EndRequest(object sender, EventArgs e) + public void Init(HttpApplication context) { - var context = ((HttpApplication)sender).Context; - context.GetScope()?.Dispose(); - context.ClearScope(); + context.BeginRequest += this.Context_BeginRequest; + context.EndRequest += this.Context_EndRequest; } /// @@ -66,5 +53,18 @@ protected virtual void Dispose(bool disposing) { // left empty by design } + + private void Context_BeginRequest(object sender, EventArgs e) + { + var context = ((HttpApplication)sender).Context; + context.SetScope(_serviceProvider.CreateScope()); + } + + private void Context_EndRequest(object sender, EventArgs e) + { + var context = ((HttpApplication)sender).Context; + context.GetScope()?.Dispose(); + context.ClearScope(); + } } } diff --git a/DNN Platform/HttpModules/Membership/MembershipModule.cs b/DNN Platform/HttpModules/Membership/MembershipModule.cs index 659902d75e5..f3135359d83 100644 --- a/DNN Platform/HttpModules/Membership/MembershipModule.cs +++ b/DNN Platform/HttpModules/Membership/MembershipModule.cs @@ -67,53 +67,6 @@ private static string CurrentCulture } } - /// - /// Initializes the specified application. - /// - /// The application. - public void Init(HttpApplication application) - { - application.AuthenticateRequest += this.OnAuthenticateRequest; - application.PreSendRequestHeaders += this.OnPreSendRequestHeaders; - } - - /// - /// Disposes of the resources (other than memory) used by the module that implements . - /// - public void Dispose() - { - } - - private void OnAuthenticateRequest(object sender, EventArgs e) - { - var application = (HttpApplication)sender; - AuthenticateRequest(new HttpContextWrapper(application.Context), false); - } - - // DNN-6973: if the authentication cookie set by cookie slide in membership, - // then use SignIn method instead if current portal is in portal group. - private void OnPreSendRequestHeaders(object sender, EventArgs e) - { - var application = (HttpApplication)sender; - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var hasAuthCookie = application.Response.Headers["Set-Cookie"] != null - && application.Response.Headers["Set-Cookie"].Contains(FormsAuthentication.FormsCookieName); - if (portalSettings != null && hasAuthCookie && !application.Context.Items.Contains("DNN_UserSignIn")) - { - var isInPortalGroup = PortalController.IsMemberOfPortalGroup(portalSettings.PortalId); - if (isInPortalGroup) - { - var authCookie = application.Response.Cookies[FormsAuthentication.FormsCookieName]; - if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value) && string.IsNullOrEmpty(authCookie.Domain)) - { - application.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); - PortalSecurity.Instance.SignIn(UserController.Instance.GetCurrentUserInfo(), false); - } - } - } - } - /// /// Called when unverified user skin initialize. /// @@ -235,6 +188,53 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow context.Items.Add("UserInfo", new UserInfo()); } } + + /// + /// Initializes the specified application. + /// + /// The application. + public void Init(HttpApplication application) + { + application.AuthenticateRequest += this.OnAuthenticateRequest; + application.PreSendRequestHeaders += this.OnPreSendRequestHeaders; + } + + /// + /// Disposes of the resources (other than memory) used by the module that implements . + /// + public void Dispose() + { + } + + private void OnAuthenticateRequest(object sender, EventArgs e) + { + var application = (HttpApplication)sender; + AuthenticateRequest(new HttpContextWrapper(application.Context), false); + } + + // DNN-6973: if the authentication cookie set by cookie slide in membership, + // then use SignIn method instead if current portal is in portal group. + private void OnPreSendRequestHeaders(object sender, EventArgs e) + { + var application = (HttpApplication)sender; + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var hasAuthCookie = application.Response.Headers["Set-Cookie"] != null + && application.Response.Headers["Set-Cookie"].Contains(FormsAuthentication.FormsCookieName); + if (portalSettings != null && hasAuthCookie && !application.Context.Items.Contains("DNN_UserSignIn")) + { + var isInPortalGroup = PortalController.IsMemberOfPortalGroup(portalSettings.PortalId); + if (isInPortalGroup) + { + var authCookie = application.Response.Cookies[FormsAuthentication.FormsCookieName]; + if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value) && string.IsNullOrEmpty(authCookie.Domain)) + { + application.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); + PortalSecurity.Instance.SignIn(UserController.Instance.GetCurrentUserInfo(), false); + } + } + } + } private static bool RequireLogout(HttpContextBase context, UserInfo user) { diff --git a/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs b/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs index 5296f6a3402..a86efdde995 100644 --- a/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs +++ b/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs @@ -27,6 +27,12 @@ public class OutputCacheModule : IHttpModule private const string ContextKeyTabOutputCacheProvider = "OutputCache:TabOutputCacheProvider"; private HttpApplication _app; + private enum IncludeExcludeType + { + IncludeByDefault, + ExcludeByDefault, + } + public void Init(HttpApplication httpApp) { this._app = httpApp; @@ -57,12 +63,12 @@ private void OnResolveRequestCache(object sender, EventArgs e) return; } - if (this._app.Context.Request.RequestType == "POST" || ! this._app.Context.Request.Url.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + if (this._app.Context.Request.RequestType == "POST" || !this._app.Context.Request.Url.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) { return; } - var portalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"]; + var portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; int tabId = portalSettings.ActiveTab.TabID; Hashtable tabSettings = TabController.Instance.GetTabSettings(tabId); @@ -172,22 +178,22 @@ private void OnResolveRequestCache(object sender, EventArgs e) } } - if (! varyBy.ContainsKey("portalid")) + if (!varyBy.ContainsKey("portalid")) { varyBy.Add("portalid", portalId.ToString()); } - if (! varyBy.ContainsKey("tabid")) + if (!varyBy.ContainsKey("tabid")) { varyBy.Add("tabid", tabId.ToString()); } - if (! varyBy.ContainsKey("locale")) + if (!varyBy.ContainsKey("locale")) { varyBy.Add("locale", locale); } - if (! varyBy.ContainsKey("alias")) + if (!varyBy.ContainsKey("alias")) { varyBy.Add("alias", portalSettings.PortalAlias.HTTPAlias); } @@ -247,11 +253,5 @@ private void OnUpdateRequestCache(object sender, EventArgs e) } } } - - private enum IncludeExcludeType - { - IncludeByDefault, - ExcludeByDefault, - } } } diff --git a/DNN Platform/HttpModules/Services/ServicesModule.cs b/DNN Platform/HttpModules/Services/ServicesModule.cs index 61b91f3e7ab..dd281283f41 100644 --- a/DNN Platform/HttpModules/Services/ServicesModule.cs +++ b/DNN Platform/HttpModules/Services/ServicesModule.cs @@ -21,6 +21,19 @@ public void Init(HttpApplication context) context.PreSendRequestHeaders += this.OnPreSendRequestHeaders; } + public void Dispose() + { + } + + private static void InitDnn(object sender, EventArgs e) + { + var app = sender as HttpApplication; + if (app != null && ServiceApi.IsMatch(app.Context.Request.RawUrl.ToLowerInvariant())) + { + Initialize.Init(app); + } + } + private void OnPreSendRequestHeaders(object sender, EventArgs e) { var app = sender as HttpApplication; @@ -38,18 +51,5 @@ private void OnPreSendRequestHeaders(object sender, EventArgs e) // } } } - - private static void InitDnn(object sender, EventArgs e) - { - var app = sender as HttpApplication; - if (app != null && ServiceApi.IsMatch(app.Context.Request.RawUrl.ToLowerInvariant())) - { - Initialize.Init(app); - } - } - - public void Dispose() - { - } } } diff --git a/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs b/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs index 013b32a69d1..11aa4c84148 100644 --- a/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs +++ b/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs @@ -24,11 +24,11 @@ namespace DotNetNuke.HttpModules.UrlRewrite internal class BasicUrlRewriter : UrlRewriterBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BasicUrlRewriter)); - public static readonly Regex TabIdRegex = new Regex("&?tabid=\\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static readonly Regex PortalIdRegex = new Regex("&?portalid=\\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BasicUrlRewriter)); + internal override void RewriteUrl(object sender, EventArgs e) { var app = (HttpApplication)sender; @@ -249,8 +249,8 @@ internal override void RewriteUrl(object sender, EventArgs e) if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect && portalAliasInfo != null && !portalAliasInfo.IsPrimary - && !string.IsNullOrWhiteSpace(portalSettings.DefaultPortalAlias)) // don't redirect if no primary alias is defined - { + && !string.IsNullOrWhiteSpace(portalSettings.DefaultPortalAlias)) // don't redirect if no primary alias is defined + { // Permanently Redirect response.StatusCode = 301; @@ -327,9 +327,9 @@ internal override void RewriteUrl(object sender, EventArgs e) // redirect to secure connection response.RedirectPermanent(strURL); } - else + else - // when switching to an unsecure page, use a clientside redirector to avoid the browser security warning + // when switching to an unsecure page, use a clientside redirector to avoid the browser security warning { response.Clear(); diff --git a/DNN Platform/Library/Application/DotNetNukeContext.cs b/DNN Platform/Library/Application/DotNetNukeContext.cs index a01a976aed7..558ad76b508 100644 --- a/DNN Platform/Library/Application/DotNetNukeContext.cs +++ b/DNN Platform/Library/Application/DotNetNukeContext.cs @@ -38,6 +38,27 @@ protected DotNetNukeContext(Application application) this._skinEventListeners = new NaiveLockingList(); } + /// + /// Gets or sets the current app context. + /// + public static DotNetNukeContext Current + { + get + { + if (_current == null) + { + _current = new DotNetNukeContext(); + } + + return _current; + } + + set + { + _current = value; + } + } + /// /// Gets get the application. /// @@ -80,26 +101,5 @@ public IList SkinEventListeners return this._skinEventListeners; } } - - /// - /// Gets or sets the current app context. - /// - public static DotNetNukeContext Current - { - get - { - if (_current == null) - { - _current = new DotNetNukeContext(); - } - - return _current; - } - - set - { - _current = value; - } - } } } diff --git a/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs b/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs index 1eda170fae8..d72c81f00b2 100644 --- a/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs +++ b/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs @@ -12,26 +12,6 @@ public class ExclusiveLockStrategy : ILockStrategy private bool _isDisposed; private Thread _lockedThread; - - public ISharedCollectionLock GetReadLock() - { - return this.GetLock(TimeSpan.FromMilliseconds(-1)); - } - - public ISharedCollectionLock GetReadLock(TimeSpan timeout) - { - return this.GetLock(timeout); - } - - public ISharedCollectionLock GetWriteLock() - { - return this.GetLock(TimeSpan.FromMilliseconds(-1)); - } - - public ISharedCollectionLock GetWriteLock(TimeSpan timeout) - { - return this.GetLock(timeout); - } public bool ThreadCanRead { @@ -58,6 +38,26 @@ public bool SupportsConcurrentReads return false; } } + + public ISharedCollectionLock GetReadLock() + { + return this.GetLock(TimeSpan.FromMilliseconds(-1)); + } + + public ISharedCollectionLock GetReadLock(TimeSpan timeout) + { + return this.GetLock(timeout); + } + + public ISharedCollectionLock GetWriteLock() + { + return this.GetLock(TimeSpan.FromMilliseconds(-1)); + } + + public ISharedCollectionLock GetWriteLock(TimeSpan timeout) + { + return this.GetLock(timeout); + } public void Dispose() { @@ -65,6 +65,13 @@ public void Dispose() // todo remove disposable from interface? } + + public void Exit() + { + this.EnsureNotDisposed(); + Monitor.Exit(this._lock); + this._lockedThread = null; + } private ISharedCollectionLock GetLock(TimeSpan timeout) { @@ -103,13 +110,6 @@ private bool IsThreadLocked() return Thread.CurrentThread.Equals(this._lockedThread); } - public void Exit() - { - this.EnsureNotDisposed(); - Monitor.Exit(this._lock); - this._lockedThread = null; - } - private void EnsureNotDisposed() { if (this._isDisposed) diff --git a/DNN Platform/Library/Collections/MonitorLock.cs b/DNN Platform/Library/Collections/MonitorLock.cs index 20143b2051f..3ad20df1ddc 100644 --- a/DNN Platform/Library/Collections/MonitorLock.cs +++ b/DNN Platform/Library/Collections/MonitorLock.cs @@ -8,15 +8,15 @@ namespace DotNetNuke.Collections.Internal internal class MonitorLock : IDisposable, ISharedCollectionLock { private ExclusiveLockStrategy _lockStrategy; + + // To detect redundant calls + private bool _isDisposed; public MonitorLock(ExclusiveLockStrategy lockStrategy) { this._lockStrategy = lockStrategy; } - // To detect redundant calls - private bool _isDisposed; - public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. diff --git a/DNN Platform/Library/Collections/NaiveLockingList.cs b/DNN Platform/Library/Collections/NaiveLockingList.cs index 915aff196f0..c869481f8bb 100644 --- a/DNN Platform/Library/Collections/NaiveLockingList.cs +++ b/DNN Platform/Library/Collections/NaiveLockingList.cs @@ -11,6 +11,63 @@ namespace DotNetNuke.Collections.Internal public class NaiveLockingList : IList { private readonly SharedList _list = new SharedList(); + + /// + /// Gets access to the underlying SharedList. + /// + /// Allows locking to be explicitly managed for the sake of effeciency + /// + /// + public SharedList SharedList + { + get + { + return this._list; + } + } + + public int Count + { + get + { + return this.DoInReadLock(() => this._list.Count); + } + } + + public bool IsReadOnly + { + get + { + return false; + } + } + + public T this[int index] + { + get + { + return this.DoInReadLock(() => this._list[index]); + } + + set + { + this.DoInWriteLock(() => this._list[index] = value); + } + } + + public IEnumerator GetEnumerator() + { + // disposal of enumerator will release read lock + // TODO is there a need for some sort of timed release? the timmer must release from the correct thread + // if using RWLS + var readLock = this._list.GetReadLock(); + return new NaiveLockingEnumerator(this._list.GetEnumerator(), readLock); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return this.GetEnumerator(); + } // TODO is no recursion the correct policy private void DoInReadLock(Action action) @@ -47,34 +104,6 @@ private TRet DoInWriteLock(Func func) } } - /// - /// Gets access to the underlying SharedList. - /// - /// Allows locking to be explicitly managed for the sake of effeciency - /// - /// - public SharedList SharedList - { - get - { - return this._list; - } - } - - public IEnumerator GetEnumerator() - { - // disposal of enumerator will release read lock - // TODO is there a need for some sort of timed release? the timmer must release from the correct thread - // if using RWLS - var readLock = this._list.GetReadLock(); - return new NaiveLockingEnumerator(this._list.GetEnumerator(), readLock); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.GetEnumerator(); - } - public void Add(T item) { this.DoInWriteLock(() => this._list.Add(item)); @@ -100,22 +129,6 @@ public bool Remove(T item) return this.DoInWriteLock(() => this._list.Remove(item)); } - public int Count - { - get - { - return this.DoInReadLock(() => this._list.Count); - } - } - - public bool IsReadOnly - { - get - { - return false; - } - } - public int IndexOf(T item) { return this.DoInReadLock(() => this._list.IndexOf(item)); @@ -131,19 +144,6 @@ public void RemoveAt(int index) this.DoInWriteLock(() => this._list.RemoveAt(index)); } - public T this[int index] - { - get - { - return this.DoInReadLock(() => this._list[index]); - } - - set - { - this.DoInWriteLock(() => this._list[index] = value); - } - } - public class NaiveLockingEnumerator : IEnumerator { private readonly IEnumerator _enumerator; @@ -156,14 +156,9 @@ public NaiveLockingEnumerator(IEnumerator enumerator, ISharedCollectionLock r this._readLock = readLock; } - public bool MoveNext() - { - return this._enumerator.MoveNext(); - } - - public void Reset() + ~NaiveLockingEnumerator() { - this._enumerator.Reset(); + this.Dispose(false); } public T Current @@ -182,6 +177,16 @@ object IEnumerator.Current } } + public bool MoveNext() + { + return this._enumerator.MoveNext(); + } + + public void Reset() + { + this._enumerator.Reset(); + } + public void Dispose() { this.Dispose(true); @@ -204,11 +209,6 @@ protected virtual void Dispose(bool disposing) this._isDisposed = true; } } - - ~NaiveLockingEnumerator() - { - this.Dispose(false); - } } } } diff --git a/DNN Platform/Library/Collections/PagedList.cs b/DNN Platform/Library/Collections/PagedList.cs index 2d9c829efbf..b02c345eee0 100644 --- a/DNN Platform/Library/Collections/PagedList.cs +++ b/DNN Platform/Library/Collections/PagedList.cs @@ -42,6 +42,21 @@ public PagedList(IEnumerable items, int totalCount, int pageIndex, int pageSi this.CommonConstruct(items, totalCount, pageIndex, pageSize); } + /// + /// Gets a value indicating whether gets a boolean indicating if there is a next page available. + /// + public bool HasNextPage { get; private set; } + + /// + /// Gets a value indicating whether gets a boolean indicating if there is a previous page available. + /// + public bool HasPreviousPage { get; private set; } + + /// + /// Gets a value indicating whether gets a boolean indicating if this is the first page. + /// + public bool IsFirstPage { get; private set; } + private void CommonConstruct(IEnumerable items, int totalCount, int pageIndex, int pageSize) { this.PageCount = (int)Math.Ceiling(totalCount / (double)pageSize); @@ -76,21 +91,6 @@ private void CommonConstruct(IEnumerable items, int totalCount, int pageIndex this.IsFirstPage = this.PageIndex <= 0; this.IsLastPage = this.PageIndex >= (this.PageCount - 1); } - - /// - /// Gets a value indicating whether gets a boolean indicating if there is a next page available. - /// - public bool HasNextPage { get; private set; } - - /// - /// Gets a value indicating whether gets a boolean indicating if there is a previous page available. - /// - public bool HasPreviousPage { get; private set; } - - /// - /// Gets a value indicating whether gets a boolean indicating if this is the first page. - /// - public bool IsFirstPage { get; private set; } /// /// Gets a value indicating whether gets a boolean indicating if this is the last page. diff --git a/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs b/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs index b47fe069c30..fb70a956453 100644 --- a/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs +++ b/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs @@ -15,6 +15,26 @@ public class ReaderWriterLockStrategy : IDisposable, ILockStrategy private ReaderWriterLockSlim _lock; private LockRecursionPolicy _lockRecursionPolicy; + + private bool _isDisposed; + + public ReaderWriterLockStrategy() + : this(LockRecursionPolicy.NoRecursion) + { + } + + public ReaderWriterLockStrategy(LockRecursionPolicy recursionPolicy) + { + this._lockRecursionPolicy = recursionPolicy; + this._lock = new ReaderWriterLockSlim(recursionPolicy); + } + + // The special constructor is used to deserialize values. + public ReaderWriterLockStrategy(SerializationInfo info, StreamingContext context) + { + this._lockRecursionPolicy = (LockRecursionPolicy)info.GetValue("_lockRecursionPolicy", typeof(LockRecursionPolicy)); + this._lock = new ReaderWriterLockSlim(this._lockRecursionPolicy); + } private ReaderWriterLockSlim Lock { @@ -32,22 +52,36 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) info.AddValue("_lockRecursionPolicy", this._lockRecursionPolicy, typeof(LockRecursionPolicy)); } - public ReaderWriterLockStrategy() - : this(LockRecursionPolicy.NoRecursion) + ~ReaderWriterLockStrategy() { + // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. + this.Dispose(false); + } + + public bool ThreadCanRead + { + get + { + this.EnsureNotDisposed(); + return this.Lock.IsReadLockHeld || this.Lock.IsWriteLockHeld; + } } - public ReaderWriterLockStrategy(LockRecursionPolicy recursionPolicy) + public bool ThreadCanWrite { - this._lockRecursionPolicy = recursionPolicy; - this._lock = new ReaderWriterLockSlim(recursionPolicy); + get + { + this.EnsureNotDisposed(); + return this.Lock.IsWriteLockHeld; + } } - // The special constructor is used to deserialize values. - public ReaderWriterLockStrategy(SerializationInfo info, StreamingContext context) + public bool SupportsConcurrentReads { - this._lockRecursionPolicy = (LockRecursionPolicy)info.GetValue("_lockRecursionPolicy", typeof(LockRecursionPolicy)); - this._lock = new ReaderWriterLockSlim(this._lockRecursionPolicy); + get + { + return true; + } } public ISharedCollectionLock GetReadLock() @@ -88,34 +122,6 @@ public ISharedCollectionLock GetWriteLock(TimeSpan timeout) } } - public bool ThreadCanRead - { - get - { - this.EnsureNotDisposed(); - return this.Lock.IsReadLockHeld || this.Lock.IsWriteLockHeld; - } - } - - public bool ThreadCanWrite - { - get - { - this.EnsureNotDisposed(); - return this.Lock.IsWriteLockHeld; - } - } - - public bool SupportsConcurrentReads - { - get - { - return true; - } - } - - private bool _isDisposed; - public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. @@ -123,14 +129,6 @@ public void Dispose() GC.SuppressFinalize(this); } - private void EnsureNotDisposed() - { - if (this._isDisposed) - { - throw new ObjectDisposedException("ReaderWriterLockStrategy"); - } - } - // To detect redundant calls // IDisposable @@ -153,11 +151,13 @@ protected virtual void Dispose(bool disposing) this._isDisposed = true; } - ~ReaderWriterLockStrategy() + private void EnsureNotDisposed() { - // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. - this.Dispose(false); - } + if (this._isDisposed) + { + throw new ObjectDisposedException("ReaderWriterLockStrategy"); + } + } // This code added by Visual Basic to correctly implement the disposable pattern. } diff --git a/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs b/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs index 06a32fdf3d5..a1c9d1fbcb9 100644 --- a/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs +++ b/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs @@ -15,6 +15,11 @@ public ReaderWriterSlimLock(ReaderWriterLockSlim @lock) { this._lock = @lock; } + + ~ReaderWriterSlimLock() + { + this.Dispose(false); + } public void Dispose() { @@ -22,14 +27,6 @@ public void Dispose() GC.SuppressFinalize(this); } - - private void EnsureNotDisposed() - { - if (this._disposed) - { - throw new ObjectDisposedException("ReaderWriterSlimLock"); - } - } protected virtual void Dispose(bool disposing) { @@ -58,10 +55,13 @@ protected virtual void Dispose(bool disposing) this._disposed = true; } } - - ~ReaderWriterSlimLock() + + private void EnsureNotDisposed() { - this.Dispose(false); + if (this._disposed) + { + throw new ObjectDisposedException("ReaderWriterSlimLock"); + } } } } diff --git a/DNN Platform/Library/Collections/SharedDictionary.cs b/DNN Platform/Library/Collections/SharedDictionary.cs index 43476eb01dd..8981a89431e 100644 --- a/DNN Platform/Library/Collections/SharedDictionary.cs +++ b/DNN Platform/Library/Collections/SharedDictionary.cs @@ -31,6 +31,41 @@ public SharedDictionary(LockingStrategy strategy) { } + ~SharedDictionary() + { + this.Dispose(false); + } + + public int Count + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.Count; + } + } + + public bool IsReadOnly + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.IsReadOnly; + } + } + + public ICollection Keys + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.Keys; + } + } + internal IDictionary BackingDictionary { get @@ -84,23 +119,30 @@ public bool Remove(KeyValuePair item) return this._dict.Remove(item); } - public int Count + public ICollection Values { get { this.EnsureNotDisposed(); this.EnsureReadAccess(); - return this._dict.Count; + return this._dict.Values; } - } + } - public bool IsReadOnly + public TValue this[TKey key] { get { this.EnsureNotDisposed(); this.EnsureReadAccess(); - return this._dict.IsReadOnly; + return this._dict[key]; + } + + set + { + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._dict[key] = value; } } @@ -131,43 +173,6 @@ public bool TryGetValue(TKey key, out TValue value) this.EnsureReadAccess(); return this._dict.TryGetValue(key, out value); } - - public TValue this[TKey key] - { - get - { - this.EnsureNotDisposed(); - this.EnsureReadAccess(); - return this._dict[key]; - } - - set - { - this.EnsureNotDisposed(); - this.EnsureWriteAccess(); - this._dict[key] = value; - } - } - - public ICollection Keys - { - get - { - this.EnsureNotDisposed(); - this.EnsureReadAccess(); - return this._dict.Keys; - } - } - - public ICollection Values - { - get - { - this.EnsureNotDisposed(); - this.EnsureReadAccess(); - return this._dict.Values; - } - } public void Dispose() { @@ -207,22 +212,6 @@ public ISharedCollectionLock GetWriteLock(int millisecondTimeout) { return this.GetWriteLock(TimeSpan.FromMilliseconds(millisecondTimeout)); } - - private void EnsureReadAccess() - { - if (! this._lockController.ThreadCanRead) - { - throw new ReadLockRequiredException(); - } - } - - private void EnsureWriteAccess() - { - if (!this._lockController.ThreadCanWrite) - { - throw new WriteLockRequiredException(); - } - } public IEnumerator> IEnumerable_GetEnumerator() { @@ -233,14 +222,6 @@ public IEnumerator> IEnumerable_GetEnumerator() return this._dict.GetEnumerator(); } - private void EnsureNotDisposed() - { - if (this._isDisposed) - { - throw new ObjectDisposedException("SharedDictionary"); - } - } - protected virtual void Dispose(bool disposing) { if (!this._isDisposed) @@ -257,10 +238,29 @@ protected virtual void Dispose(bool disposing) this._isDisposed = true; } } + + private void EnsureReadAccess() + { + if (!this._lockController.ThreadCanRead) + { + throw new ReadLockRequiredException(); + } + } - ~SharedDictionary() + private void EnsureWriteAccess() { - this.Dispose(false); + if (!this._lockController.ThreadCanWrite) + { + throw new WriteLockRequiredException(); + } + } + + private void EnsureNotDisposed() + { + if (this._isDisposed) + { + throw new ObjectDisposedException("SharedDictionary"); + } } } } diff --git a/DNN Platform/Library/Collections/SharedList.cs b/DNN Platform/Library/Collections/SharedList.cs index 6d250c324c9..9bed4fa0cfd 100644 --- a/DNN Platform/Library/Collections/SharedList.cs +++ b/DNN Platform/Library/Collections/SharedList.cs @@ -11,6 +11,8 @@ public class SharedList : IList, IDisposable { private readonly List _list = new List(); private ILockStrategy _lockStrategy; + + private bool _isDisposed; public SharedList() : this(LockingStrategy.ReaderWriter) @@ -27,6 +29,31 @@ public SharedList(LockingStrategy strategy) { } + ~SharedList() + { + this.Dispose(false); + } + + public int Count + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._list.Count; + } + } + + public bool IsReadOnly + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return ((ICollection)this._list).IsReadOnly; + } + } + internal IList BackingList { get @@ -34,6 +61,23 @@ internal IList BackingList return this._list; } } + + public T this[int index] + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._list[index]; + } + + set + { + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._list[index] = value; + } + } public void Add(T item) { @@ -63,26 +107,6 @@ public void CopyTo(T[] array, int arrayIndex) this._list.CopyTo(array, arrayIndex); } - public int Count - { - get - { - this.EnsureNotDisposed(); - this.EnsureReadAccess(); - return this._list.Count; - } - } - - public bool IsReadOnly - { - get - { - this.EnsureNotDisposed(); - this.EnsureReadAccess(); - return ((ICollection)this._list).IsReadOnly; - } - } - public bool Remove(T item) { this.EnsureNotDisposed(); @@ -111,23 +135,6 @@ public void Insert(int index, T item) this._list.Insert(index, item); } - public T this[int index] - { - get - { - this.EnsureNotDisposed(); - this.EnsureReadAccess(); - return this._list[index]; - } - - set - { - this.EnsureNotDisposed(); - this.EnsureWriteAccess(); - this._list[index] = value; - } - } - public void RemoveAt(int index) { this.EnsureNotDisposed(); @@ -139,8 +146,6 @@ IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator1(); } - - private bool _isDisposed; public void Dispose() { @@ -156,6 +161,17 @@ public void EnsureNotDisposed() throw new ObjectDisposedException("SharedList"); } } + + public ISharedCollectionLock GetReadLock() + { + return this.GetReadLock(TimeSpan.FromMilliseconds(-1)); + } + + public ISharedCollectionLock GetReadLock(TimeSpan timeOut) + { + this.EnsureNotDisposed(); + return this._lockStrategy.GetReadLock(timeOut); + } // IDisposable protected virtual void Dispose(bool disposing) @@ -174,22 +190,6 @@ protected virtual void Dispose(bool disposing) this._isDisposed = true; } - ~SharedList() - { - this.Dispose(false); - } - - public ISharedCollectionLock GetReadLock() - { - return this.GetReadLock(TimeSpan.FromMilliseconds(-1)); - } - - public ISharedCollectionLock GetReadLock(TimeSpan timeOut) - { - this.EnsureNotDisposed(); - return this._lockStrategy.GetReadLock(timeOut); - } - public ISharedCollectionLock GetReadLock(int millisecondTimeout) { return this.GetReadLock(TimeSpan.FromMilliseconds(millisecondTimeout)); @@ -211,9 +211,14 @@ public ISharedCollectionLock GetWriteLock(int millisecondTimeout) return this.GetWriteLock(TimeSpan.FromMilliseconds(millisecondTimeout)); } + public IEnumerator GetEnumerator1() + { + return this.GetEnumerator(); + } + private void EnsureReadAccess() { - if (! this._lockStrategy.ThreadCanRead) + if (!this._lockStrategy.ThreadCanRead) { throw new ReadLockRequiredException(); } @@ -226,10 +231,5 @@ private void EnsureWriteAccess() throw new WriteLockRequiredException(); } } - - public IEnumerator GetEnumerator1() - { - return this.GetEnumerator(); - } } } diff --git a/DNN Platform/Library/Common/Controls/ActionLessForm.cs b/DNN Platform/Library/Common/Controls/ActionLessForm.cs index 91c13149b82..cd54401c381 100644 --- a/DNN Platform/Library/Common/Controls/ActionLessForm.cs +++ b/DNN Platform/Library/Common/Controls/ActionLessForm.cs @@ -30,8 +30,8 @@ protected override void RenderAttributes(HtmlTextWriter writer) } if (this.ID != null) - { - // Locate and replace id attribute + { + // Locate and replace id attribute StartPoint = html.IndexOf("id=\""); if (StartPoint >= 0) { diff --git a/DNN Platform/Library/Common/Globals.cs b/DNN Platform/Library/Common/Globals.cs index 6709b389942..fb1f495d536 100644 --- a/DNN Platform/Library/Common/Globals.cs +++ b/DNN Platform/Library/Common/Globals.cs @@ -66,10 +66,28 @@ namespace DotNetNuke.Common [StandardModule] public sealed class Globals { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(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"; public static readonly Regex EmailValidatorRegex = new Regex(glbEmailRegEx, RegexOptions.Compiled); public static readonly Regex NonAlphanumericCharacters = new Regex("[^A-Za-z0-9]", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Globals)); public static readonly Regex InvalidCharacters = new Regex("[^A-Za-z0-9_-]", RegexOptions.Compiled | RegexOptions.CultureInvariant); public static readonly Regex InvalidInitialCharacters = new Regex("^[^A-Za-z]", RegexOptions.Compiled | RegexOptions.CultureInvariant); public static readonly Regex NumberMatchRegex = new Regex(@"^\d+$", RegexOptions.Compiled); @@ -189,24 +207,6 @@ public enum UpgradeStatus Unknown, } - /// - /// 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. /// @@ -321,6 +321,7 @@ public enum UpgradeStatus /// /// ]]> public const string glbScriptFormat = ""; + private const string _tabPathInvalidCharsEx = "[&\\? \\./'#:\\*]"; // this value should keep same with the value used in sp BuildTabLevelAndPath to remove invalid chars. // global constants for the life of the application ( set in Application_Start ) private static string _applicationPath; @@ -333,9 +334,10 @@ public enum UpgradeStatus private static string _installPath; private static Version _dataBaseVersion; private static UpgradeStatus _status = UpgradeStatus.Unknown; - 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(); + /// /// Gets the application path. /// @@ -373,17 +375,6 @@ public static string ApplicationMapPath } } - private static string GetCurrentDomainDirectory() - { - var dir = AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\\"); - if (dir.Length > 3 && dir.EndsWith("\\")) - { - dir = dir.Substring(0, dir.Length - 1); - } - - return dir; - } - /// /// Gets the desktop module path. /// @@ -429,6 +420,17 @@ public static Version DataBaseVersion } } + private static string GetCurrentDomainDirectory() + { + var dir = AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\\"); + if (dir.Length > 3 && dir.EndsWith("\\")) + { + dir = dir.Substring(0, dir.Length - 1); + } + + return dir; + } + /// /// Gets the host map path. /// @@ -537,36 +539,6 @@ public static string InstallPath /// public static Version DatabaseEngineVersion { get; set; } - /// - /// Gets or sets the Dependency Service. - /// - /// - /// The Dependency Service. - /// - internal static IServiceProvider DependencyProvider { get; set; } - - /// - /// Redirects the specified URL. - /// - /// The URL. - /// if set to true [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); - } - } - /// /// Gets the status of application. /// @@ -610,7 +582,7 @@ public static UpgradeStatus Status else { // An error that occurs before the database has been installed should be treated as a new install - tempStatus = UpgradeStatus.Install; + tempStatus = UpgradeStatus.Install; } } else if (DataBaseVersion == null) @@ -655,190 +627,84 @@ public static UpgradeStatus Status } } - public static bool IncrementalVersionExists(Version version) - { - Provider currentdataprovider = Config.GetDefaultProvider("data"); - string providerpath = currentdataprovider.Attributes["providerPath"]; - - // If the provider path does not exist, then there can't be any log files - if (!string.IsNullOrEmpty(providerpath)) - { - providerpath = HttpRuntime.AppDomainAppPath + providerpath.Replace("~", string.Empty); - if (Directory.Exists(providerpath)) - { - var incrementalcount = Directory.GetFiles(providerpath, Upgrade.GetStringVersion(version) + ".*." + Upgrade.DefaultProvider).Length; - - if (incrementalcount > Globals.GetLastAppliedIteration(version)) - { - return true; - } - } - } - - return false; - } - - /// - /// IsInstalled looks at various file artifacts to determine if DotNetNuke has already been installed. - /// - /// - /// - /// 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. - /// - internal static bool IsInstalled() - { - const int c_PassingScore = 4; - int installationdatefactor = Convert.ToInt32(HasInstallationDate() ? 1 : 0); - int dataproviderfactor = Convert.ToInt32(HasDataProviderLogFiles() ? 3 : 0); - int htmlmodulefactor = Convert.ToInt32(ModuleDirectoryExists("html") ? 2 : 0); - int portaldirectoryfactor = Convert.ToInt32(HasNonDefaultPortalDirectory() ? 2 : 0); - int localexecutionfactor = Convert.ToInt32(HttpContext.Current.Request.IsLocal ? c_PassingScore - 1 : 0); - - // This calculation ensures that you have a more than one item that indicates you have already installed DNN. - // While it is possible that you might not have an installation date or that you have deleted log files - // it is unlikely that you have removed every trace of an installation and yet still have a working install - bool isInstalled = (!IsInstallationURL()) && ((installationdatefactor + dataproviderfactor + htmlmodulefactor + portaldirectoryfactor + localexecutionfactor) >= c_PassingScore); - - // we need to tighten this check. We now are enforcing the existence of the InstallVersion value in web.config. If - // this value exists, then DNN was previously installed, and we should never try to re-install it - return isInstalled || HasInstallVersion(); - } - /// - /// Determines whether has data provider log files. + /// Gets image file types. /// - /// - /// true if has data provider log files; otherwise, false. - /// - private static bool HasDataProviderLogFiles() + /// Values read from ImageTypes List. If there is not List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico. + public static string glbImageFileTypes { - Provider currentdataprovider = Config.GetDefaultProvider("data"); - string providerpath = currentdataprovider.Attributes["providerPath"]; - - // If the provider path does not exist, then there can't be any log files - if (!string.IsNullOrEmpty(providerpath)) + get { - providerpath = HttpContext.Current.Server.MapPath(providerpath); - if (Directory.Exists(providerpath)) + var listController = new ListController(); + var listEntries = listController.GetListEntryInfoItems("ImageTypes"); + if (listEntries == null || listEntries.Count() == 0) { - return Directory.GetFiles(providerpath, "*.log.resources").Length > 0; + return "jpg,jpeg,jpe,gif,bmp,png,svg,ico"; } - } - return false; - } - - /// - /// Determines whether has installation date. - /// - /// - /// true if has installation date; otherwise, false. - /// - private static bool HasInstallationDate() - { - return Config.GetSetting("InstallationDate") != null; + return string.Join(",", listEntries.Select(l => l.Value)); + } } - /// - /// Determines whether has InstallVersion set. - /// - /// - /// true if has installation date; otherwise, false. - /// - private static bool HasInstallVersion() + public static TimeSpan ElapsedSinceAppStart { - return Config.GetSetting("InstallVersion") != null; + get + { + return AppStopwatch.Elapsed; + } } /// - /// Check whether the modules directory is exists. + /// Gets or sets the Dependency Service. /// - /// Name of the module. - /// - /// true if the module directory exist, otherwise, false. - /// - private static bool ModuleDirectoryExists(string moduleName) - { - string dir = ApplicationMapPath + "\\desktopmodules\\" + moduleName; - return Directory.Exists(dir); - } + /// + /// The Dependency Service. + /// + internal static IServiceProvider DependencyProvider { get; set; } /// - /// Determines whether has portal directory except default portal directory in portal path. + /// Redirects the specified URL. /// - /// - /// true if has portal directory except default portal directory in portal path; otherwise, false. - /// - private static bool HasNonDefaultPortalDirectory() + /// The URL. + /// if set to true [end response]. + public static void Redirect(string url, bool endResponse) { - string dir = ApplicationMapPath + "\\portals"; - if (Directory.Exists(dir)) + try { - return Directory.GetDirectories(dir).Length > 1; + 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); } - - return false; } - /// - /// Determines whether current request is for install. - /// - /// - /// true if current request is for install; otherwise, false. - /// - private static bool IsInstallationURL() + public static bool IncrementalVersionExists(Version version) { - string requestURL = HttpContext.Current.Request.RawUrl.ToLowerInvariant().Replace("\\", "/"); - return requestURL.Contains("/install.aspx") || requestURL.Contains("/installwizard.aspx"); - } + Provider currentdataprovider = Config.GetDefaultProvider("data"); + string providerpath = currentdataprovider.Attributes["providerPath"]; - /// - /// Gets the culture code of the tab. - /// - /// The tab ID. - /// if set to true [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) + // If the provider path does not exist, then there can't be any log files + if (!string.IsNullOrEmpty(providerpath)) { - TabInfo linkTab = TabController.Instance.GetTab(TabID, IsSuperTab ? Null.NullInteger : settings.PortalId, false); - if (linkTab != null) + providerpath = HttpRuntime.AppDomainAppPath + providerpath.Replace("~", string.Empty); + if (Directory.Exists(providerpath)) { - cultureCode = linkTab.CultureCode; - } + var incrementalcount = Directory.GetFiles(providerpath, Upgrade.GetStringVersion(version) + ".*." + Upgrade.DefaultProvider).Length; - if (string.IsNullOrEmpty(cultureCode)) - { - cultureCode = Thread.CurrentThread.CurrentCulture.Name; + if (incrementalcount > Globals.GetLastAppliedIteration(version)) + { + return true; + } } } - return cultureCode; - } - - /// - /// Gets image file types. - /// - /// Values read from ImageTypes List. If there is not List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico. - public static string glbImageFileTypes - { - get - { - var listController = new ListController(); - var listEntries = listController.GetListEntryInfoItems("ImageTypes"); - if (listEntries == null || listEntries.Count() == 0) - { - return "jpg,jpeg,jpe,gif,bmp,png,svg,ico"; - } - - return string.Join(",", listEntries.Select(l => l.Value)); - } + return false; } /// @@ -970,57 +836,201 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul // assign pivot column value if (!string.IsNullOrEmpty(FieldTypeColumn)) { - FieldType = result[FieldTypeColumn].ToString(); + 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; + } + + /// + /// IsInstalled looks at various file artifacts to determine if DotNetNuke has already been installed. + /// + /// + /// + /// 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. + /// + internal static bool IsInstalled() + { + const int c_PassingScore = 4; + int installationdatefactor = Convert.ToInt32(HasInstallationDate() ? 1 : 0); + int dataproviderfactor = Convert.ToInt32(HasDataProviderLogFiles() ? 3 : 0); + int htmlmodulefactor = Convert.ToInt32(ModuleDirectoryExists("html") ? 2 : 0); + int portaldirectoryfactor = Convert.ToInt32(HasNonDefaultPortalDirectory() ? 2 : 0); + int localexecutionfactor = Convert.ToInt32(HttpContext.Current.Request.IsLocal ? c_PassingScore - 1 : 0); + + // This calculation ensures that you have a more than one item that indicates you have already installed DNN. + // While it is possible that you might not have an installation date or that you have deleted log files + // it is unlikely that you have removed every trace of an installation and yet still have a working install + bool isInstalled = (!IsInstallationURL()) && ((installationdatefactor + dataproviderfactor + htmlmodulefactor + portaldirectoryfactor + localexecutionfactor) >= c_PassingScore); + + // we need to tighten this check. We now are enforcing the existence of the InstallVersion value in web.config. If + // this value exists, then DNN was previously installed, and we should never try to re-install it + return isInstalled || HasInstallVersion(); + } + + /// + /// Gets the culture code of the tab. + /// + /// The tab ID. + /// if set to true [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; } - else + + if (string.IsNullOrEmpty(cultureCode)) { - FieldType = "String"; + cultureCode = Thread.CurrentThread.CurrentCulture.Name; } + } - 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; - } - } + return cultureCode; + } - break; + /// + /// Determines whether has data provider log files. + /// + /// + /// true if has data provider log files; otherwise, false. + /// + private static bool HasDataProviderLogFiles() + { + Provider currentdataprovider = Config.GetDefaultProvider("data"); + string providerpath = currentdataprovider.Attributes["providerPath"]; + + // If the provider path does not exist, then there can't be any log files + if (!string.IsNullOrEmpty(providerpath)) + { + providerpath = HttpContext.Current.Server.MapPath(providerpath); + if (Directory.Exists(providerpath)) + { + return Directory.GetFiles(providerpath, "*.log.resources").Length > 0; } } - result.Close(); + return false; + } - // add row - if (intKeyColumn != -1) + /// + /// Determines whether has installation date. + /// + /// + /// true if has installation date; otherwise, false. + /// + private static bool HasInstallationDate() + { + return Config.GetSetting("InstallationDate") != null; + } + + /// + /// Determines whether has InstallVersion set. + /// + /// + /// true if has installation date; otherwise, false. + /// + private static bool HasInstallVersion() + { + return Config.GetSetting("InstallVersion") != null; + } + + /// + /// Check whether the modules directory is exists. + /// + /// Name of the module. + /// + /// true if the module directory exist, otherwise, false. + /// + private static bool ModuleDirectoryExists(string moduleName) + { + string dir = ApplicationMapPath + "\\desktopmodules\\" + moduleName; + return Directory.Exists(dir); + } + + /// + /// Determines whether has portal directory except default portal directory in portal path. + /// + /// + /// true if has portal directory except default portal directory in portal path; otherwise, false. + /// + private static bool HasNonDefaultPortalDirectory() + { + string dir = ApplicationMapPath + "\\portals"; + if (Directory.Exists(dir)) { - tab.Rows.Add(row); + return Directory.GetDirectories(dir).Length > 1; } - // finalize dataset - crosstab.AcceptChanges(); + return false; + } - // return the dataset - return crosstab; + /// + /// Determines whether current request is for install. + /// + /// + /// true if current request is for install; otherwise, false. + /// + private static bool IsInstallationURL() + { + string requestURL = HttpContext.Current.Request.RawUrl.ToLowerInvariant().Replace("\\", "/"); + return requestURL.Contains("/install.aspx") || requestURL.Contains("/installwizard.aspx"); } /// @@ -1231,21 +1241,21 @@ public static void UpdateDataBaseVersion(Version version) public static void UpdateDataBaseVersionIncrement(Version version, int increment) { // update the version and increment - DataProvider.Instance().UpdateDatabaseVersionIncrement(version.Major, version.Minor, version.Build, increment, DotNetNukeContext.Current.Application.Name); - _dataBaseVersion = version; + DataProvider.Instance().UpdateDatabaseVersionIncrement(version.Major, version.Minor, version.Build, increment, DotNetNukeContext.Current.Application.Name); + _dataBaseVersion = version; } public static int GetLastAppliedIteration(Version version) - { - try - { - return DataProvider.Instance().GetLastAppliedIteration(version.Major, version.Minor, version.Build); - } - catch (Exception) - { - return 0; - } - } + { + try + { + return DataProvider.Instance().GetLastAppliedIteration(version.Major, version.Minor, version.Build); + } + catch (Exception) + { + return 0; + } + } /// /// Adds the port. @@ -2363,6 +2373,27 @@ public static void DeleteFilesRecursive(string strRoot, string filter) FileSystemUtils.DeleteFilesRecursive(strRoot, filter); } + /// + /// 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); + } + private static void DeleteFile(string filePath) { try @@ -2400,27 +2431,6 @@ private static void DeleteFolder(string strRoot) } } - /// - /// 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. /// @@ -3715,38 +3725,6 @@ public static bool ValidateModuleInTab(int tabId, string moduleName) return hasModule; } - /// - /// Check whether the Filename matches extensions. - /// - /// The filename. - /// The valid extensions. - /// true if the Filename matches extensions, otherwise, false. - private static bool FilenameMatchesExtensions(string filename, string strExtensions) - { - bool result = string.IsNullOrEmpty(strExtensions); - if (!result) - { - filename = filename.ToUpper(); - strExtensions = strExtensions.ToUpper(); - foreach (string extension in strExtensions.Split(',')) - { - string ext = extension.Trim(); - if (!ext.StartsWith(".")) - { - ext = "." + extension; - } - - result = filename.EndsWith(extension); - if (result) - { - break; - } - } - } - - return result; - } - /// ----------------------------------------------------------------------------- /// /// DeserializeHashTableBase64 deserializes a Hashtable using Binary Formatting. @@ -3804,6 +3782,38 @@ public static Hashtable DeserializeHashTableXml(string Source) return XmlUtils.DeSerializeHashtable(Source, "profile"); } + /// + /// Check whether the Filename matches extensions. + /// + /// The filename. + /// The valid extensions. + /// true if the Filename matches extensions, otherwise, false. + private static bool FilenameMatchesExtensions(string filename, string strExtensions) + { + bool result = string.IsNullOrEmpty(strExtensions); + if (!result) + { + filename = filename.ToUpper(); + strExtensions = strExtensions.ToUpper(); + foreach (string extension in strExtensions.Split(',')) + { + string ext = extension.Trim(); + if (!ext.StartsWith(".")) + { + ext = "." + extension; + } + + result = filename.EndsWith(extension); + if (result) + { + break; + } + } + } + + return result; + } + /// ----------------------------------------------------------------------------- /// /// SerializeHashTableBase64 serializes a Hashtable using Binary Formatting. @@ -4045,19 +4055,9 @@ public static string PreventSQLInjection(string strSQL) return PortalSecurity.Instance.InputFilter(strSQL, PortalSecurity.FilterFlag.NoSQL); } - private static readonly Stopwatch AppStopwatch = Stopwatch.StartNew(); - internal static void ResetAppStartElapseTime() { AppStopwatch.Restart(); } - - public static TimeSpan ElapsedSinceAppStart - { - get - { - return AppStopwatch.Elapsed; - } - } } } diff --git a/DNN Platform/Library/Common/Initialize.cs b/DNN Platform/Library/Common/Initialize.cs index 43d4f29199f..98a49bac67c 100644 --- a/DNN Platform/Library/Common/Initialize.cs +++ b/DNN Platform/Library/Common/Initialize.cs @@ -38,6 +38,55 @@ public class Initialize private static bool InitializedAlready; private static readonly object InitializeLock = new object(); + /// ----------------------------------------------------------------------------- + /// + /// Inits the app. + /// + /// The app. + /// ----------------------------------------------------------------------------- + public static void Init(HttpApplication app) + { + string redirect; + + // Check if app is initialised + if (InitializedAlready && Globals.Status == Globals.UpgradeStatus.None) + { + return; + } + + lock (InitializeLock) + { + // Double-Check if app was initialised by another request + if (InitializedAlready && Globals.Status == Globals.UpgradeStatus.None) + { + return; + } + + // Initialize ... + redirect = InitializeApp(app, ref InitializedAlready); + } + + if (!string.IsNullOrEmpty(redirect)) + { + app.Response.Redirect(redirect, true); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// LogStart logs the Application Start Event. + /// + /// ----------------------------------------------------------------------------- + public static void LogStart() + { + var log = new LogInfo + { + BypassBuffering = true, + LogTypeKey = EventLogController.EventLogType.APPLICATION_START.ToString(), + }; + LogController.Instance.AddLog(log); + } + private static string CheckVersion(HttpApplication app) { HttpServerUtility Server = app.Server; @@ -250,55 +299,6 @@ private static bool IsUpgradeOrInstallRequest(HttpRequest request) || url.Contains("/installwizard.aspx"); } - /// ----------------------------------------------------------------------------- - /// - /// Inits the app. - /// - /// The app. - /// ----------------------------------------------------------------------------- - public static void Init(HttpApplication app) - { - string redirect; - - // Check if app is initialised - if (InitializedAlready && Globals.Status == Globals.UpgradeStatus.None) - { - return; - } - - lock (InitializeLock) - { - // Double-Check if app was initialised by another request - if (InitializedAlready && Globals.Status == Globals.UpgradeStatus.None) - { - return; - } - - // Initialize ... - redirect = InitializeApp(app, ref InitializedAlready); - } - - if (!string.IsNullOrEmpty(redirect)) - { - app.Response.Redirect(redirect, true); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// LogStart logs the Application Start Event. - /// - /// ----------------------------------------------------------------------------- - public static void LogStart() - { - var log = new LogInfo - { - BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.APPLICATION_START.ToString(), - }; - LogController.Instance.AddLog(log); - } - /// ----------------------------------------------------------------------------- /// /// LogEnd logs the Application Start Event. diff --git a/DNN Platform/Library/Common/Internal/GlobalsImpl.cs b/DNN Platform/Library/Common/Internal/GlobalsImpl.cs index fc2023dd96c..e2478453b3a 100644 --- a/DNN Platform/Library/Common/Internal/GlobalsImpl.cs +++ b/DNN Platform/Library/Common/Internal/GlobalsImpl.cs @@ -17,8 +17,6 @@ namespace DotNetNuke.Common.Internal public class GlobalsImpl : IGlobals { - protected INavigationManager NavigationManager { get; } - public GlobalsImpl() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); @@ -33,6 +31,8 @@ public string HostMapPath { get { return Globals.HostMapPath; } } + + protected INavigationManager NavigationManager { get; } public string GetSubFolderPath(string strFileNamePath, int portalId) { diff --git a/DNN Platform/Library/Common/Lists/CachedCountryList.cs b/DNN Platform/Library/Common/Lists/CachedCountryList.cs index 6e0996032de..bbfc1a91e4b 100644 --- a/DNN Platform/Library/Common/Lists/CachedCountryList.cs +++ b/DNN Platform/Library/Common/Lists/CachedCountryList.cs @@ -14,16 +14,6 @@ namespace DotNetNuke.Common.Lists [Serializable] public class CachedCountryList : Dictionary { - [Serializable] - public struct Country - { - public int Id; - public string Name; - public string Code; - public string FullName; - public string NormalizedFullName; - } - public CachedCountryList(string locale) : base() { @@ -67,5 +57,15 @@ public static string CacheKey(string locale) { return string.Format("CountryList:{0}", locale); } + + [Serializable] + public struct Country + { + public int Id; + public string Name; + public string Code; + public string FullName; + public string NormalizedFullName; + } } } diff --git a/DNN Platform/Library/Common/Lists/ListController.cs b/DNN Platform/Library/Common/Lists/ListController.cs index 9184582204e..c048a43ea9d 100644 --- a/DNN Platform/Library/Common/Lists/ListController.cs +++ b/DNN Platform/Library/Common/Lists/ListController.cs @@ -23,6 +23,55 @@ public class ListController { public readonly string[] NonLocalizedLists = { "ContentTypes", "Processor", "DataType", "ProfanityFilter", "BannedPasswords" }; + /// + /// Adds a new list entry to the database. If the current thread locale is not "en-US" then the text value will also be + /// persisted to a resource file under App_GlobalResources using the list's name and the value as key. + /// + /// The list entry. + /// + public int AddListEntry(ListEntryInfo listEntry) + { + bool enableSortOrder = listEntry.SortOrder > 0; + this.ClearListCache(listEntry.PortalID); + int entryId = DataProvider.Instance().AddListEntry( + listEntry.ListName, + listEntry.Value, + listEntry.TextNonLocalized, + listEntry.ParentID, + listEntry.Level, + enableSortOrder, + listEntry.DefinitionID, + listEntry.Description, + listEntry.PortalID, + listEntry.SystemList, + UserController.Instance.GetCurrentUserInfo().UserID); + + if (entryId != Null.NullInteger) + { + EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LISTENTRY_CREATED); + } + + if (Thread.CurrentThread.CurrentCulture.Name != Localization.SystemLocale && !this.NonLocalizedLists.Contains(listEntry.ListName)) + { + if (string.IsNullOrEmpty(listEntry.ParentKey)) + { + LocalizationProvider.Instance.SaveString(listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); + } + else + { + LocalizationProvider.Instance.SaveString(listEntry.ParentKey + "." + listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); + } + } + + this.ClearEntriesCache(listEntry.ListName, listEntry.PortalID); + return entryId; + } + + public void DeleteList(string listName, string parentKey) + { + this.DeleteList(listName, parentKey, Null.NullInteger); + } + private void ClearListCache(int portalId) { DataCache.ClearListsCache(portalId); @@ -118,55 +167,6 @@ private IEnumerable GetListEntries(string listName, int portalId) DataCache.ListsCachePriority), c => CBO.FillCollection(DataProvider.Instance().GetListEntriesByListName(listName, string.Empty, portalId))); } - - /// - /// Adds a new list entry to the database. If the current thread locale is not "en-US" then the text value will also be - /// persisted to a resource file under App_GlobalResources using the list's name and the value as key. - /// - /// The list entry. - /// - public int AddListEntry(ListEntryInfo listEntry) - { - bool enableSortOrder = listEntry.SortOrder > 0; - this.ClearListCache(listEntry.PortalID); - int entryId = DataProvider.Instance().AddListEntry( - listEntry.ListName, - listEntry.Value, - listEntry.TextNonLocalized, - listEntry.ParentID, - listEntry.Level, - enableSortOrder, - listEntry.DefinitionID, - listEntry.Description, - listEntry.PortalID, - listEntry.SystemList, - UserController.Instance.GetCurrentUserInfo().UserID); - - if (entryId != Null.NullInteger) - { - EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LISTENTRY_CREATED); - } - - if (Thread.CurrentThread.CurrentCulture.Name != Localization.SystemLocale && !this.NonLocalizedLists.Contains(listEntry.ListName)) - { - if (string.IsNullOrEmpty(listEntry.ParentKey)) - { - LocalizationProvider.Instance.SaveString(listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); - } - else - { - LocalizationProvider.Instance.SaveString(listEntry.ParentKey + "." + listEntry.Value + ".Text", listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); - } - } - - this.ClearEntriesCache(listEntry.ListName, listEntry.PortalID); - return entryId; - } - - public void DeleteList(string listName, string parentKey) - { - this.DeleteList(listName, parentKey, Null.NullInteger); - } public void DeleteList(string listName, string parentKey, int portalId) { @@ -270,14 +270,6 @@ public Dictionary GetListEntryInfoDictionary(string listN return ListEntryInfoItemsToDictionary(this.GetListEntryInfoItems(listName, parentKey, portalId)); } - private static Dictionary ListEntryInfoItemsToDictionary(IEnumerable items) - { - var dict = new Dictionary(); - items.ToList().ForEach(x => dict.Add(x.Key, x)); - - return dict; - } - public ListInfo GetListInfo(string listName) { return this.GetListInfo(listName, string.Empty); @@ -288,6 +280,14 @@ public ListInfo GetListInfo(string listName, string parentKey) return this.GetListInfo(listName, parentKey, -1); } + private static Dictionary ListEntryInfoItemsToDictionary(IEnumerable items) + { + var dict = new Dictionary(); + items.ToList().ForEach(x => dict.Add(x.Key, x)); + + return dict; + } + public ListInfo GetListInfo(string listName, string parentKey, int portalId) { ListInfo list = null; diff --git a/DNN Platform/Library/Common/Lists/ListEntryCollection.cs b/DNN Platform/Library/Common/Lists/ListEntryCollection.cs index a1b7c4237f1..fd4daa01bd2 100644 --- a/DNN Platform/Library/Common/Lists/ListEntryCollection.cs +++ b/DNN Platform/Library/Common/Lists/ListEntryCollection.cs @@ -57,12 +57,6 @@ public ListEntryInfo GetChildren(string parentName) return this.Item(parentName); } - internal new void Clear() - { - this._keyIndexLookup.Clear(); - base.Clear(); - } - public void Add(string key, ListEntryInfo value) { int index; @@ -76,5 +70,11 @@ public void Add(string key, ListEntryInfo value) Logger.Error(exc); } } + + internal new void Clear() + { + this._keyIndexLookup.Clear(); + base.Clear(); + } } } diff --git a/DNN Platform/Library/Common/Lists/ListEntryInfo.cs b/DNN Platform/Library/Common/Lists/ListEntryInfo.cs index c63f6e9cfeb..783151feb1a 100644 --- a/DNN Platform/Library/Common/Lists/ListEntryInfo.cs +++ b/DNN Platform/Library/Common/Lists/ListEntryInfo.cs @@ -12,6 +12,8 @@ namespace DotNetNuke.Common.Lists [Serializable] public class ListEntryInfo { + private string _Text = Null.NullString; + public ListEntryInfo() { this.ParentKey = Null.NullString; @@ -51,8 +53,6 @@ public string DisplayName } public string Value { get; set; } - - private string _Text = Null.NullString; /// /// Gets or sets localized text value of the list entry item. An attempt is made to look up the key "[ParentKey].[Value].Text" in the resource file diff --git a/DNN Platform/Library/Common/Lists/ListInfoCollection.cs b/DNN Platform/Library/Common/Lists/ListInfoCollection.cs index 26f40207310..cd3108ca966 100644 --- a/DNN Platform/Library/Common/Lists/ListInfoCollection.cs +++ b/DNN Platform/Library/Common/Lists/ListInfoCollection.cs @@ -19,12 +19,6 @@ public ListInfo GetChildren(string ParentName) return (ListInfo)this.Item(ParentName); } - internal new void Clear() - { - this.mKeyIndexLookup.Clear(); - base.Clear(); - } - public void Add(string key, object value) { int index; @@ -56,6 +50,12 @@ public object Item(int index) } } + internal new void Clear() + { + this.mKeyIndexLookup.Clear(); + base.Clear(); + } + public object Item(string key) { int index; diff --git a/DNN Platform/Library/Common/SerializableKeyValuePair.cs b/DNN Platform/Library/Common/SerializableKeyValuePair.cs index 13c7ef0c513..754be62587c 100644 --- a/DNN Platform/Library/Common/SerializableKeyValuePair.cs +++ b/DNN Platform/Library/Common/SerializableKeyValuePair.cs @@ -12,17 +12,17 @@ namespace DotNetNuke.Common [DataContract] public class SerializableKeyValuePair { - [DataMember(Name = "key")] - public TKey Key { get; set; } - - [DataMember(Name = "value")] - public TValue Value { get; set; } - public SerializableKeyValuePair(TKey key, TValue value) { this.Key = key; this.Value = value; } + + [DataMember(Name = "key")] + public TKey Key { get; set; } + + [DataMember(Name = "value")] + public TValue Value { get; set; } public override string ToString() { diff --git a/DNN Platform/Library/Common/Utilities/CBO.cs b/DNN Platform/Library/Common/Utilities/CBO.cs index 0329c7dea75..94f93369189 100644 --- a/DNN Platform/Library/Common/Utilities/CBO.cs +++ b/DNN Platform/Library/Common/Utilities/CBO.cs @@ -32,6 +32,94 @@ public partial class CBO : ServiceLocator, ICBO private const string objectMapCacheKey = "ObjectMap_"; + /// ----------------------------------------------------------------------------- + /// + /// CloneObject clones an object. + /// + /// The Object to Clone. + /// + /// ----------------------------------------------------------------------------- + public static object CloneObject(object objObject) + { + try + { + Type objType = objObject.GetType(); + object objNewObject = Activator.CreateInstance(objType); + + // get cached object mapping for type + ObjectMappingInfo objMappingInfo = GetObjectMapping(objType); + foreach (KeyValuePair kvp in objMappingInfo.Properties) + { + PropertyInfo objProperty = kvp.Value; + if (objProperty.CanWrite) + { + // Check if property is ICloneable + var objPropertyClone = objProperty.GetValue(objObject, null) as ICloneable; + if (objPropertyClone == null) + { + objProperty.SetValue(objNewObject, objProperty.GetValue(objObject, null), null); + } + else + { + objProperty.SetValue(objNewObject, objPropertyClone.Clone(), null); + } + + // Check if Property is IEnumerable + var enumerable = objProperty.GetValue(objObject, null) as IEnumerable; + if (enumerable != null) + { + var list = objProperty.GetValue(objNewObject, null) as IList; + if (list != null) + { + foreach (object obj in enumerable) + { + list.Add(CloneObject(obj)); + } + } + + var dic = objProperty.GetValue(objNewObject, null) as IDictionary; + if (dic != null) + { + foreach (DictionaryEntry de in enumerable) + { + dic.Add(de.Key, CloneObject(de.Value)); + } + } + } + } + } + + return objNewObject; + } + catch (Exception exc) + { + Exceptions.LogException(exc); + return null; + } + } + + public static void CloseDataReader(IDataReader dr, bool closeReader) + { + // close datareader + if (dr != null && closeReader) + { + using (dr) + { + dr.Close(); + } + } + } + + List ICBO.FillCollection(IDataReader dr) + { + return (List)FillListFromReader(dr, new List(), true); + } + + TObject ICBO.FillObject(IDataReader dr) + { + return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); + } + protected override Func GetFactory() { return () => new CBO(); @@ -343,32 +431,32 @@ private static void HydrateObject(object hydratedObject, IDataReader dr) } } - private static object ChangeType(object obj, Type type) - { - Type u = Nullable.GetUnderlyingType(type); - - if (u != null) - { - if (obj == null) - { - return GetDefault(type); - } - - return Convert.ChangeType(obj, u); - } + private static object ChangeType(object obj, Type type) + { + Type u = Nullable.GetUnderlyingType(type); - return Convert.ChangeType(obj, type); - } - - private static object GetDefault(Type type) - { - if (type.IsValueType) - { - return Activator.CreateInstance(type); - } + if (u != null) + { + if (obj == null) + { + return GetDefault(type); + } + + return Convert.ChangeType(obj, u); + } + + return Convert.ChangeType(obj, type); + } - return null; - } + private static object GetDefault(Type type) + { + if (type.IsValueType) + { + return Activator.CreateInstance(type); + } + + return null; + } private static string GetColumnName(PropertyInfo objProperty) { @@ -434,100 +522,12 @@ private static string GetTableName(Type objType) return tableName; } - - List ICBO.FillCollection(IDataReader dr) - { - return (List)FillListFromReader(dr, new List(), true); - } - - TObject ICBO.FillObject(IDataReader dr) - { - return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); - } TObject ICBO.GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary) { return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired, saveInDictionary); } - /// ----------------------------------------------------------------------------- - /// - /// CloneObject clones an object. - /// - /// The Object to Clone. - /// - /// ----------------------------------------------------------------------------- - public static object CloneObject(object objObject) - { - try - { - Type objType = objObject.GetType(); - object objNewObject = Activator.CreateInstance(objType); - - // get cached object mapping for type - ObjectMappingInfo objMappingInfo = GetObjectMapping(objType); - foreach (KeyValuePair kvp in objMappingInfo.Properties) - { - PropertyInfo objProperty = kvp.Value; - if (objProperty.CanWrite) - { - // Check if property is ICloneable - var objPropertyClone = objProperty.GetValue(objObject, null) as ICloneable; - if (objPropertyClone == null) - { - objProperty.SetValue(objNewObject, objProperty.GetValue(objObject, null), null); - } - else - { - objProperty.SetValue(objNewObject, objPropertyClone.Clone(), null); - } - - // Check if Property is IEnumerable - var enumerable = objProperty.GetValue(objObject, null) as IEnumerable; - if (enumerable != null) - { - var list = objProperty.GetValue(objNewObject, null) as IList; - if (list != null) - { - foreach (object obj in enumerable) - { - list.Add(CloneObject(obj)); - } - } - - var dic = objProperty.GetValue(objNewObject, null) as IDictionary; - if (dic != null) - { - foreach (DictionaryEntry de in enumerable) - { - dic.Add(de.Key, CloneObject(de.Value)); - } - } - } - } - } - - return objNewObject; - } - catch (Exception exc) - { - Exceptions.LogException(exc); - return null; - } - } - - public static void CloseDataReader(IDataReader dr, bool closeReader) - { - // close datareader - if (dr != null && closeReader) - { - using (dr) - { - dr.Close(); - } - } - } - /// ----------------------------------------------------------------------------- /// /// CreateObject creates a new object of Type TObject. @@ -875,8 +875,8 @@ public static void SerializeSettings(IDictionary dictionary, XmlDocument documen nodeSettingName.InnerText = sKey.ToString(); nodeSettingValue = nodeSetting.AppendChild(document.CreateElement("settingvalue")); - nodeSettingValue.InnerText = dictionary[sKey].ToString(); - } + nodeSettingValue.InnerText = dictionary[sKey].ToString(); + } } else { diff --git a/DNN Platform/Library/Common/Utilities/Config.cs b/DNN Platform/Library/Common/Utilities/Config.cs index 58dde8c1a3e..26235644079 100644 --- a/DNN Platform/Library/Common/Utilities/Config.cs +++ b/DNN Platform/Library/Common/Utilities/Config.cs @@ -327,11 +327,6 @@ public static void SetMaxUploadSize(long newSize) Save(configNav); } - private static bool Iis7AndAbove() - { - return Environment.OSVersion.Version.Major >= 6; - } - /// ----------------------------------------------------------------------------- /// /// Gets the specified upgrade connection string. @@ -362,6 +357,11 @@ public static string GetDataBaseOwner() return databaseOwner; } + private static bool Iis7AndAbove() + { + return Environment.OSVersion.Version.Major >= 6; + } + public static Provider GetDefaultProvider(string type) { ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration(type); @@ -829,17 +829,6 @@ public static string GetPathToFile(ConfigFileType file, bool overwrite) return path; } - private static string EnumToFileName(ConfigFileType file) - { - switch (file) - { - case ConfigFileType.SolutionsExplorer: - return "SolutionsExplorer.opml.config"; - default: - return file + ".config"; - } - } - /// /// UpdateInstallVersion, but only if the setting does not already exist. /// @@ -881,14 +870,6 @@ public static string UpdateInstallVersion(Version version) return strError; } - private static XmlDocument UpdateInstallVersion(XmlDocument xmlConfig, Version version) - { - // only update appsetting if necessary - xmlConfig = AddAppSetting(xmlConfig, "InstallVersion", Globals.FormatVersion(version), false); - - return xmlConfig; - } - public static bool IsNet45OrNewer() { // Class "ReflectionContext" exists from .NET 4.5 onwards. @@ -921,5 +902,24 @@ public static string AddFCNMode(FcnMode fcnMode) return string.Empty; } + + private static string EnumToFileName(ConfigFileType file) + { + switch (file) + { + case ConfigFileType.SolutionsExplorer: + return "SolutionsExplorer.opml.config"; + default: + return file + ".config"; + } + } + + private static XmlDocument UpdateInstallVersion(XmlDocument xmlConfig, Version version) + { + // only update appsetting if necessary + xmlConfig = AddAppSetting(xmlConfig, "InstallVersion", Globals.FormatVersion(version), false); + + return xmlConfig; + } } } diff --git a/DNN Platform/Library/Common/Utilities/DataCache.cs b/DNN Platform/Library/Common/Utilities/DataCache.cs index 369893a8164..c0ce514ecd0 100644 --- a/DNN Platform/Library/Common/Utilities/DataCache.cs +++ b/DNN Platform/Library/Common/Utilities/DataCache.cs @@ -38,11 +38,11 @@ public enum CoreCacheType /// ----------------------------------------------------------------------------- public class DataCache { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DataCache)); - // Host keys public const string SecureHostSettingsCacheKey = "SecureHostSettings"; public const string UnSecureHostSettingsCacheKey = "UnsecureHostSettings"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DataCache)); public const string HostSettingsCacheKey = "HostSettings"; public const CacheItemPriority HostSettingsCachePriority = CacheItemPriority.NotRemovable; public const int HostSettingsCacheTimeOut = 20; @@ -301,10 +301,10 @@ public class DataCache public const CacheItemPriority WorkflowsCachePriority = CacheItemPriority.Low; public const int WorkflowsCacheTimeout = 2; - private static string _CachePersistenceEnabled = string.Empty; - public const string ScopeTypesCacheKey = "ScopeTypes"; public const string VocabularyCacheKey = "Vocabularies"; + + private static string _CachePersistenceEnabled = string.Empty; public const string TermCacheKey = "Terms_{0}"; internal const string UserIdListToClearDiskImageCacheKey = "UserIdListToClearDiskImage_{0}"; @@ -314,6 +314,8 @@ public class DataCache private static readonly SharedDictionary dictionaryCache = new SharedDictionary(); + private static readonly TimeSpan _5seconds = new TimeSpan(0, 0, 5); + public static bool CachePersistenceEnabled { get @@ -327,14 +329,23 @@ public static bool CachePersistenceEnabled } } - private static string GetDnnCacheKey(string CacheKey) + public static void ClearCache() { - return CachingProvider.GetCacheKey(CacheKey); + CachingProvider.Instance().Clear("Prefix", "DNN_"); + using (dictionaryCache.GetWriteLock()) + { + dictionaryCache.Clear(); + } + + // log the cache clear event + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.CACHE_REFRESH.ToString() }; + log.LogProperties.Add(new LogDetailInfo("*", "Refresh")); + LogController.Instance.AddLog(log); } - private static string CleanCacheKey(string cacheKey) + public static void ClearCache(string cachePrefix) { - return CachingProvider.CleanCacheKey(cacheKey); + CachingProvider.Instance().Clear("Prefix", GetDnnCacheKey(cachePrefix)); } internal static void ItemRemovedCallback(string key, object value, CacheItemRemovedReason removedReason) @@ -372,23 +383,14 @@ internal static void ItemRemovedCallback(string key, object value, CacheItemRemo } } - public static void ClearCache() + private static string GetDnnCacheKey(string CacheKey) { - CachingProvider.Instance().Clear("Prefix", "DNN_"); - using (dictionaryCache.GetWriteLock()) - { - dictionaryCache.Clear(); - } - - // log the cache clear event - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.CACHE_REFRESH.ToString() }; - log.LogProperties.Add(new LogDetailInfo("*", "Refresh")); - LogController.Instance.AddLog(log); + return CachingProvider.GetCacheKey(CacheKey); } - public static void ClearCache(string cachePrefix) + private static string CleanCacheKey(string cacheKey) { - CachingProvider.Instance().Clear("Prefix", GetDnnCacheKey(cachePrefix)); + return CachingProvider.CleanCacheKey(cacheKey); } public static void ClearFolderCache(int PortalId) @@ -498,6 +500,43 @@ public static void ClearPackagesCache(int portalId) RemoveCache(string.Format(PackagesCacheKey, portalId)); } + public static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) + { + // declare local object and try and retrieve item from the cache + return GetCachedData(cacheItemArgs, cacheItemExpired, false); + } + + public static TObject GetCache(string CacheKey) + { + object objObject = GetCache(CacheKey); + if (objObject == null) + { + return default(TObject); + } + + return (TObject)objObject; + } + + public static object GetCache(string CacheKey) + { + return CachingProvider.Instance().GetItem(GetDnnCacheKey(CacheKey)); + } + + internal static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool storeInDictionary) + { + object objObject = storeInDictionary + ? GetCachedDataFromDictionary(cacheItemArgs, cacheItemExpired) + : GetCachedDataFromRuntimeCache(cacheItemArgs, cacheItemExpired); + + // return the object + if (objObject == null) + { + return default(TObject); + } + + return (TObject)objObject; + } + private static object GetCachedDataFromRuntimeCache(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) { object objObject = GetCache(cacheItemArgs.CacheKey); @@ -601,29 +640,6 @@ private static object GetCachedDataFromDictionary(CacheItemArgs cacheItemArgs, C return cachedObject; } - public static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) - { - // declare local object and try and retrieve item from the cache - return GetCachedData(cacheItemArgs, cacheItemExpired, false); - } - - internal static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool storeInDictionary) - { - object objObject = storeInDictionary - ? GetCachedDataFromDictionary(cacheItemArgs, cacheItemExpired) - : GetCachedDataFromRuntimeCache(cacheItemArgs, cacheItemExpired); - - // return the object - if (objObject == null) - { - return default(TObject); - } - - return (TObject)objObject; - } - - private static readonly TimeSpan _5seconds = new TimeSpan(0, 0, 5); - private static object GetUniqueLockObject(string key) { object @lock = null; @@ -691,22 +707,6 @@ private static void RemoveUniqueLockObject(string key) } } - public static TObject GetCache(string CacheKey) - { - object objObject = GetCache(CacheKey); - if (objObject == null) - { - return default(TObject); - } - - return (TObject)objObject; - } - - public static object GetCache(string CacheKey) - { - return CachingProvider.Instance().GetItem(GetDnnCacheKey(CacheKey)); - } - public static void RemoveCache(string CacheKey) { CachingProvider.Instance().Remove(GetDnnCacheKey(CacheKey)); diff --git a/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs b/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs index 3e0ef656a3b..8f9a8f273c5 100644 --- a/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs +++ b/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs @@ -23,6 +23,18 @@ public FileExtensionWhitelist(string extensionList) this._extensions = EscapedString.Seperate(extensionList.ToLowerInvariant()).Select(item => "." + item).ToList(); } + /// + /// Gets the list of extensions in the whitelist. + /// + /// All extensions are lowercase and prefixed with a '.'. + public IEnumerable AllowedExtensions + { + get + { + return this._extensions; + } + } + /// /// Returns a string suitale for display to an end user. /// @@ -44,18 +56,6 @@ public string ToDisplayString(IEnumerable additionalExtensions) return "*" + string.Join(", *", allExtensions.ToArray()); } - /// - /// Gets the list of extensions in the whitelist. - /// - /// All extensions are lowercase and prefixed with a '.'. - public IEnumerable AllowedExtensions - { - get - { - return this._extensions; - } - } - /// /// Indicates if the file extension is permitted by the Host Whitelist. /// @@ -119,6 +119,12 @@ public string ToStorageString(IEnumerable additionalExtensions) return EscapedString.Combine(leadingDotRemoved); } + public FileExtensionWhitelist RestrictBy(FileExtensionWhitelist parentList) + { + var filter = parentList._extensions; + return new FileExtensionWhitelist(string.Join(",", this._extensions.Where(x => filter.Contains(x)).Select(s => s.Substring(1)))); + } + private IEnumerable CombineLists(IEnumerable additionalExtensions) { if (additionalExtensions == null) @@ -141,11 +147,5 @@ private IEnumerable NormalizeExtensions(IEnumerable additionalEx { return additionalExtensions.Select(ext => (ext.StartsWith(".") ? ext : "." + ext).ToLowerInvariant()); } - - public FileExtensionWhitelist RestrictBy(FileExtensionWhitelist parentList) - { - var filter = parentList._extensions; - return new FileExtensionWhitelist(string.Join(",", this._extensions.Where(x => filter.Contains(x)).Select(s => s.Substring(1)))); - } } } diff --git a/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs b/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs index 0054e28f922..c87526d905d 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs @@ -22,6 +22,17 @@ public class FileSystemPermissionVerifier private int _retryTimes = 30; + public FileSystemPermissionVerifier(string basePath) + { + this._basePath = basePath; + } + + public FileSystemPermissionVerifier(string basePath, int retryTimes) + : this(basePath) + { + this._retryTimes = retryTimes; + } + /// /// Gets base path need to verify permission. /// @@ -33,15 +44,39 @@ public string BasePath } } - public FileSystemPermissionVerifier(string basePath) + public bool VerifyAll() { - this._basePath = basePath; + lock (typeof(FileSystemPermissionVerifier)) + { + // All these steps must be executed in this sequence as one unit + return this.VerifyFolderCreate() && + this.VerifyFileCreate() && + this.VerifyFileDelete() && + this.VerifyFolderDelete(); + } } - public FileSystemPermissionVerifier(string basePath, int retryTimes) - : this(basePath) + private static void FileCreateAction(string verifyPath) { - this._retryTimes = retryTimes; + if (File.Exists(verifyPath)) + { + File.Delete(verifyPath); + } + + using (File.Create(verifyPath)) + { + // do nothing just let it close + } + } + + private static void FolderCreateAction(string verifyPath) + { + if (Directory.Exists(verifyPath)) + { + Directory.Delete(verifyPath, true); + } + + Directory.CreateDirectory(verifyPath); } /// ----------------------------------------------------------------------------- @@ -68,19 +103,6 @@ private bool VerifyFileCreate() return verified; } - private static void FileCreateAction(string verifyPath) - { - if (File.Exists(verifyPath)) - { - File.Delete(verifyPath); - } - - using (File.Create(verifyPath)) - { - // do nothing just let it close - } - } - /// ----------------------------------------------------------------------------- /// /// VerifyFileDelete checks whether a file can be deleted. @@ -129,16 +151,6 @@ private bool VerifyFolderCreate() return verified; } - private static void FolderCreateAction(string verifyPath) - { - if (Directory.Exists(verifyPath)) - { - Directory.Delete(verifyPath, true); - } - - Directory.CreateDirectory(verifyPath); - } - /// ----------------------------------------------------------------------------- /// /// VerifyFolderDelete checks whether a folder can be deleted. @@ -163,18 +175,6 @@ private bool VerifyFolderDelete() return verified; } - public bool VerifyAll() - { - lock (typeof(FileSystemPermissionVerifier)) - { - // All these steps must be executed in this sequence as one unit - return this.VerifyFolderCreate() && - this.VerifyFileCreate() && - this.VerifyFileDelete() && - this.VerifyFolderDelete(); - } - } - private void Try(Action action, string description) { new RetryableAction(action, description, this._retryTimes, TimeSpan.FromSeconds(1)).TryIt(); diff --git a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs index 24fa9529c72..a92dad9ba10 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs @@ -35,6 +35,67 @@ public class FileSystemUtils { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSystemUtils)); + /// ----------------------------------------------------------------------------- + /// + /// Adds a File to a Zip File. + /// + /// ----------------------------------------------------------------------------- + public static 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(); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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); + } + private static string CreateFile(IFolderInfo folder, string fileName, string contentType, Stream fileContent, bool unzip, bool overwrite, bool checkPermissions) { var strMessage = string.Empty; @@ -163,67 +224,6 @@ private static void WriteStream(HttpResponse objResponse, Stream objStream) } } } - - /// ----------------------------------------------------------------------------- - /// - /// Adds a File to a Zip File. - /// - /// ----------------------------------------------------------------------------- - public static 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(); - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// 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); - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs index f9a671b9ba1..66214a1ea8e 100644 --- a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs @@ -25,6 +25,9 @@ namespace DotNetNuke.Common.Utilities /// ----------------------------------------------------------------------------- public class HtmlUtils { + // Create Regular Expression objects + private const string PunctuationMatch = "[~!#\\$%\\^&*\\(\\)-+=\\{\\[\\}\\]\\|;:\\x22'<,>\\.\\?\\\\\\t\\r\\v\\f\\n]"; + private static readonly Regex HtmlDetectionRegex = new Regex("<(.*\\s*)>", RegexOptions.Compiled); private static readonly Regex StripWhiteSpaceRegex = new Regex("\\s+", RegexOptions.Compiled); private static readonly Regex StripNonWordRegex = new Regex("\\W*", RegexOptions.Compiled); @@ -33,9 +36,6 @@ public class HtmlUtils // Match all variants of
tag (
,
,
, including embedded space private static readonly Regex ReplaceHtmlNewLinesRegex = new Regex("\\s*<\\s*[bB][rR]\\s*/\\s*>\\s*", RegexOptions.Compiled); - - // Create Regular Expression objects - private const string PunctuationMatch = "[~!#\\$%\\^&*\\(\\)-+=\\{\\[\\}\\]\\|;:\\x22'<,>\\.\\?\\\\\\t\\r\\v\\f\\n]"; private static readonly Regex AfterRegEx = new Regex(PunctuationMatch + "\\s", RegexOptions.Compiled); private static readonly Regex BeforeRegEx = new Regex("\\s" + PunctuationMatch, RegexOptions.Compiled); private static readonly Regex EntityRegEx = new Regex("&[^;]+;", RegexOptions.Compiled); diff --git a/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs b/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs index b474ce6ba72..d2cf665ac6e 100644 --- a/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs +++ b/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs @@ -21,17 +21,7 @@ internal OrderedDictionary Dictionary } } - public void AddMethodBody(string name, string methodBody) - { - this.AddMethod(name, "function() { " + methodBody + "; }"); - } - - public void AddMethod(string name, string method) - { - this.Dictionary[name] = method; - } - - private static string ToJsonString(IEnumerable> methods) + public static string ToJavaScriptArrayString(IEnumerable> methods) { if (methods == null) { @@ -39,7 +29,7 @@ private static string ToJsonString(IEnumerable> met } var builder = new StringBuilder(); - builder.Append('{'); + builder.Append('['); var isFirstPair = true; foreach (var keyValuePair in methods) { @@ -52,24 +42,15 @@ private static string ToJsonString(IEnumerable> met builder.Append(','); } - builder.Append('"'); - builder.Append(HttpUtility.JavaScriptStringEncode(keyValuePair.Key)); - builder.Append('"'); - builder.Append(':'); var methodValue = string.IsNullOrEmpty(keyValuePair.Value) ? "null" : keyValuePair.Value; builder.Append(methodValue); } - builder.Append('}'); + builder.Append(']'); return builder.ToString(); } - public string ToJsonString() - { - return ToJsonString(this); - } - - public static string ToJavaScriptArrayString(IEnumerable> methods) + public static string ToJavaScriptArrayString(IEnumerable methods) { if (methods == null) { @@ -79,7 +60,7 @@ public static string ToJavaScriptArrayString(IEnumerable methods) + public void AddMethodBody(string name, string methodBody) + { + this.AddMethod(name, "function() { " + methodBody + "; }"); + } + + public void AddMethod(string name, string method) + { + this.Dictionary[name] = method; + } + + public string ToJsonString() + { + return ToJsonString(this); + } + + private static string ToJsonString(IEnumerable> methods) { if (methods == null) { @@ -106,9 +102,9 @@ public static string ToJavaScriptArrayString(IEnumerable methods) } var builder = new StringBuilder(); - builder.Append('['); + builder.Append('{'); var isFirstPair = true; - foreach (var method in methods) + foreach (var keyValuePair in methods) { if (isFirstPair) { @@ -119,11 +115,15 @@ public static string ToJavaScriptArrayString(IEnumerable methods) builder.Append(','); } - var methodValue = string.IsNullOrEmpty(method) ? "null" : method; + builder.Append('"'); + builder.Append(HttpUtility.JavaScriptStringEncode(keyValuePair.Key)); + builder.Append('"'); + builder.Append(':'); + var methodValue = string.IsNullOrEmpty(keyValuePair.Value) ? "null" : keyValuePair.Value; builder.Append(methodValue); } - builder.Append(']'); + builder.Append('}'); return builder.ToString(); } @@ -140,11 +140,6 @@ public IEnumerator> GetEnumerator() yield return new KeyValuePair(enumerator.Key.ToString(), enumerator.Value.ToString()); } } - - private IEnumerator GetEnumeratorPrivate() - { - return this.GetEnumerator(); - } IEnumerator IEnumerable.GetEnumerator() { @@ -155,4 +150,9 @@ public override string ToString() { return this._dictionary == null ? string.Empty : this._dictionary.ToString(); } + + private IEnumerator GetEnumeratorPrivate() + { + return this.GetEnumerator(); + } } diff --git a/DNN Platform/Library/Common/Utilities/JsonExtensions.cs b/DNN Platform/Library/Common/Utilities/JsonExtensions.cs index 970cb2ad8bc..d1467856504 100644 --- a/DNN Platform/Library/Common/Utilities/JsonExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/JsonExtensions.cs @@ -11,12 +11,6 @@ namespace DotNetNuke.Common.Utilities ///
public static class JsonExtensionsWeb { - private static JavaScriptSerializer SerializerFactory() - { - // Allow large JSON strings to be serialized and deserialized. - return new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; - } - /// /// Serializes a type to Json. Note the type must be marked Serializable /// or include a DataContract attribute. @@ -40,6 +34,12 @@ public static string ToJson(this object value) { return ToJsonString(value); } + + private static JavaScriptSerializer SerializerFactory() + { + // Allow large JSON strings to be serialized and deserialized. + return new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; + } /// /// Deserializes a json string into a specific type. diff --git a/DNN Platform/Library/Common/Utilities/NetworkUtils.cs b/DNN Platform/Library/Common/Utilities/NetworkUtils.cs index 16006d90f71..b4fca6b7458 100644 --- a/DNN Platform/Library/Common/Utilities/NetworkUtils.cs +++ b/DNN Platform/Library/Common/Utilities/NetworkUtils.cs @@ -8,6 +8,15 @@ namespace DotNetNuke.Common.Utils using System.Net; using System.Net.Sockets; using System.Web; + + /// + /// Enumration of IP AddressTyes. + /// + public enum AddressType + { + IPv4, + IPv6, + } /// /// Utility functions for network information. @@ -104,16 +113,6 @@ public static string LongToIp(long ip) return addr.TrimEnd('.'); } - /// - /// Masks from cidr. - /// - /// The Classless Inter-Domain Routing (cidr). - /// - private static long MaskFromCidr(int cidr) - { - return Convert.ToInt64(Math.Pow(2, 32 - cidr) - 1) ^ 4294967295L; - } - /// /// Formats as cidr. /// @@ -195,6 +194,16 @@ public static void Network2IpRange(string sNetwork, out uint startIP, out uint e } } + /// + /// Masks from cidr. + /// + /// The Classless Inter-Domain Routing (cidr). + /// + private static long MaskFromCidr(int cidr) + { + return Convert.ToInt64(Math.Pow(2, 32 - cidr) - 1) ^ 4294967295L; + } + /// /// Convert IP to Integer. /// @@ -279,13 +288,4 @@ public static string GetClientIpAddress(HttpRequest request) return ipAddress; } } - - /// - /// Enumration of IP AddressTyes. - /// - public enum AddressType - { - IPv4, - IPv6, - } } diff --git a/DNN Platform/Library/Common/Utilities/PathUtils.cs b/DNN Platform/Library/Common/Utilities/PathUtils.cs index c302d67e96e..f7ae64f0b32 100644 --- a/DNN Platform/Library/Common/Utilities/PathUtils.cs +++ b/DNN Platform/Library/Common/Utilities/PathUtils.cs @@ -145,35 +145,6 @@ public virtual string GetUserFolderPathElement(int userID, UserFolderElement mod return this.GetUserFolderPathElementInternal(userID, mode); } - internal string GetUserFolderPathElementInternal(int userId, UserFolderElement mode) - { - const int subfolderSeedLength = 2; - const int byteOffset = 255; - var element = string.Empty; - - switch (mode) - { - case UserFolderElement.Root: - element = (Convert.ToInt32(userId) & byteOffset).ToString("000"); - break; - case UserFolderElement.SubFolder: - element = userId.ToString("00").Substring(userId.ToString("00").Length - subfolderSeedLength, subfolderSeedLength); - break; - } - - return element; - } - - internal string GetUserFolderPathInternal(UserInfo user) - { - var rootFolder = this.GetUserFolderPathElementInternal(user.UserID, UserFolderElement.Root); - var subFolder = this.GetUserFolderPathElementInternal(user.UserID, UserFolderElement.SubFolder); - - var fullPath = Path.Combine(Path.Combine(rootFolder, subFolder), user.UserID.ToString(CultureInfo.InvariantCulture)); - - return string.Format("Users/{0}/", fullPath.Replace("\\", "/")); - } - /// /// Checks if a folder is a default protected folder. /// @@ -230,6 +201,35 @@ public virtual string MapPath(string path) return convertedPath; } + internal string GetUserFolderPathElementInternal(int userId, UserFolderElement mode) + { + const int subfolderSeedLength = 2; + const int byteOffset = 255; + var element = string.Empty; + + switch (mode) + { + case UserFolderElement.Root: + element = (Convert.ToInt32(userId) & byteOffset).ToString("000"); + break; + case UserFolderElement.SubFolder: + element = userId.ToString("00").Substring(userId.ToString("00").Length - subfolderSeedLength, subfolderSeedLength); + break; + } + + return element; + } + + internal string GetUserFolderPathInternal(UserInfo user) + { + var rootFolder = this.GetUserFolderPathElementInternal(user.UserID, UserFolderElement.Root); + var subFolder = this.GetUserFolderPathElementInternal(user.UserID, UserFolderElement.SubFolder); + + var fullPath = Path.Combine(Path.Combine(rootFolder, subFolder), user.UserID.ToString(CultureInfo.InvariantCulture)); + + return string.Format("Users/{0}/", fullPath.Replace("\\", "/")); + } + /// /// Removes the trailing slash or backslash from the specified source. /// diff --git a/DNN Platform/Library/Common/Utilities/RetryableAction.cs b/DNN Platform/Library/Common/Utilities/RetryableAction.cs index 415dd34de0a..9b233cf7b3b 100644 --- a/DNN Platform/Library/Common/Utilities/RetryableAction.cs +++ b/DNN Platform/Library/Common/Utilities/RetryableAction.cs @@ -16,6 +16,35 @@ namespace DotNetNuke.Common.Utilities.Internal public class RetryableAction { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RetryableAction)); + + static RetryableAction() + { + SleepAction = GoToSleep; + } + + public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay) + : this(action, description, maxRetries, delay, 1) + { + } + + public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay, float delayMultiplier) + { + if (delay.TotalMilliseconds > int.MaxValue) + { + throw new ArgumentException(string.Format("delay must be less than {0} milliseconds", int.MaxValue)); + } + + this.Action = action; + this.Description = description; + this.MaxRetries = maxRetries; + this.Delay = delay; + this.DelayMultiplier = delayMultiplier; + } + + /// + /// Gets or sets method that allows thread to sleep until next retry meant for unit testing purposes. + /// + public static Action SleepAction { get; set; } /// /// Gets or sets the Action to execute. @@ -55,40 +84,6 @@ public static void Retry5TimesWith2SecondsDelay(Action action, string descriptio new RetryableAction(action, description, 5, TimeSpan.FromSeconds(2)).TryIt(); } - /// - /// Gets or sets method that allows thread to sleep until next retry meant for unit testing purposes. - /// - public static Action SleepAction { get; set; } - - static RetryableAction() - { - SleepAction = GoToSleep; - } - - private static void GoToSleep(int delay) - { - Thread.Sleep(delay); - } - - public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay) - : this(action, description, maxRetries, delay, 1) - { - } - - public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay, float delayMultiplier) - { - if (delay.TotalMilliseconds > int.MaxValue) - { - throw new ArgumentException(string.Format("delay must be less than {0} milliseconds", int.MaxValue)); - } - - this.Action = action; - this.Description = description; - this.MaxRetries = maxRetries; - this.Delay = delay; - this.DelayMultiplier = delayMultiplier; - } - public void TryIt() { var currentDelay = (int)this.Delay.TotalMilliseconds; @@ -132,5 +127,10 @@ public void TryIt() } while (true); } + + private static void GoToSleep(int delay) + { + Thread.Sleep(delay); + } } } diff --git a/DNN Platform/Library/Common/Utilities/StateVariable.cs b/DNN Platform/Library/Common/Utilities/StateVariable.cs index 04a749ec16b..8293595fddc 100644 --- a/DNN Platform/Library/Common/Utilities/StateVariable.cs +++ b/DNN Platform/Library/Common/Utilities/StateVariable.cs @@ -51,34 +51,6 @@ protected StateVariable(string key, Func initializer) this._initializer = initializer; } - private object GetInitializedInternalValue() - { - var value = this[this._key]; - if (value == null && this._initializer != null) - { - value = this._initializer(); - this[this._key] = value; - } - - return value; - } - - /// - /// Get/sets the value in associated dictionary/map. - /// - /// Value key. - /// - /// - /// - protected abstract object this[string key] { get; set; } - - /// - /// Removes the value in associated dictionary according. - /// - /// Value key. - /// - protected abstract void Remove(string key); - /// /// Gets a value indicating whether indicates wether there is a value present or not. /// @@ -132,6 +104,34 @@ public T ValueOrDefault } } + /// + /// Get/sets the value in associated dictionary/map. + /// + /// Value key. + /// + /// + /// + protected abstract object this[string key] { get; set; } + + /// + /// Removes the value in associated dictionary according. + /// + /// Value key. + /// + protected abstract void Remove(string key); + + private object GetInitializedInternalValue() + { + var value = this[this._key]; + if (value == null && this._initializer != null) + { + value = this._initializer(); + this[this._key] = value; + } + + return value; + } + /// /// Clears the value in the current items. /// diff --git a/DNN Platform/Library/Common/Utilities/StringExtensions.cs b/DNN Platform/Library/Common/Utilities/StringExtensions.cs index 8bc9aa97321..c6ed72e4040 100644 --- a/DNN Platform/Library/Common/Utilities/StringExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/StringExtensions.cs @@ -9,6 +9,8 @@ namespace DotNetNuke.Common.Utilities public static class StringExtensions { + private static readonly Encoding Iso8859Encoding = Encoding.GetEncoding("iso-8859-8"); + public static string TrimToLength(this string source, int maxLength) { return source == null || source.Length <= maxLength @@ -64,7 +66,5 @@ public static string ReplaceIgnoreCase(this string source, string oldValue, stri return Regex.Replace(source, Regex.Escape(oldValue), newValue, RegexOptions.IgnoreCase); } - - private static readonly Encoding Iso8859Encoding = Encoding.GetEncoding("iso-8859-8"); } } diff --git a/DNN Platform/Library/Common/Utilities/UrlUtils.cs b/DNN Platform/Library/Common/Utilities/UrlUtils.cs index aa3c0a12cc8..16f3e6f17f9 100644 --- a/DNN Platform/Library/Common/Utilities/UrlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/UrlUtils.cs @@ -188,8 +188,8 @@ public static bool IsSslOffloadEnabled(HttpRequest request) string ssloffload = request.Headers[ssloffloadheader]; if (!string.IsNullOrEmpty(ssloffload) && (string.IsNullOrWhiteSpace(ssloffloadValue) || ssloffloadValue == ssloffload)) - { - return true; + { + return true; } } diff --git a/DNN Platform/Library/Common/Utilities/XmlUtils.cs b/DNN Platform/Library/Common/Utilities/XmlUtils.cs index 21682c2d5f8..5836ed3247e 100644 --- a/DNN Platform/Library/Common/Utilities/XmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/XmlUtils.cs @@ -594,15 +594,15 @@ public static float GetNodeValueSingle(XPathNavigator navigator, string path, fl } return Convert.ToSingle(strValue, CultureInfo.InvariantCulture); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets an XmlWriterSettings object. /// /// Conformance Level. /// An XmlWriterSettings. - /// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- public static XmlWriterSettings GetXmlWriterSettings(ConformanceLevel conformance) { var settings = new XmlWriterSettings(); diff --git a/DNN Platform/Library/Common/XmlValidatorBase.cs b/DNN Platform/Library/Common/XmlValidatorBase.cs index 194a0897eff..59240292440 100644 --- a/DNN Platform/Library/Common/XmlValidatorBase.cs +++ b/DNN Platform/Library/Common/XmlValidatorBase.cs @@ -53,16 +53,6 @@ public XmlSchemaSet SchemaSet } } - /// - /// Validations the call back. - /// - /// The sender. - /// The instance containing the event data. - protected void ValidationCallBack(object sender, ValidationEventArgs args) - { - this._errs.Add(args.Message); - } - /// /// Determines whether this instance is valid. /// @@ -110,6 +100,16 @@ public virtual bool Validate(Stream xmlStream) return this.IsValid(); } + /// + /// Validations the call back. + /// + /// The sender. + /// The instance containing the event data. + protected void ValidationCallBack(object sender, ValidationEventArgs args) + { + this._errs.Add(args.Message); + } + /// /// Validates the specified filename. /// diff --git a/DNN Platform/Library/ComponentModel/ComponentBase.cs b/DNN Platform/Library/ComponentModel/ComponentBase.cs index b96d216a8dc..9f94b556c4b 100644 --- a/DNN Platform/Library/ComponentModel/ComponentBase.cs +++ b/DNN Platform/Library/ComponentModel/ComponentBase.cs @@ -32,6 +32,14 @@ public static TContract Instance } } + public static void RegisterInstance(TContract instance) + { + if (ComponentFactory.GetComponent() == null) + { + ComponentFactory.RegisterComponentInstance(instance); + } + } + /// /// Registers an instance to use for the Singleton. /// @@ -52,13 +60,5 @@ internal static void ClearInstance() _useTestable = false; _testableInstance = default(TContract); } - - public static void RegisterInstance(TContract instance) - { - if (ComponentFactory.GetComponent() == null) - { - ComponentFactory.RegisterComponentInstance(instance); - } - } } } diff --git a/DNN Platform/Library/ComponentModel/ComponentFactory.cs b/DNN Platform/Library/ComponentModel/ComponentFactory.cs index 0899667f4ec..a4c54fe992f 100644 --- a/DNN Platform/Library/ComponentModel/ComponentFactory.cs +++ b/DNN Platform/Library/ComponentModel/ComponentFactory.cs @@ -30,14 +30,6 @@ public static void InstallComponents(params IComponentInstaller[] installers) } } - private static void VerifyContainer() - { - if (Container == null) - { - Container = new SimpleContainer(); - } - } - public static object GetComponent(string name) { VerifyContainer(); @@ -50,6 +42,14 @@ public static TContract GetComponent() return Container.GetComponent(); } + private static void VerifyContainer() + { + if (Container == null) + { + Container = new SimpleContainer(); + } + } + public static object GetComponent(Type contractType) { VerifyContainer(); diff --git a/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs b/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs index 339c766919a..d913a4a446c 100644 --- a/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs @@ -19,11 +19,6 @@ public InstanceComponentBuilder(string name, object instance) this._Name = name; this._Instance = instance; } - - public object BuildComponent() - { - return this._Instance; - } public string Name { @@ -32,5 +27,10 @@ public string Name return this._Name; } } + + public object BuildComponent() + { + return this._Instance; + } } } diff --git a/DNN Platform/Library/ComponentModel/ProviderInstaller.cs b/DNN Platform/Library/ComponentModel/ProviderInstaller.cs index eb543c8cd1f..adc1d5abc12 100644 --- a/DNN Platform/Library/ComponentModel/ProviderInstaller.cs +++ b/DNN Platform/Library/ComponentModel/ProviderInstaller.cs @@ -72,8 +72,8 @@ private void InstallProvider(IContainer container, Provider provider) // Get the provider type try { - type = BuildManager.GetType(provider.Type, false, true); - } + type = BuildManager.GetType(provider.Type, false, true); + } catch (TypeLoadException) { if (this._defaultProvider != null) diff --git a/DNN Platform/Library/ComponentModel/SimpleContainer.cs b/DNN Platform/Library/ComponentModel/SimpleContainer.cs index 73fa4fdb875..60b72ec9809 100644 --- a/DNN Platform/Library/ComponentModel/SimpleContainer.cs +++ b/DNN Platform/Library/ComponentModel/SimpleContainer.cs @@ -37,6 +37,29 @@ public SimpleContainer(string name) this._name = name; } + public override string Name + { + get + { + return this._name; + } + } + + public override void RegisterComponent(string name, Type type) + { + using (this._registeredComponents.GetWriteLock()) + { + this._registeredComponents[type] = name; + } + } + + public override object GetComponent(string name) + { + IComponentBuilder builder = this.GetComponentBuilder(name); + + return this.GetComponent(builder); + } + private void AddBuilder(Type contractType, IComponentBuilder builder) { ComponentType componentType = this.GetComponentType(contractType); @@ -122,29 +145,6 @@ private ComponentType GetComponentType(Type contractType) return componentType; } - public override void RegisterComponent(string name, Type type) - { - using (this._registeredComponents.GetWriteLock()) - { - this._registeredComponents[type] = name; - } - } - - public override string Name - { - get - { - return this._name; - } - } - - public override object GetComponent(string name) - { - IComponentBuilder builder = this.GetComponentBuilder(name); - - return this.GetComponent(builder); - } - public override object GetComponent(Type contractType) { ComponentType componentType = this.GetComponentType(contractType); diff --git a/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs b/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs index a0f53a1b712..64eb7b592c6 100644 --- a/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs @@ -23,6 +23,14 @@ public SingletonComponentBuilder(string name, Type type) this._Name = name; this._Type = type; } + + public string Name + { + get + { + return this._Name; + } + } public object BuildComponent() { @@ -33,14 +41,6 @@ public object BuildComponent() return this._Instance; } - - public string Name - { - get - { - return this._Name; - } - } private void CreateInstance() { diff --git a/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs b/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs index f8d53e221f5..e58f9b229d4 100644 --- a/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs @@ -22,11 +22,6 @@ public TransientComponentBuilder(string name, Type type) this._Name = name; this._Type = type; } - - public object BuildComponent() - { - return Reflection.CreateObject(this._Type); - } public string Name { @@ -35,5 +30,10 @@ public string Name return this._Name; } } + + public object BuildComponent() + { + return Reflection.CreateObject(this._Type); + } } } diff --git a/DNN Platform/Library/Data/DataProvider.cs b/DNN Platform/Library/Data/DataProvider.cs index b5ea09d28d8..6c1dfbe5b1d 100644 --- a/DNN Platform/Library/Data/DataProvider.cs +++ b/DNN Platform/Library/Data/DataProvider.cs @@ -30,14 +30,9 @@ namespace DotNetNuke.Data public abstract class DataProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DataProvider)); - private const int DuplicateKey = 2601; - public static DataProvider Instance() - { - return ComponentFactory.GetComponent(); - } + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DataProvider)); public virtual string ConnectionString { @@ -73,6 +68,11 @@ public string DefaultProviderName { get { return Instance().ProviderName; } } + + public static DataProvider Instance() + { + return ComponentFactory.GetComponent(); + } public abstract bool IsConnectionValid { get; } @@ -112,6 +112,10 @@ public virtual string UpgradeConnectionString } } + public abstract void ExecuteNonQuery(string procedureName, params object[] commandParameters); + + public abstract void ExecuteNonQuery(int timeoutSec, string procedureName, params object[] commandParameters); + private static DateTime FixDate(DateTime dateToFix) { // Fix for Sql Dates having a minimum value of January 1, 1753 @@ -137,10 +141,6 @@ private object GetRoleNull(int RoleID) return RoleID; } - - public abstract void ExecuteNonQuery(string procedureName, params object[] commandParameters); - - public abstract void ExecuteNonQuery(int timeoutSec, string procedureName, params object[] commandParameters); public abstract void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable); @@ -265,6 +265,42 @@ public virtual Version GetInstallVersion() { return this.GetVersionInternal(false); } + + public virtual DbConnectionStringBuilder GetConnectionStringBuilder() + { + return new SqlConnectionStringBuilder(); + } + + public virtual string GetProviderPath() + { + string path = this.ProviderPath; + if (!string.IsNullOrEmpty(path)) + { + path = HostingEnvironment.MapPath(path); + + // ReSharper disable AssignNullToNotNullAttribute + if (Directory.Exists(path)) + + // ReSharper restore AssignNullToNotNullAttribute + { + if (!this.IsConnectionValid) + { + path = "ERROR: Could not connect to database specified in connectionString for SqlDataProvider"; + } + } + else + { + path = "ERROR: providerPath folder " + path + + " specified for SqlDataProvider does not exist on web server"; + } + } + else + { + path = "ERROR: providerPath folder value not specified in web.config for SqlDataProvider"; + } + + return path; + } private Version GetVersionInternal(bool current) { @@ -305,42 +341,6 @@ private Version GetVersionInternal(bool current) return version; } - public virtual DbConnectionStringBuilder GetConnectionStringBuilder() - { - return new SqlConnectionStringBuilder(); - } - - public virtual string GetProviderPath() - { - string path = this.ProviderPath; - if (!string.IsNullOrEmpty(path)) - { - path = HostingEnvironment.MapPath(path); - - // ReSharper disable AssignNullToNotNullAttribute - if (Directory.Exists(path)) - - // ReSharper restore AssignNullToNotNullAttribute - { - if (!this.IsConnectionValid) - { - path = "ERROR: Could not connect to database specified in connectionString for SqlDataProvider"; - } - } - else - { - path = "ERROR: providerPath folder " + path + - " specified for SqlDataProvider does not exist on web server"; - } - } - else - { - path = "ERROR: providerPath folder value not specified in web.config for SqlDataProvider"; - } - - return path; - } - public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, string Owner, string Qualifier) { var sqlBuilder = builder as SqlConnectionStringBuilder; @@ -566,20 +566,6 @@ public virtual IDataReader GetPortalSettings(int PortalId, string CultureCode) return this.ExecuteReader("GetPortalSettings", PortalId, CultureCode); } - internal virtual IDictionary GetPortalSettingsBySetting(string settingName, string cultureCode) - { - var result = new Dictionary(); - using (var reader = this.ExecuteReader("GetPortalSettingsBySetting", settingName, cultureCode)) - { - while (reader.Read()) - { - result[reader.GetInt32(0)] = reader.GetString(1); - } - } - - return result; - } - public virtual IDataReader GetPortalSpaceUsed(int PortalId) { return this.ExecuteReader("GetPortalSpaceUsed", this.GetNull(PortalId)); @@ -672,6 +658,20 @@ public virtual void UpdatePortalInfo(int portalId, int portalGroupId, string por cultureCode); } + internal virtual IDictionary GetPortalSettingsBySetting(string settingName, string cultureCode) + { + var result = new Dictionary(); + using (var reader = this.ExecuteReader("GetPortalSettingsBySetting", settingName, cultureCode)) + { + while (reader.Read()) + { + result[reader.GetInt32(0)] = reader.GetString(1); + } + } + + return result; + } + public virtual void UpdatePortalSetting(int portalId, string settingName, string settingValue, int userId, string cultureCode, bool isSecure) { diff --git a/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs b/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs index 3804f9057fa..f7173eda2c0 100644 --- a/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs +++ b/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs @@ -10,12 +10,6 @@ namespace DotNetNuke.Data.PetaPoco [CLSCompliant(false)] public class FluentColumnMap { - public ColumnInfo ColumnInfo { get; set; } - - public Func FromDbConverter { get; set; } - - public Func ToDbConverter { get; set; } - public FluentColumnMap() { } @@ -30,6 +24,12 @@ public FluentColumnMap(ColumnInfo columnInfo, Func fromDbConvert { } + public ColumnInfo ColumnInfo { get; set; } + + public Func FromDbConverter { get; set; } + + public Func ToDbConverter { get; set; } + public FluentColumnMap(ColumnInfo columnInfo, Func fromDbConverter, Func toDbConverter) { this.ColumnInfo = columnInfo; diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs index adea136edd2..3edb093489d 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs @@ -46,6 +46,12 @@ public PetaPocoDataContext(string connectionStringName, string tablePrefix, Dict public Dictionary FluentMappers { get; private set; } public string TablePrefix { get; private set; } + + public bool EnableAutoSelect + { + get { return this._database.EnableAutoSelect; } + set { this._database.EnableAutoSelect = value; } + } public void BeginTransaction() { @@ -57,12 +63,6 @@ public void Commit() this._database.CompleteTransaction(); } - public bool EnableAutoSelect - { - get { return this._database.EnableAutoSelect; } - set { this._database.EnableAutoSelect = value; } - } - public void Execute(CommandType type, string sql, params object[] args) { if (type == CommandType.StoredProcedure) diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs index 277e3b295e6..d2957d2e824 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs @@ -15,10 +15,10 @@ namespace DotNetNuke.Data.PetaPoco public static class PetaPocoHelper { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(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); diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs index 92c65ee867c..a1135e2eaf5 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs @@ -13,8 +13,8 @@ namespace DotNetNuke.Data.PetaPoco public class PetaPocoMapper : IMapper { private static IMapper _defaultMapper; - private readonly string _tablePrefix; private static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); + private readonly string _tablePrefix; public PetaPocoMapper(string tablePrefix) { @@ -22,6 +22,22 @@ public PetaPocoMapper(string tablePrefix) _defaultMapper = new StandardMapper(); } + public static void SetMapper(IMapper mapper) + { + _lock.EnterWriteLock(); + try + { + if (Mappers.GetMapper(typeof(T), _defaultMapper) is StandardMapper) + { + Mappers.Register(typeof(T), mapper); + } + } + finally + { + _lock.ExitWriteLock(); + } + } + public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) { bool includeColumn = true; @@ -42,8 +58,8 @@ public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) if (pocoProperty.GetCustomAttributes(typeof(IgnoreColumnAttribute), true).Length > 0) { includeColumn = false; - } - } + } + } ColumnInfo ci = null; if (includeColumn) @@ -83,21 +99,5 @@ public Func GetToDbConverter(PropertyInfo SourceProperty) { return null; } - - public static void SetMapper(IMapper mapper) - { - _lock.EnterWriteLock(); - try - { - if (Mappers.GetMapper(typeof(T), _defaultMapper) is StandardMapper) - { - Mappers.Register(typeof(T), mapper); - } - } - finally - { - _lock.ExitWriteLock(); - } - } } } diff --git a/DNN Platform/Library/Data/RepositoryBase.cs b/DNN Platform/Library/Data/RepositoryBase.cs index c8b8c3cf2fa..2b335f04a08 100644 --- a/DNN Platform/Library/Data/RepositoryBase.cs +++ b/DNN Platform/Library/Data/RepositoryBase.cs @@ -22,6 +22,12 @@ protected RepositoryBase() this.InitializeInternal(); } + protected CacheItemArgs CacheArgs { get; private set; } + + protected string Scope { get; private set; } + + protected bool IsCacheable { get; private set; } + public void Delete(T item) { this.DeleteInternal(item); @@ -151,27 +157,41 @@ private void InitializeInternal() this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); } } - - 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 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); + var secondComparable = second as IComparable; + + // ReSharper disable PossibleNullReferenceException + return firstComparable.CompareTo(secondComparable); -// ReSharper restore PossibleNullReferenceException + // ReSharper restore PossibleNullReferenceException } protected TProperty GetPropertyValue(T item, string propertyName) @@ -204,25 +224,5 @@ protected TProperty GetScopeValue(T item) protected abstract void InsertInternal(T item); protected abstract void UpdateInternal(T item); - - 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; - } - } } } diff --git a/DNN Platform/Library/Data/SqlDataProvider.cs b/DNN Platform/Library/Data/SqlDataProvider.cs index 07b2704670c..de691cd3be6 100644 --- a/DNN Platform/Library/Data/SqlDataProvider.cs +++ b/DNN Platform/Library/Data/SqlDataProvider.cs @@ -19,9 +19,9 @@ namespace DotNetNuke.Data public sealed class SqlDataProvider : DataProvider { + private const string ScriptDelimiter = "(?<=(?:[^\\w]+|^))GO(?=(?: |\\t)*?(?:\\r?\\n|$))"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SqlDataProvider)); private static DatabaseConnectionProvider _dbConnectionProvider = DatabaseConnectionProvider.Instance() ?? new SqlDatabaseConnectionProvider(); - private const string ScriptDelimiter = "(?<=(?:[^\\w]+|^))GO(?=(?: |\\t)*?(?:\\r?\\n|$))"; public override bool IsConnectionValid { @@ -39,6 +39,16 @@ public override Dictionary Settings } } + public override void ExecuteNonQuery(string procedureName, params object[] commandParameters) + { + _dbConnectionProvider.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); + } + + public override void ExecuteNonQuery(int timeoutSec, string procedureName, params object[] commandParameters) + { + _dbConnectionProvider.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); + } + private static bool CanConnect(string connectionString, string owner, string qualifier) { bool connectionValid = true; @@ -234,16 +244,6 @@ private string ExecuteUpgradedConnectionQuery(string sql) return exceptions; } - - public override void ExecuteNonQuery(string procedureName, params object[] commandParameters) - { - _dbConnectionProvider.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); - } - - public override void ExecuteNonQuery(int timeoutSec, string procedureName, params object[] commandParameters) - { - _dbConnectionProvider.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); - } public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable) { diff --git a/DNN Platform/Library/Entities/BaseEntityInfo.cs b/DNN Platform/Library/Entities/BaseEntityInfo.cs index d52f93b9a8b..5317e6ad3de 100644 --- a/DNN Platform/Library/Entities/BaseEntityInfo.cs +++ b/DNN Platform/Library/Entities/BaseEntityInfo.cs @@ -105,6 +105,16 @@ public UserInfo LastModifiedByUser(int portalId) return null; } + /// + /// method used by cbo to fill readonly properties ignored by HydrateObject reflection. + /// + /// the data reader to use. + /// + internal void FillBaseProperties(IDataReader dr) + { + this.FillInternal(dr); + } + /// ----------------------------------------------------------------------------- /// /// Fills a BaseEntityInfo from a Data Reader. @@ -126,15 +136,5 @@ protected void CloneBaseProperties(BaseEntityInfo clonedItem, BaseEntityInfo ori clonedItem.LastModifiedByUserID = originalItem.LastModifiedByUserID; clonedItem.LastModifiedOnDate = originalItem.LastModifiedOnDate; } - - /// - /// method used by cbo to fill readonly properties ignored by HydrateObject reflection. - /// - /// the data reader to use. - /// - internal void FillBaseProperties(IDataReader dr) - { - this.FillInternal(dr); - } } } diff --git a/DNN Platform/Library/Entities/Content/AttachmentController.cs b/DNN Platform/Library/Entities/Content/AttachmentController.cs index bbf9a084817..4fe9da98180 100644 --- a/DNN Platform/Library/Entities/Content/AttachmentController.cs +++ b/DNN Platform/Library/Entities/Content/AttachmentController.cs @@ -19,7 +19,13 @@ namespace DotNetNuke.Entities.Content /// Implementation of . public class AttachmentController : IAttachmentController { + internal const string FilesKey = "Files"; + internal const string ImageKey = "Images"; + internal const string VideoKey = "Videos"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AttachmentController)); + + private readonly IContentController _contentController; public AttachmentController() : this(Util.GetContentController()) @@ -31,17 +37,6 @@ public AttachmentController(IContentController contentController) this._contentController = contentController; } - private readonly IContentController _contentController; - - private void AddToContent(int contentItemId, Action action) - { - var contentItem = this._contentController.GetContentItem(contentItemId); - - action(contentItem); - - this._contentController.UpdateContentItem(contentItem); - } - public void AddFileToContent(int contentItemId, IFileInfo fileInfo) { this.AddFilesToContent(contentItemId, new[] { fileInfo }); @@ -51,6 +46,15 @@ public void AddFilesToContent(int contentItemId, IEnumerable fileInfo { this.AddToContent(contentItemId, contentItem => contentItem.Files.AddRange(fileInfo)); } + + private void AddToContent(int contentItemId, Action action) + { + var contentItem = this._contentController.GetContentItem(contentItemId); + + action(contentItem); + + this._contentController.UpdateContentItem(contentItem); + } public void AddVideoToContent(int contentItemId, IFileInfo fileInfo) { @@ -92,29 +96,6 @@ public IList GetFilesByContent(int contentItemId) return files.Select(fileId => FileManager.Instance.GetFile(fileId)).ToList(); } - - private static void SerializeToMetadata(IList files, NameValueCollection nvc, string key) - { - var remove = !files.Any(); - if (remove == false) - { - var serialized = SerializeFileInfo(files); - - if (string.IsNullOrEmpty(serialized)) - { - remove = true; - } - else - { - nvc[key] = serialized; - } - } - - if (remove) - { - nvc.Remove(key); - } - } internal static void SerializeAttachmentMetadata(ContentItem contentItem) { @@ -123,32 +104,6 @@ internal static void SerializeAttachmentMetadata(ContentItem contentItem) SerializeToMetadata(contentItem.Images, contentItem.Metadata, ImageKey); } - private IEnumerable GetFilesByContent(int contentItemId, string type) - { - var contentItem = this._contentController.GetContentItem(contentItemId); - if (contentItem == null) - { - throw new ApplicationException(string.Format("Cannot find ContentItem ID {0}", contentItemId)); - } - - var serialized = contentItem.Metadata[type]; - - if (string.IsNullOrEmpty(serialized)) - { - return new int[0]; - } - - try - { - return serialized.FromJson().ToArray(); - } - catch (FormatException ex) - { - throw new ApplicationException( - string.Format("ContentItem metadata has become corrupt (ID {0}): invalid file ID", contentItemId), ex); - } - } - internal static IEnumerable DeserializeFileInfo(string content) { if (string.IsNullOrEmpty(content)) @@ -191,9 +146,54 @@ internal static string SerializeFileInfo(IEnumerable files) return fileList.ToJson(); } - internal const string FilesKey = "Files"; - internal const string ImageKey = "Images"; - internal const string VideoKey = "Videos"; + private static void SerializeToMetadata(IList files, NameValueCollection nvc, string key) + { + var remove = !files.Any(); + if (remove == false) + { + var serialized = SerializeFileInfo(files); + + if (string.IsNullOrEmpty(serialized)) + { + remove = true; + } + else + { + nvc[key] = serialized; + } + } + + if (remove) + { + nvc.Remove(key); + } + } + + private IEnumerable GetFilesByContent(int contentItemId, string type) + { + var contentItem = this._contentController.GetContentItem(contentItemId); + if (contentItem == null) + { + throw new ApplicationException(string.Format("Cannot find ContentItem ID {0}", contentItemId)); + } + + var serialized = contentItem.Metadata[type]; + + if (string.IsNullOrEmpty(serialized)) + { + return new int[0]; + } + + try + { + return serialized.FromJson().ToArray(); + } + catch (FormatException ex) + { + throw new ApplicationException( + string.Format("ContentItem metadata has become corrupt (ID {0}): invalid file ID", contentItemId), ex); + } + } internal const string TitleKey = "Title"; } } diff --git a/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs b/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs index 0841e0393aa..60dfe004b90 100644 --- a/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs +++ b/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs @@ -39,35 +39,6 @@ namespace DotNetNuke.Entities.Content.Common /// public static class ContentExtensions { - /// - /// Gets the child terms. - /// - /// The term. - /// The term id. - /// The vocabulary id. - /// term collection which's parent is the specific term. - internal static List GetChildTerms(this Term Term, int termId, int vocabularyId) - { - ITermController ctl = Util.GetTermController(); - - IQueryable terms = from term in ctl.GetTermsByVocabulary(vocabularyId) where term.ParentTermId == termId select term; - - return terms.ToList(); - } - - /// - /// Gets the vocabulary. - /// - /// The term. - /// The vocabulary id. - /// Vocabulary. - internal static Vocabulary GetVocabulary(this Term term, int vocabularyId) - { - IVocabularyController ctl = Util.GetVocabularyController(); - - return (from v in ctl.GetVocabularies() where v.VocabularyId == vocabularyId select v).SingleOrDefault(); - } - /// /// Toes the delimitted string. /// @@ -119,6 +90,35 @@ public static string ToDelimittedString(this List terms, string format, st return sb.ToString(); } + /// + /// Gets the child terms. + /// + /// The term. + /// The term id. + /// The vocabulary id. + /// term collection which's parent is the specific term. + internal static List GetChildTerms(this Term Term, int termId, int vocabularyId) + { + ITermController ctl = Util.GetTermController(); + + IQueryable terms = from term in ctl.GetTermsByVocabulary(vocabularyId) where term.ParentTermId == termId select term; + + return terms.ToList(); + } + + /// + /// Gets the vocabulary. + /// + /// The term. + /// The vocabulary id. + /// Vocabulary. + internal static Vocabulary GetVocabulary(this Term term, int vocabularyId) + { + IVocabularyController ctl = Util.GetVocabularyController(); + + return (from v in ctl.GetVocabularies() where v.VocabularyId == vocabularyId select v).SingleOrDefault(); + } + /// /// Gets the type of the scope. /// diff --git a/DNN Platform/Library/Entities/Content/ContentController.cs b/DNN Platform/Library/Entities/Content/ContentController.cs index 678e33698a0..4e91d8cacc8 100644 --- a/DNN Platform/Library/Entities/Content/ContentController.cs +++ b/DNN Platform/Library/Entities/Content/ContentController.cs @@ -22,11 +22,6 @@ public class ContentController : ServiceLocator GetFactory() - { - return () => new ContentController(); - } - public ContentController() : this(Util.GetDataService()) { @@ -59,6 +54,11 @@ public int AddContentItem(ContentItem contentItem) return contentItem.ContentItemId; } + protected override Func GetFactory() + { + return () => new ContentController(); + } + public void DeleteContentItem(ContentItem contentItem) { // Argument Contract @@ -116,10 +116,10 @@ public IQueryable GetContentItemsByTerm(Term term) public IQueryable GetContentItemsByContentType(int contentTypeId) { return CBO.FillQueryable(this._dataService.GetContentItemsByContentType(contentTypeId)); - } - + } + /// Get a list of content items by ContentType. -/// + /// public IQueryable GetContentItemsByContentType(ContentType contentType) { return this.GetContentItemsByContentType(contentType.ContentTypeId); @@ -234,6 +234,25 @@ public NameValueCollection GetMetaData(int contentItemId) return metadata; } + private static bool MetaDataChanged( + IEnumerable> lh, + IEnumerable> rh) + { + return lh.SequenceEqual(rh, new NameValueEqualityComparer()) == false; + } + + private static void UpdateContentItemsCache(ContentItem contentItem, bool readdItem = true) + { + DataCache.RemoveCache(GetContentItemCacheKey(contentItem.ContentItemId)); // remove first to synch web-farm servers + if (readdItem) + { + CBO.GetCachedObject( + new CacheItemArgs( + GetContentItemCacheKey(contentItem.ContentItemId), + DataCache.ContentItemsCacheTimeOut, DataCache.ContentItemsCachePriority), c => contentItem); + } + } + private void SaveMetadataDelta(ContentItem contentItem) { var persisted = this.GetMetaData(contentItem.ContentItemId); @@ -258,25 +277,6 @@ private void SaveMetadataDelta(ContentItem contentItem) UpdateContentItemsCache(contentItem, false); } - private static bool MetaDataChanged( - IEnumerable> lh, - IEnumerable> rh) - { - return lh.SequenceEqual(rh, new NameValueEqualityComparer()) == false; - } - - private static void UpdateContentItemsCache(ContentItem contentItem, bool readdItem = true) - { - DataCache.RemoveCache(GetContentItemCacheKey(contentItem.ContentItemId)); // remove first to synch web-farm servers - if (readdItem) - { - CBO.GetCachedObject( - new CacheItemArgs( - GetContentItemCacheKey(contentItem.ContentItemId), - DataCache.ContentItemsCacheTimeOut, DataCache.ContentItemsCachePriority), c => contentItem); - } - } - private static string GetContentItemCacheKey(int contetnItemId) { return string.Format(DataCache.ContentItemsCacheKey, contetnItemId); diff --git a/DNN Platform/Library/Entities/Content/ContentItem.cs b/DNN Platform/Library/Entities/Content/ContentItem.cs index b72d614b7eb..5c56a31c1ef 100644 --- a/DNN Platform/Library/Entities/Content/ContentItem.cs +++ b/DNN Platform/Library/Entities/Content/ContentItem.cs @@ -225,6 +225,39 @@ public List Images /// [XmlIgnore] public int StateID { 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] + public virtual int KeyID + { + get + { + return this.ContentItemId; + } + + set + { + this.ContentItemId = value; + } + } + + /// + /// Fill this content object will the information from data reader. + /// + /// The data reader. + /// + public virtual void Fill(IDataReader dr) + { + this.FillInternal(dr); + } /// /// Fills the internal. @@ -268,38 +301,5 @@ protected void Clone(ContentItem cloneItem, ContentItem originalItem) cloneItem.Indexed = originalItem.Indexed; cloneItem.StateID = originalItem.StateID; } - - /// - /// Fill this content object will the information from data reader. - /// - /// The data reader. - /// - public virtual void Fill(IDataReader dr) - { - this.FillInternal(dr); - } - - /// - /// 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] - public virtual int KeyID - { - get - { - return this.ContentItemId; - } - - set - { - this.ContentItemId = value; - } - } } } diff --git a/DNN Platform/Library/Entities/Content/ContentType.cs b/DNN Platform/Library/Entities/Content/ContentType.cs index 8bc70ea4a41..9cbca0334c9 100644 --- a/DNN Platform/Library/Entities/Content/ContentType.cs +++ b/DNN Platform/Library/Entities/Content/ContentType.cs @@ -21,12 +21,12 @@ namespace DotNetNuke.Entities.Content [Serializable] public class ContentType : ContentTypeMemberNameFixer, IHydratable { + private const string desktopModuleContentTypeName = "DesktopModule"; + private const string moduleContentTypeName = "Module"; + private static ContentType _desktopModule; private static ContentType _module; private static ContentType _tab; - - private const string desktopModuleContentTypeName = "DesktopModule"; - private const string moduleContentTypeName = "Module"; private const string tabContentTypeName = "Tab"; public ContentType() @@ -71,17 +71,6 @@ public static ContentType Tab /// The content type id. /// public int ContentTypeId { get; set; } - - /// - /// Fill this content object will the information from data reader. - /// - /// The data reader. - /// - public void Fill(IDataReader dr) - { - this.ContentTypeId = Null.SetNullInteger(dr["ContentTypeID"]); - this.ContentType = Null.SetNullString(dr["ContentType"]); - } /// /// Gets or sets the key ID. @@ -102,6 +91,17 @@ public int KeyID } } + /// + /// Fill this content object will the information from data reader. + /// + /// The data reader. + /// + public void Fill(IDataReader dr) + { + this.ContentTypeId = Null.SetNullInteger(dr["ContentTypeID"]); + this.ContentType = Null.SetNullString(dr["ContentType"]); + } + /// /// override ToString to return content type. /// diff --git a/DNN Platform/Library/Entities/Content/IContentController.cs b/DNN Platform/Library/Entities/Content/IContentController.cs index db4e4fbcae8..113bcd371ae 100644 --- a/DNN Platform/Library/Entities/Content/IContentController.cs +++ b/DNN Platform/Library/Entities/Content/IContentController.cs @@ -82,10 +82,10 @@ public interface IContentController /// /// A list of terms that should be attached to the ContentItems returned. /// - IQueryable GetContentItemsByTerms(IList terms); - + IQueryable GetContentItemsByTerms(IList terms); + /// Return a list of ContentItems that have all of the specified terms attached. -/// + /// IQueryable GetContentItemsByTerms(string[] terms); /// diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs index b273bd9ebf8..74572ea423e 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs @@ -40,12 +40,6 @@ public ScopeType(string scopeType) public int ScopeTypeId { get; set; } - public void Fill(IDataReader dr) - { - this.ScopeTypeId = Null.SetNullInteger(dr["ScopeTypeID"]); - this.ScopeType = Null.SetNullString(dr["ScopeType"]); - } - public int KeyID { get @@ -59,6 +53,12 @@ public int KeyID } } + public void Fill(IDataReader dr) + { + this.ScopeTypeId = Null.SetNullInteger(dr["ScopeTypeID"]); + this.ScopeType = Null.SetNullString(dr["ScopeType"]); + } + public override string ToString() { return this.ScopeType; diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs index 60f0ef5f191..c59a0cf440e 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs @@ -17,8 +17,8 @@ namespace DotNetNuke.Entities.Content.Taxonomy /// public class ScopeTypeController : IScopeTypeController { - private readonly IDataService _DataService; private const int _CacheTimeOut = 20; + private readonly IDataService _DataService; public ScopeTypeController() : this(Util.GetDataService()) @@ -30,11 +30,6 @@ public ScopeTypeController(IDataService dataService) this._DataService = dataService; } - private object GetScopeTypesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillQueryable(this._DataService.GetScopeTypes()).ToList(); - } - public int AddScopeType(ScopeType scopeType) { // Argument Contract @@ -53,6 +48,11 @@ public void ClearScopeTypeCache() { DataCache.RemoveCache(DataCache.ScopeTypesCacheKey); } + + private object GetScopeTypesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillQueryable(this._DataService.GetScopeTypes()).ToList(); + } public void DeleteScopeType(ScopeType scopeType) { diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs b/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs index 606a8d8d76d..2cb5d74112f 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs @@ -259,6 +259,19 @@ public int Weight this._weight = value; } } + + public int KeyID + { + get + { + return this.TermId; + } + + set + { + this.TermId = value; + } + } public virtual void Fill(IDataReader dr) { @@ -286,19 +299,6 @@ public virtual void Fill(IDataReader dr) // Fill base class properties this.FillInternal(dr); } - - public int KeyID - { - get - { - return this.TermId; - } - - set - { - this.TermId = value; - } - } public string GetTermPath() { diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs index bf5c8981643..7111fc64d7b 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs @@ -29,9 +29,9 @@ namespace DotNetNuke.Entities.Content.Taxonomy /// public class TermController : ITermController { - private readonly IDataService _DataService; private const CacheItemPriority _CachePriority = CacheItemPriority.Normal; private const int _CacheTimeOut = 20; + private readonly IDataService _DataService; public TermController() : this(Util.GetDataService()) @@ -43,12 +43,6 @@ public TermController(IDataService dataService) this._DataService = dataService; } - private object GetTermsCallBack(CacheItemArgs cacheItemArgs) - { - var vocabularyId = (int)cacheItemArgs.ParamList[0]; - return CBO.FillQueryable(this._DataService.GetTermsByVocabulary(vocabularyId)).ToList(); - } - /// /// Adds the term. /// @@ -96,6 +90,12 @@ public void AddTermToContent(Term term, ContentItem contentItem) this._DataService.AddTermToContent(term, contentItem); } + + private object GetTermsCallBack(CacheItemArgs cacheItemArgs) + { + var vocabularyId = (int)cacheItemArgs.ParamList[0]; + return CBO.FillQueryable(this._DataService.GetTermsByVocabulary(vocabularyId)).ToList(); + } /// /// Deletes the term. diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs b/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs index 7e2f8254462..8799294fb7e 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs @@ -6,14 +6,6 @@ namespace DotNetNuke.Entities.Content.Taxonomy { public class TermUsage { - public int TotalTermUsage { get; set; } - - public int MonthTermUsage { get; set; } - - public int WeekTermUsage { get; set; } - - public int DayTermUsage { get; set; } - /// /// Initializes a new instance of the class. /// parameterless constructor, so that it can be used in CBO. @@ -32,5 +24,13 @@ internal TermUsage(int total, int month, int week, int day) this.DayTermUsage = day; } + + public int TotalTermUsage { get; set; } + + public int MonthTermUsage { get; set; } + + public int WeekTermUsage { get; set; } + + public int DayTermUsage { get; set; } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs b/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs index 9d3fd406c25..9a03a6ffb25 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs @@ -207,6 +207,19 @@ public int Weight this._Weight = value; } } + + public virtual int KeyID + { + get + { + return this.VocabularyId; + } + + set + { + this.VocabularyId = value; + } + } public virtual void Fill(IDataReader dr) { @@ -231,18 +244,5 @@ public virtual void Fill(IDataReader dr) // Fill base class properties this.FillInternal(dr); } - - public virtual int KeyID - { - get - { - return this.VocabularyId; - } - - set - { - this.VocabularyId = value; - } - } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs index f12dbef31d4..ccc236cd91f 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs @@ -18,8 +18,8 @@ namespace DotNetNuke.Entities.Content.Taxonomy /// public class VocabularyController : IVocabularyController { - private readonly IDataService _DataService; private const int _CacheTimeOut = 20; + private readonly IDataService _DataService; public VocabularyController() : this(Util.GetDataService()) @@ -31,11 +31,6 @@ public VocabularyController(IDataService dataService) this._DataService = dataService; } - private object GetVocabulariesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillQueryable(this._DataService.GetVocabularies()).ToList(); - } - public int AddVocabulary(Vocabulary vocabulary) { // Argument Contract @@ -55,6 +50,11 @@ public void ClearVocabularyCache() { DataCache.RemoveCache(DataCache.VocabularyCacheKey); } + + private object GetVocabulariesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillQueryable(this._DataService.GetVocabularies()).ToList(); + } public void DeleteVocabulary(Vocabulary vocabulary) { diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs index d06673082d0..bec2699951e 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs @@ -26,8 +26,8 @@ namespace DotNetNuke.Entities.Content.Workflow [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public class ContentWorkflowController : ComponentBase, IContentWorkflowController { - private readonly ContentController contentController; private const string ContentWorkflowNotificationType = "ContentWorkflowNotification"; + private readonly ContentController contentController; private ContentWorkflowController() { @@ -501,6 +501,30 @@ public void SendWorkflowNotification(bool sendEmail, bool sendMessage, PortalSet var replacedBody = this.ReplaceNotificationTokens(body, null, null, null, settings.PortalId, userID); this.SendNotification(sendEmail, sendMessage, settings, roles, users, replacedSubject, replacedBody, comment, userID, null, null); } + + private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, IEnumerable roles) + { + return roles.Any(r => r.RoleName == settings.AdministratorRoleName); + } + + private static IEnumerable IncludeSuperUsers(ICollection users) + { + var superUsers = UserController.GetUsers(false, true, Null.NullInteger); + foreach (UserInfo superUser in superUsers) + { + if (IsSuperUserNotIncluded(users, superUser)) + { + users.Add(superUser); + } + } + + return users; + } + + private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo superUser) + { + return users.All(u => u.UserID != superUser.UserID); + } private void AddWorkflowCommentLog(ContentItem item, string userComment, int userID) { @@ -608,11 +632,6 @@ private IEnumerable GetRolesFromPermissions(PortalSettings settings, I return roles; } - private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, IEnumerable roles) - { - return roles.Any(r => r.RoleName == settings.AdministratorRoleName); - } - private IEnumerable GetUsersFromPermissions(PortalSettings settings, IEnumerable permissions) { var users = new List(); @@ -627,25 +646,6 @@ private IEnumerable GetUsersFromPermissions(PortalSettings settings, I return IncludeSuperUsers(users); } - private static IEnumerable IncludeSuperUsers(ICollection users) - { - var superUsers = UserController.GetUsers(false, true, Null.NullInteger); - foreach (UserInfo superUser in superUsers) - { - if (IsSuperUserNotIncluded(users, superUser)) - { - users.Add(superUser); - } - } - - return users; - } - - private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo superUser) - { - return users.All(u => u.UserID != superUser.UserID); - } - private bool IsReviewer(UserInfo user, PortalSettings settings, IEnumerable permissions) { var administratorRoleName = settings.AdministratorRoleName; diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs index dae0208522b..045ef053138 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs @@ -13,11 +13,6 @@ namespace DotNetNuke.Entities.Content.Workflow.Repositories internal class WorkflowActionRepository : ServiceLocator, IWorkflowActionRepository { - protected override Func GetFactory() - { - return () => new WorkflowActionRepository(); - } - public WorkflowAction GetWorkflowAction(int contentTypeId, string type) { using (var context = DataContext.Instance()) @@ -35,5 +30,10 @@ public void AddWorkflowAction(WorkflowAction action) rep.Insert(action); } } + + protected override Func GetFactory() + { + return () => new WorkflowActionRepository(); + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs index 613fdb2ac69..6ce3039c9c7 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs @@ -135,6 +135,16 @@ public void DeleteWorkflow(Entities.Workflow workflow) DataCache.RemoveCache(GetWorkflowItemKey(workflow.WorkflowID)); } + + internal static string GetWorkflowItemKey(int workflowId) + { + return string.Format(DataCache.ContentWorkflowCacheKey, workflowId); + } + + protected override Func GetFactory() + { + return () => new WorkflowRepository(); + } private static bool DoesExistWorkflow(Entities.Workflow workflow, IRepository rep) { @@ -143,11 +153,6 @@ private static bool DoesExistWorkflow(Entities.Workflow workflow, IRepository 0) @@ -158,10 +163,5 @@ private static void CacheWorkflow(Entities.Workflow workflow) DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), _ => workflow); } } - - protected override Func GetFactory() - { - return () => new WorkflowRepository(); - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs index 23ecba0b0e4..25e43ecef37 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs @@ -97,6 +97,11 @@ public void DeleteWorkflowState(WorkflowState state) DataCache.RemoveCache(WorkflowRepository.GetWorkflowItemKey(state.WorkflowID)); } + protected override Func GetFactory() + { + return () => new WorkflowStateRepository(); + } + private static bool DoesExistWorkflowState(WorkflowState state, IRepository rep) { return rep.Find( @@ -119,10 +124,5 @@ private void CacheWorkflowState(WorkflowState state) _ => state); } } - - protected override Func GetFactory() - { - return () => new WorkflowStateRepository(); - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs b/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs index 4cd21302777..4bbbf358a2f 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs @@ -26,6 +26,18 @@ public SystemWorkflowManager() this._workflowStateRepository = WorkflowStateRepository.Instance; } + public void CreateSystemWorkflows(int portalId) + { + this.CreateDirectPublishWorkflow(portalId); + this.CreateSaveDraftWorkflow(portalId); + this.CreateContentApprovalWorkflow(portalId); + } + + public Entities.Workflow GetDirectPublishWorkflow(int portalId) + { + return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == DirectPublishWorkflowKey); + } + private WorkflowState GetDefaultWorkflowState(int order) { return new WorkflowState @@ -98,18 +110,6 @@ private void CreateContentApprovalWorkflow(int portalId) state.WorkflowID = workflow.WorkflowID; this._workflowStateRepository.AddWorkflowState(state); } - - public void CreateSystemWorkflows(int portalId) - { - this.CreateDirectPublishWorkflow(portalId); - this.CreateSaveDraftWorkflow(portalId); - this.CreateContentApprovalWorkflow(portalId); - } - - public Entities.Workflow GetDirectPublishWorkflow(int portalId) - { - return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == DirectPublishWorkflowKey); - } public Entities.Workflow GetSaveDraftWorkflow(int portalId) { diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs index 24303353278..5a8956f79be 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs @@ -58,6 +58,28 @@ public WorkflowEngine() this._systemWorkflowManager = SystemWorkflowManager.Instance; } + public UserInfo GetStartedDraftStateUser(ContentItem contentItem) + { + return this.GetUserByWorkflowLogType(contentItem, WorkflowLogType.WorkflowStarted); + } + + public UserInfo GetSubmittedDraftStateUser(ContentItem contentItem) + { + return this.GetUserByWorkflowLogType(contentItem, WorkflowLogType.DraftCompleted); + } + + private static List GetRolesFromPermissions(PortalSettings settings, IEnumerable permissions) + { + return (from permission in permissions + where permission.AllowAccess && permission.RoleID > Null.NullInteger + select RoleController.Instance.GetRoleById(settings.PortalId, permission.RoleID)).ToList(); + } + + private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, IEnumerable roles) + { + return roles.Any(r => r.RoleName == settings.AdministratorRoleName); + } + private StateTransaction CreateInitialTransaction(int contentItemId, int stateId, int userId) { return new StateTransaction @@ -281,21 +303,14 @@ private Notification GetNotification(string workflowContext, StateTransaction st }; return notification; } - - private class ReviewersDto - { - public List Roles { get; set; } - - public List Users { get; set; } - } private ReviewersDto GetUserAndRolesForStateReviewers(PortalSettings portalSettings, WorkflowState state) { - var reviewers = new ReviewersDto - { - Roles = new List(), - Users = new List(), - }; + var reviewers = new ReviewersDto + { + Roles = new List(), + Users = new List(), + }; if (state.SendNotification) { var permissions = this._workflowStatePermissionsRepository.GetWorkflowStatePermissionByState(state.StateID).ToArray(); @@ -316,24 +331,19 @@ private ReviewersDto GetUserAndRolesForStateReviewers(PortalSettings portalSetti return reviewers; } - - private static List GetRolesFromPermissions(PortalSettings settings, IEnumerable permissions) + + private class ReviewersDto { - return (from permission in permissions - where permission.AllowAccess && permission.RoleID > Null.NullInteger - select RoleController.Instance.GetRoleById(settings.PortalId, permission.RoleID)).ToList(); - } + public List Roles { get; set; } - private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, IEnumerable roles) - { - return roles.Any(r => r.RoleName == settings.AdministratorRoleName); + public List Users { get; set; } } private static List GetUsersFromPermissions(PortalSettings settings, IEnumerable permissions) { - return (from permission in permissions - where permission.AllowAccess && permission.UserID > Null.NullInteger - select UserController.GetUserById(settings.PortalId, permission.UserID)).ToList(); + return (from permission in permissions + where permission.AllowAccess && permission.UserID > Null.NullInteger + select UserController.GetUserById(settings.PortalId, permission.UserID)).ToList(); } private static List IncludeSuperUsers(ICollection users) @@ -354,6 +364,12 @@ private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo { return users.All(u => u.UserID != superUser.UserID); } + + private static string GetWorkflowActionComment(WorkflowLogType logType) + { + var logName = Enum.GetName(typeof(WorkflowLogType), logType); + return Localization.GetString(logName + ".Comment"); + } private void AddWorkflowCommentLog(ContentItem contentItem, int userId, string userComment) { @@ -402,12 +418,6 @@ private void TryAddWorkflowLog(ContentItem contentItem, WorkflowState state, Wor this._workflowLogger.AddWorkflowLog(contentItem.ContentItemId, workflow.WorkflowID, logType, logComment, userId); } - private static string GetWorkflowActionComment(WorkflowLogType logType) - { - var logName = Enum.GetName(typeof(WorkflowLogType), logType); - return Localization.GetString(logName + ".Comment"); - } - private string ReplaceNotificationTokens(string text, Entities.Workflow workflow, ContentItem item, WorkflowState state, int userId, string comment = "") { var user = this._userController.GetUserById(workflow.PortalID, userId); @@ -468,16 +478,6 @@ private WorkflowState GetPreviousWorkflowState(Entities.Workflow workflow, int s return previousState ?? workflow.LastState; } - - public UserInfo GetStartedDraftStateUser(ContentItem contentItem) - { - return this.GetUserByWorkflowLogType(contentItem, WorkflowLogType.WorkflowStarted); - } - - public UserInfo GetSubmittedDraftStateUser(ContentItem contentItem) - { - return this.GetUserByWorkflowLogType(contentItem, WorkflowLogType.DraftCompleted); - } public void StartWorkflow(int workflowId, int contentItemId, int userId) { diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs index 4e90a64468b..288a120bb32 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs @@ -21,6 +21,16 @@ public WorkflowLogger() this._workflowLogRepository = WorkflowLogRepository.Instance; } + public IEnumerable GetWorkflowLogs(int contentItemId, int workflowId) + { + return this._workflowLogRepository.GetWorkflowLogs(contentItemId, workflowId); + } + + public void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType type, string comment, int userId) + { + this.AddWorkflowLog(contentItemId, workflowId, type, this.GetWorkflowActionText(type), comment, userId); + } + private void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType type, string action, string comment, int userId) { var workflowLog = new WorkflowLog @@ -41,16 +51,6 @@ private string GetWorkflowActionText(WorkflowLogType logType) var logName = Enum.GetName(typeof(WorkflowLogType), logType); return Localization.GetString(logName + ".Action"); } - - public IEnumerable GetWorkflowLogs(int contentItemId, int workflowId) - { - return this._workflowLogRepository.GetWorkflowLogs(contentItemId, workflowId); - } - - public void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType type, string comment, int userId) - { - this.AddWorkflowLog(contentItemId, workflowId, type, this.GetWorkflowActionText(type), comment, userId); - } public void AddWorkflowLog(int contentItemId, int workflowId, string action, string comment, int userId) { diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs index 5762e44c476..d2b5ad8a3a0 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs @@ -242,6 +242,11 @@ public int GetContentWorkflowStateUsageCount(int stateId) return this._dataProvider.GetContentWorkflowStateUsageCount(stateId); } + protected override Func GetFactory() + { + return () => new WorkflowStateManager(); + } + private int GetStateIndex(WorkflowState[] states, WorkflowState currentState) { int i = 0; @@ -281,10 +286,5 @@ private void MoveState(WorkflowState state, int targetIndex, int currentIndex) } } } - - protected override Func GetFactory() - { - return () => new WorkflowStateManager(); - } } } diff --git a/DNN Platform/Library/Entities/Controllers/HostController.cs b/DNN Platform/Library/Entities/Controllers/HostController.cs index e0dd14ca79f..5a634996629 100644 --- a/DNN Platform/Library/Entities/Controllers/HostController.cs +++ b/DNN Platform/Library/Entities/Controllers/HostController.cs @@ -355,7 +355,7 @@ public void IncrementCrmVersion(bool includeOverridingPortals) /// /// Gets all settings from the databse. /// - /// <, >. + /// private static Dictionary GetSettingsFromDatabase() { var dicSettings = new Dictionary(); @@ -367,11 +367,11 @@ private static Dictionary GetSettingsFromDatabase( { string key = dr.GetString(0); var config = new ConfigurationSetting - { - Key = key, - IsSecure = Convert.ToBoolean(dr[2]), - Value = dr.IsDBNull(1) ? string.Empty : dr.GetString(1), - }; + { + Key = key, + IsSecure = Convert.ToBoolean(dr[2]), + Value = dr.IsDBNull(1) ? string.Empty : dr.GetString(1), + }; dicSettings.Add(key, config); } diff --git a/DNN Platform/Library/Entities/Controllers/IHostController.cs b/DNN Platform/Library/Entities/Controllers/IHostController.cs index 8dd540a8bbe..ad1d48b8a55 100644 --- a/DNN Platform/Library/Entities/Controllers/IHostController.cs +++ b/DNN Platform/Library/Entities/Controllers/IHostController.cs @@ -70,13 +70,13 @@ public interface IHostController /// /// Gets the host settings. /// - /// Host settings as a <, >. + /// Host settings as a . Dictionary GetSettings(); /// /// Gets the host settings. /// - /// Host settings as a <, >. + /// Host settings as a . Dictionary GetSettingsDictionary(); /// diff --git a/DNN Platform/Library/Entities/DataStructures/NTree.cs b/DNN Platform/Library/Entities/DataStructures/NTree.cs index da6692904a6..b0dfd2d97d0 100644 --- a/DNN Platform/Library/Entities/DataStructures/NTree.cs +++ b/DNN Platform/Library/Entities/DataStructures/NTree.cs @@ -12,16 +12,16 @@ namespace DotNetNuke.Entities.DataStructures [DataContract] public class NTree { - public NTree() - { - this.Children = new List>(); - } - [DataMember(Name = "data")] public T Data; [DataMember(Name = "children")] public List> Children; + + public NTree() + { + this.Children = new List>(); + } public bool HasChildren() { diff --git a/DNN Platform/Library/Entities/EventManager.cs b/DNN Platform/Library/Entities/EventManager.cs index 61969dde82b..ce874f2520d 100644 --- a/DNN Platform/Library/Entities/EventManager.cs +++ b/DNN Platform/Library/Entities/EventManager.cs @@ -22,92 +22,6 @@ namespace DotNetNuke.Entities public class EventManager : ServiceLocator, IEventManager { - private event EventHandler FileAdded; - - private event EventHandler FileChanged; - - private event EventHandler FileDeleted; - - private event EventHandler FileMetadataChanged; - - private event EventHandler FileMoved; - - private event EventHandler FileOverwritten; - - private event EventHandler FileRenamed; - - private event EventHandler FileDownloaded; - - private event EventHandler FolderAdded; - - private event EventHandler FolderDeleted; - - private event EventHandler FolderMoved; - - private event EventHandler FolderRenamed; - - private event EventHandler FollowRequested; - - private event EventHandler UnfollowRequested; - - private event EventHandler FriendshipAccepted; - - private event EventHandler FriendshipDeleted; - - private event EventHandler FriendshipRequested; - - private event EventHandler ModuleCreated; - - private event EventHandler ModuleUpdated; - - private event EventHandler ModuleRemoved; // soft delete - - private event EventHandler ModuleDeleted; // hard delete - - private event EventHandler PortalCreated; - - private event EventHandler PortalTemplateCreated; - - private event EventHandler PortalSettingUpdated; - - private event EventHandler ProfileUpdated; - - private event EventHandler RoleCreated; - - private event EventHandler RoleDeleted; - - private event EventHandler RoleJoined; - - private event EventHandler RoleLeft; - - private event EventHandler TabCreated; - - private event EventHandler TabUpdated; - - private event EventHandler TabRemoved; // soft delete - - private event EventHandler TabDeleted; // hard delete - - private event EventHandler TabRestored; - - private event EventHandler TabMarkedAsPublished; - - private event EventHandler TabSerialize; // soft delete - - private event EventHandler TabDeserialize; // hard delete - - private event EventHandler UserApproved; - - private event EventHandler UserAuthenticated; - - private event EventHandler UserCreated; - - private event EventHandler UserDeleted; - - private event EventHandler UserRemoved; - - private event EventHandler UserUpdated; - public EventManager() { foreach (var handler in EventHandlersContainer.Instance.EventHandlers) @@ -202,11 +116,92 @@ public EventManager() this.UserUpdated += handler.Value.UserUpdated; } } + + private event EventHandler FileAdded; + + private event EventHandler FileChanged; + + private event EventHandler FileDeleted; + + private event EventHandler FileMetadataChanged; + + private event EventHandler FileMoved; + + private event EventHandler FileOverwritten; + + private event EventHandler FileRenamed; + + private event EventHandler FileDownloaded; - protected override Func GetFactory() - { - return () => new EventManager(); - } + private event EventHandler FolderAdded; + + private event EventHandler FolderDeleted; + + private event EventHandler FolderMoved; + + private event EventHandler FolderRenamed; + + private event EventHandler FollowRequested; + + private event EventHandler UnfollowRequested; + + private event EventHandler FriendshipAccepted; + + private event EventHandler FriendshipDeleted; + + private event EventHandler FriendshipRequested; + + private event EventHandler ModuleCreated; + + private event EventHandler ModuleUpdated; + + private event EventHandler ModuleRemoved; // soft delete + + private event EventHandler ModuleDeleted; // hard delete + + private event EventHandler PortalCreated; + + private event EventHandler PortalTemplateCreated; + + private event EventHandler PortalSettingUpdated; + + private event EventHandler ProfileUpdated; + + private event EventHandler RoleCreated; + + private event EventHandler RoleDeleted; + + private event EventHandler RoleJoined; + + private event EventHandler RoleLeft; + + private event EventHandler TabCreated; + + private event EventHandler TabUpdated; + + private event EventHandler TabRemoved; // soft delete + + private event EventHandler TabDeleted; // hard delete + + private event EventHandler TabRestored; + + private event EventHandler TabMarkedAsPublished; + + private event EventHandler TabSerialize; // soft delete + + private event EventHandler TabDeserialize; // hard delete + + private event EventHandler UserApproved; + + private event EventHandler UserAuthenticated; + + private event EventHandler UserCreated; + + private event EventHandler UserDeleted; + + private event EventHandler UserRemoved; + + private event EventHandler UserUpdated; public virtual void OnFileAdded(FileAddedEventArgs args) { @@ -228,6 +223,11 @@ public virtual void OnFileChanged(FileChangedEventArgs args) AddLog(args.FileInfo, args.UserId, EventLogController.EventLogType.FILE_CHANGED); } + protected override Func GetFactory() + { + return () => new EventManager(); + } + public virtual void OnFileDeleted(FileDeletedEventArgs args) { if (this.FileDeleted != null) diff --git a/DNN Platform/Library/Entities/Host/Host.cs b/DNN Platform/Library/Entities/Host/Host.cs index 5607f04096c..7de4b75dd14 100644 --- a/DNN Platform/Library/Entities/Host/Host.cs +++ b/DNN Platform/Library/Entities/Host/Host.cs @@ -27,6 +27,8 @@ namespace DotNetNuke.Entities.Host [Serializable] public class Host : BaseEntityInfo { + private static Globals.PerformanceSettings? _performanceSetting; + /// ----------------------------------------------------------------------------- /// /// Gets the AutoAccountUnlockDuration. @@ -955,8 +957,6 @@ public static string PaymentProcessor } } - private static Globals.PerformanceSettings? _performanceSetting; - /// ----------------------------------------------------------------------------- /// /// Gets or sets the PerformanceSettings. @@ -1274,50 +1274,6 @@ public static string SMTPAuthentication } } - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets the SMTP mode (portal|host). - /// - /// ----------------------------------------------------------------------------- - internal static bool SMTPPortalEnabled - { - get - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - - if (portalSettings == null || portalSettings.ActiveTab == null) - { - // without portal settings or active tab, we can't continue - return false; - } - - // we don't want to load the portal smtp server when on a host tab. - if (portalSettings.ActiveTab.PortalID == Null.NullInteger) - { - return false; - } - - var currentSmtpMode = PortalController.GetPortalSetting("SMTPmode", portalSettings.PortalId, Null.NullString); - - return currentSmtpMode.Equals("P", StringComparison.OrdinalIgnoreCase); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Get's the SMTP setting, if portal smtp is configured, it will return items from the portal settings collection. - /// - /// ----------------------------------------------------------------------------- - private static string GetSmtpSetting(string settingName) - { - if (SMTPPortalEnabled) - { - return PortalController.GetPortalSetting(settingName, PortalSettings.Current.PortalId, Null.NullString); - } - - return HostController.Instance.GetString(settingName); - } - /// ----------------------------------------------------------------------------- /// /// Gets the SMTP Password. @@ -1384,6 +1340,50 @@ public static string SMTPUsername } } + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets the SMTP mode (portal|host). + /// + /// ----------------------------------------------------------------------------- + internal static bool SMTPPortalEnabled + { + get + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + + if (portalSettings == null || portalSettings.ActiveTab == null) + { + // without portal settings or active tab, we can't continue + return false; + } + + // we don't want to load the portal smtp server when on a host tab. + if (portalSettings.ActiveTab.PortalID == Null.NullInteger) + { + return false; + } + + var currentSmtpMode = PortalController.GetPortalSetting("SMTPmode", portalSettings.PortalId, Null.NullString); + + return currentSmtpMode.Equals("P", StringComparison.OrdinalIgnoreCase); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Get's the SMTP setting, if portal smtp is configured, it will return items from the portal settings collection. + /// + /// ----------------------------------------------------------------------------- + private static string GetSmtpSetting(string settingName) + { + if (SMTPPortalEnabled) + { + return PortalController.GetPortalSetting(settingName, PortalSettings.Current.PortalId, Null.NullString); + } + + return HostController.Instance.GetString(settingName); + } + /// ----------------------------------------------------------------------------- /// /// Gets the SMTP Connection Limit. diff --git a/DNN Platform/Library/Entities/Host/ServerInfo.cs b/DNN Platform/Library/Entities/Host/ServerInfo.cs index 1e0e95ca8f9..3fcfc5b0eb3 100644 --- a/DNN Platform/Library/Entities/Host/ServerInfo.cs +++ b/DNN Platform/Library/Entities/Host/ServerInfo.cs @@ -47,6 +47,25 @@ public ServerInfo(DateTime created, DateTime lastactivity) public int PingFailureCount { get; set; } public string UniqueId { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public int KeyID + { + get + { + return this.ServerID; + } + + set + { + this.ServerID = value; + } + } /// ----------------------------------------------------------------------------- /// @@ -83,24 +102,5 @@ public void Fill(IDataReader dr) } } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Key ID. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - public int KeyID - { - get - { - return this.ServerID; - } - - set - { - this.ServerID = value; - } - } } } diff --git a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs index 2a978eedde6..e93f132a812 100644 --- a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs +++ b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs @@ -22,6 +22,10 @@ namespace DotNetNuke.Entities.Host public class IPFilterController : ComponentBase, IIPFilterController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IPFilterController)); + + internal IPFilterController() + { + } private enum FilterType { @@ -29,10 +33,6 @@ private enum FilterType Deny = 2, } - internal IPFilterController() - { - } - /// /// add a new IP filter. /// @@ -88,8 +88,8 @@ IList IIPFilterController.GetIPFilters() public void IsIPAddressBanned(string ipAddress) { if (this.CheckIfBannedIPAddress(ipAddress)) - {// should throw 403.6 - throw new HttpException(403, string.Empty); + {// should throw 403.6 + throw new HttpException(403, string.Empty); } } @@ -103,46 +103,6 @@ public bool IsIPBanned(string ipAddress) return this.CheckIfBannedIPAddress(ipAddress); } - private bool CheckIfBannedIPAddress(string ipAddress) - { - IList filterList = Instance.GetIPFilters(); - bool ipAllowed = true; - foreach (var ipFilterInfo in filterList) - { - // if a single deny exists, this win's - if (ipFilterInfo.RuleType == (int)FilterType.Deny) - { - if (NetworkUtils.IsIPInRange(ipAddress, ipFilterInfo.IPAddress, ipFilterInfo.SubnetMask)) - { - // log - this.LogBannedIPAttempt(ipAddress); - return true; - } - } - - // check any allows - if one exists set flag but let processing continue to verify no deny overrides - if (ipFilterInfo.RuleType == (int)FilterType.Allow) - { - if (ipFilterInfo.IPAddress == "*" || NetworkUtils.IsIPInRange(ipAddress, ipFilterInfo.IPAddress, ipFilterInfo.SubnetMask)) - { - ipAllowed = false; - } - } - } - - return ipAllowed; - } - - private void LogBannedIPAttempt(string ipAddress) - { - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), - }; - log.LogProperties.Add(new LogDetailInfo("HostAddress", ipAddress)); - LogController.Instance.AddLog(log); - } - /// /// Check if an IP address range can still access based on a set of rules /// note: this set is typically the list of IP filter rules minus a proposed delete. @@ -226,6 +186,46 @@ public bool IsAllowableDeny(string currentIP, IPFilterInfo ipFilter) return true; } + + private bool CheckIfBannedIPAddress(string ipAddress) + { + IList filterList = Instance.GetIPFilters(); + bool ipAllowed = true; + foreach (var ipFilterInfo in filterList) + { + // if a single deny exists, this win's + if (ipFilterInfo.RuleType == (int)FilterType.Deny) + { + if (NetworkUtils.IsIPInRange(ipAddress, ipFilterInfo.IPAddress, ipFilterInfo.SubnetMask)) + { + // log + this.LogBannedIPAttempt(ipAddress); + return true; + } + } + + // check any allows - if one exists set flag but let processing continue to verify no deny overrides + if (ipFilterInfo.RuleType == (int)FilterType.Allow) + { + if (ipFilterInfo.IPAddress == "*" || NetworkUtils.IsIPInRange(ipAddress, ipFilterInfo.IPAddress, ipFilterInfo.SubnetMask)) + { + ipAllowed = false; + } + } + } + + return ipAllowed; + } + + private void LogBannedIPAttempt(string ipAddress) + { + var log = new LogInfo + { + LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), + }; + log.LogProperties.Add(new LogDetailInfo("HostAddress", ipAddress)); + LogController.Instance.AddLog(log); + } private static void AssertValidIPFilter(IPFilterInfo ipFilter) { diff --git a/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs b/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs index d37e19fa8b2..430003c7d08 100644 --- a/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs +++ b/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs @@ -46,6 +46,24 @@ public IPFilterInfo() public string SubnetMask { get; set; } public int RuleType { get; set; } + + /// + /// Gets or sets and sets the Key ID. + /// + /// KeyId of the IHydratable.Key. + /// + public int KeyID + { + get + { + return this.IPFilterID; + } + + set + { + this.IPFilterID = value; + } + } /// /// Fills an IPFilterInfo from a Data Reader. @@ -72,23 +90,5 @@ public void Fill(IDataReader dr) this.FillInternal(dr); } - - /// - /// Gets or sets and sets the Key ID. - /// - /// KeyId of the IHydratable.Key. - /// - public int KeyID - { - get - { - return this.IPFilterID; - } - - set - { - this.IPFilterID = value; - } - } } } diff --git a/DNN Platform/Library/Entities/Icons/IconController.cs b/DNN Platform/Library/Entities/Icons/IconController.cs index 2e10b31800f..414220f0316 100644 --- a/DNN Platform/Library/Entities/Icons/IconController.cs +++ b/DNN Platform/Library/Entities/Icons/IconController.cs @@ -41,13 +41,15 @@ namespace DotNetNuke.Entities.Icons /// public class IconController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IconController)); public const string DefaultIconSize = "16X16"; public const string DefaultLargeIconSize = "32X32"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IconController)); public const string DefaultIconStyle = "Standard"; public const string IconKeyName = "IconKey"; public const string IconSizeName = "IconSize"; public const string IconStyleName = "IconStyle"; + + private static readonly SharedDictionary _iconsStatusOnDisk = new SharedDictionary(); /// /// Gets the Icon URL. @@ -113,7 +115,22 @@ public static string GetFileIconUrl(string extension) return IconURL("ExtFile", "32x32", "Standard"); } - private static readonly SharedDictionary _iconsStatusOnDisk = new SharedDictionary(); + public static string[] GetIconSets() + { + string iconPhysicalPath = Path.Combine(Globals.ApplicationMapPath, "icons"); + var iconRootDir = new DirectoryInfo(iconPhysicalPath); + string result = string.Empty; + foreach (var iconDir in iconRootDir.EnumerateDirectories()) + { + string testFile = Path.Combine(iconDir.FullName, "About_16x16_Standard.png"); + if (File.Exists(testFile)) + { + result += iconDir.Name + ","; + } + } + + return result.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + } private static void CheckIconOnDisk(string path) { @@ -138,22 +155,5 @@ private static void CheckIconOnDisk(string path) } } } - - public static string[] GetIconSets() - { - string iconPhysicalPath = Path.Combine(Globals.ApplicationMapPath, "icons"); - var iconRootDir = new DirectoryInfo(iconPhysicalPath); - string result = string.Empty; - foreach (var iconDir in iconRootDir.EnumerateDirectories()) - { - string testFile = Path.Combine(iconDir.FullName, "About_16x16_Standard.png"); - if (File.Exists(testFile)) - { - result += iconDir.Name + ","; - } - } - - return result.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - } } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs index c5bd82a0d87..88899e1d2d3 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs @@ -187,6 +187,27 @@ public ModuleAction(int id, string title, string cmdName, string cmdArg, string /// ----------------------------------------------------------------------------- public string CommandArgument { get; set; } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the string that is displayed in the Module Menu + /// that represents a given menu action. + /// + /// The string value that is displayed to represent the module action. + /// The title property is displayed by the Actions control for each module + /// action. + /// ----------------------------------------------------------------------------- + public string Title { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the URL for the icon file that is displayed for the given + /// . + /// + /// The URL for the icon that is displayed with the module action. + /// The URL for the icon is a simple string and is not checked for formatting. + /// ----------------------------------------------------------------------------- + public string Icon { get; set; } + internal string ControlKey { get @@ -221,27 +242,6 @@ internal string ControlKey } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the string that is displayed in the Module Menu - /// that represents a given menu action. - /// - /// The string value that is displayed to represent the module action. - /// The title property is displayed by the Actions control for each module - /// action. - /// ----------------------------------------------------------------------------- - public string Title { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the URL for the icon file that is displayed for the given - /// . - /// - /// The URL for the icon that is displayed with the module action. - /// The URL for the icon is a simple string and is not checked for formatting. - /// ----------------------------------------------------------------------------- - public string Icon { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets or sets the URL to which the user is redirected when the diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs index 3ecef45951a..8dc4a36c3c9 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs @@ -28,19 +28,39 @@ public class ModuleDefinitionController { private const string key = "ModuleDefID"; private static readonly DataProvider dataProvider = DataProvider.Instance(); - + /// ----------------------------------------------------------------------------- /// - /// GetModuleDefinitionsCallBack gets a Dictionary of Module Definitions from - /// the Database. + /// GetModuleDefinitionByID gets a Module Definition by its ID. /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call. + /// The ID of the Module Definition. + /// /// ----------------------------------------------------------------------------- - private static object GetModuleDefinitionsCallBack(CacheItemArgs cacheItemArgs) + public static ModuleDefinitionInfo GetModuleDefinitionByID(int moduleDefID) { - return CBO.FillDictionary(key, dataProvider.GetModuleDefinitions(), new Dictionary()); - } + return (from kvp in GetModuleDefinitions() + where kvp.Value.ModuleDefID == moduleDefID + select kvp.Value) + .FirstOrDefault(); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetModuleDefinitionByFriendlyName gets a Module Definition by its Friendly + /// Name (and DesktopModuleID). + /// + /// The friendly name. + /// + /// ----------------------------------------------------------------------------- + public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string friendlyName) + { + Requires.NotNullOrEmpty("friendlyName", friendlyName); + + return (from kvp in GetModuleDefinitions() + where kvp.Value.FriendlyName == friendlyName + select kvp.Value) + .FirstOrDefault(); + } /// ----------------------------------------------------------------------------- /// @@ -79,39 +99,19 @@ public void DeleteModuleDefinition(int moduleDefinitionId) DataProvider.Instance().AddSearchDeletedItems(document); } - - /// ----------------------------------------------------------------------------- - /// - /// GetModuleDefinitionByID gets a Module Definition by its ID. - /// - /// The ID of the Module Definition. - /// - /// ----------------------------------------------------------------------------- - public static ModuleDefinitionInfo GetModuleDefinitionByID(int moduleDefID) - { - return (from kvp in GetModuleDefinitions() - where kvp.Value.ModuleDefID == moduleDefID - select kvp.Value) - .FirstOrDefault(); - } - + /// ----------------------------------------------------------------------------- /// - /// GetModuleDefinitionByFriendlyName gets a Module Definition by its Friendly - /// Name (and DesktopModuleID). + /// GetModuleDefinitionsCallBack gets a Dictionary of Module Definitions from + /// the Database. /// - /// The friendly name. - /// + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. /// ----------------------------------------------------------------------------- - public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string friendlyName) + private static object GetModuleDefinitionsCallBack(CacheItemArgs cacheItemArgs) { - Requires.NotNullOrEmpty("friendlyName", friendlyName); - - return (from kvp in GetModuleDefinitions() - where kvp.Value.FriendlyName == friendlyName - select kvp.Value) - .FirstOrDefault(); - } + return CBO.FillDictionary(key, dataProvider.GetModuleDefinitions(), new Dictionary()); + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs index ea664971cdc..f9106b2abd3 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs @@ -111,24 +111,6 @@ public Dictionary ModuleControls /// A String. /// ----------------------------------------------------------------------------- public Dictionary Permissions { get; private set; } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a ModuleDefinitionInfo from a Data Reader. - /// - /// The Data Reader to use. - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - this.ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); - this.DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); - this.DefaultCacheTime = Null.SetNullInteger(dr["DefaultCacheTime"]); - this.FriendlyName = Null.SetNullString(dr["FriendlyName"]); - if (dr.GetSchemaTable().Select("ColumnName = 'DefinitionName'").Length > 0) - { - this.DefinitionName = Null.SetNullString(dr["DefinitionName"]); - } - } /// ----------------------------------------------------------------------------- /// @@ -149,6 +131,24 @@ public int KeyID } } + /// ----------------------------------------------------------------------------- + /// + /// Fills a ModuleDefinitionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.ModuleDefID = Null.SetNullInteger(dr["ModuleDefID"]); + this.DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); + this.DefaultCacheTime = Null.SetNullInteger(dr["DefaultCacheTime"]); + this.FriendlyName = Null.SetNullString(dr["FriendlyName"]); + if (dr.GetSchemaTable().Select("ColumnName = 'DefinitionName'").Length > 0) + { + this.DefinitionName = Null.SetNullString(dr["DefinitionName"]); + } + } + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the ModuleDefinitionInfo. diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs index 276e6b6f96b..2f623a9b90d 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs @@ -24,42 +24,6 @@ public enum ModuleDefinitionVersion public class ModuleDefinitionValidator : XmlValidatorBase { - 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 Exception(GetLocalizedString("EXCEPTION_LoadFailed")); - } - - return Path.Combine(Globals.ApplicationMapPath, schemaPath); - } - - private static string GetLocalizedString(string key) - { - var objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; - if (objPortalSettings == null) - { - return key; - } - - return Localization.GetString(key, objPortalSettings); - } - public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) { ModuleDefinitionVersion retValue; @@ -119,5 +83,41 @@ 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 Exception(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 490cd0371e8..cf82a74dc5f 100644 --- a/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs @@ -40,59 +40,6 @@ public class DesktopModuleController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DesktopModuleController)); private static readonly DataProvider DataProvider = DataProvider.Instance(); - - private static Dictionary GetDesktopModulesInternal(int portalID) - { - string cacheKey = string.Format(DataCache.DesktopModuleCacheKey, portalID); - var args = new CacheItemArgs(cacheKey, DataCache.DesktopModuleCacheTimeOut, DataCache.DesktopModuleCachePriority, portalID); - Dictionary desktopModules = (portalID == Null.NullInteger) - ? CBO.GetCachedObject>(args, GetDesktopModulesCallBack) - : CBO.GetCachedObject>(args, GetDesktopModulesByPortalCallBack); - return desktopModules; - } - - private static object GetDesktopModulesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillDictionary("DesktopModuleID", DataProvider.GetDesktopModules(), new Dictionary()); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetDesktopModulesByPortalCallBack gets a Dictionary of Desktop Modules by - /// Portal from the the Database. - /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call. - /// ----------------------------------------------------------------------------- - private static object GetDesktopModulesByPortalCallBack(CacheItemArgs cacheItemArgs) - { - var portalId = (int)cacheItemArgs.ParamList[0]; - return CBO.FillDictionary("DesktopModuleID", DataProvider.GetDesktopModulesByPortal(portalId), new Dictionary()); - } - - private static object GetPortalDesktopModulesByPortalIDCallBack(CacheItemArgs cacheItemArgs) - { - var portalId = (int)cacheItemArgs.ParamList[0]; - return CBO.FillDictionary("PortalDesktopModuleID", DataProvider.Instance().GetPortalDesktopModules(portalId, Null.NullInteger), new Dictionary()); - } - - private static void CreateContentItem(DesktopModuleInfo desktopModule) - { - IContentTypeController typeController = new ContentTypeController(); - ContentType contentType = ContentType.DesktopModule; - - if (contentType == null) - { - contentType = new ContentType { ContentType = "DesktopModule" }; - contentType.ContentTypeId = typeController.AddContentType(contentType); - } - - IContentController contentController = Util.GetContentController(); - desktopModule.Content = desktopModule.FriendlyName; - desktopModule.Indexed = false; - desktopModule.ContentTypeId = contentType.ContentTypeId; - desktopModule.ContentItemId = contentController.AddContentItem(desktopModule); - } public static void AddModuleCategory(string category) { @@ -119,35 +66,6 @@ public static void AddModuleCategory(string category) } } - /// ----------------------------------------------------------------------------- - /// - /// DeleteDesktopModule deletes a Desktop Module. - /// - /// Desktop Module Info. - /// ----------------------------------------------------------------------------- - public void DeleteDesktopModule(DesktopModuleInfo objDesktopModule) - { - this.DeleteDesktopModule(objDesktopModule.DesktopModuleID); - } - - /// ----------------------------------------------------------------------------- - /// - /// DeleteDesktopModule deletes a Desktop Module By ID. - /// - /// The ID of the Desktop Module to delete. - /// ----------------------------------------------------------------------------- - public void DeleteDesktopModule(int desktopModuleID) - { - DataProvider.DeleteDesktopModule(desktopModuleID); - EventLogController.Instance.AddLog( - "DesktopModuleID", - desktopModuleID.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.DESKTOPMODULE_DELETED); - DataCache.ClearHostCache(true); - } - /// ----------------------------------------------------------------------------- /// /// DeleteDesktopModule deletes a Desktop Module. @@ -201,6 +119,88 @@ public static DesktopModuleInfo GetDesktopModule(int desktopModuleID, int portal return module; } + /// ----------------------------------------------------------------------------- + /// + /// DeleteDesktopModule deletes a Desktop Module. + /// + /// Desktop Module Info. + /// ----------------------------------------------------------------------------- + public void DeleteDesktopModule(DesktopModuleInfo objDesktopModule) + { + this.DeleteDesktopModule(objDesktopModule.DesktopModuleID); + } + + private static Dictionary GetDesktopModulesInternal(int portalID) + { + string cacheKey = string.Format(DataCache.DesktopModuleCacheKey, portalID); + var args = new CacheItemArgs(cacheKey, DataCache.DesktopModuleCacheTimeOut, DataCache.DesktopModuleCachePriority, portalID); + Dictionary desktopModules = (portalID == Null.NullInteger) + ? CBO.GetCachedObject>(args, GetDesktopModulesCallBack) + : CBO.GetCachedObject>(args, GetDesktopModulesByPortalCallBack); + return desktopModules; + } + + private static object GetDesktopModulesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillDictionary("DesktopModuleID", DataProvider.GetDesktopModules(), new Dictionary()); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetDesktopModulesByPortalCallBack gets a Dictionary of Desktop Modules by + /// Portal from the the Database. + /// + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. + /// ----------------------------------------------------------------------------- + private static object GetDesktopModulesByPortalCallBack(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + return CBO.FillDictionary("DesktopModuleID", DataProvider.GetDesktopModulesByPortal(portalId), new Dictionary()); + } + + private static object GetPortalDesktopModulesByPortalIDCallBack(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + return CBO.FillDictionary("PortalDesktopModuleID", DataProvider.Instance().GetPortalDesktopModules(portalId, Null.NullInteger), new Dictionary()); + } + + private static void CreateContentItem(DesktopModuleInfo desktopModule) + { + IContentTypeController typeController = new ContentTypeController(); + ContentType contentType = ContentType.DesktopModule; + + if (contentType == null) + { + contentType = new ContentType { ContentType = "DesktopModule" }; + contentType.ContentTypeId = typeController.AddContentType(contentType); + } + + IContentController contentController = Util.GetContentController(); + desktopModule.Content = desktopModule.FriendlyName; + desktopModule.Indexed = false; + desktopModule.ContentTypeId = contentType.ContentTypeId; + desktopModule.ContentItemId = contentController.AddContentItem(desktopModule); + } + + /// ----------------------------------------------------------------------------- + /// + /// DeleteDesktopModule deletes a Desktop Module By ID. + /// + /// The ID of the Desktop Module to delete. + /// ----------------------------------------------------------------------------- + public void DeleteDesktopModule(int desktopModuleID) + { + DataProvider.DeleteDesktopModule(desktopModuleID); + EventLogController.Instance.AddLog( + "DesktopModuleID", + desktopModuleID.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.DESKTOPMODULE_DELETED); + DataCache.ClearHostCache(true); + } + /// ----------------------------------------------------------------------------- /// /// GetDesktopModuleByPackageID gets a Desktop Module by its Package ID. @@ -286,6 +286,90 @@ public static int SaveDesktopModule(DesktopModuleInfo desktopModule, bool saveCh { return SaveDesktopModule(desktopModule, saveChildren, clearCache, true); } + + public static int AddDesktopModuleToPortal(int portalID, DesktopModuleInfo desktopModule, DesktopModulePermissionCollection permissions, bool clearCache) + { + int portalDesktopModuleID = AddDesktopModuleToPortal(portalID, desktopModule.DesktopModuleID, false, clearCache); + if (portalDesktopModuleID > Null.NullInteger) + { + DesktopModulePermissionController.DeleteDesktopModulePermissionsByPortalDesktopModuleID(portalDesktopModuleID); + foreach (DesktopModulePermissionInfo permission in permissions) + { + permission.PortalDesktopModuleID = portalDesktopModuleID; + DesktopModulePermissionController.AddDesktopModulePermission(permission); + } + } + + return portalDesktopModuleID; + } + + public static int AddDesktopModuleToPortal(int portalId, int desktopModuleId, bool addPermissions, bool clearCache) + { + int portalDesktopModuleID; + PortalDesktopModuleInfo portalDesktopModule = GetPortalDesktopModule(portalId, desktopModuleId); + if (portalDesktopModule == null) + { + portalDesktopModuleID = DataProvider.Instance().AddPortalDesktopModule(portalId, desktopModuleId, UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog( + "PortalDesktopModuleID", + portalDesktopModuleID.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTALDESKTOPMODULE_CREATED); + if (addPermissions) + { + ArrayList permissions = PermissionController.GetPermissionsByPortalDesktopModule(); + if (permissions.Count > 0) + { + var permission = permissions[0] as PermissionInfo; + PortalInfo objPortal = PortalController.Instance.GetPortal(portalId); + if (permission != null && objPortal != null) + { + var desktopModulePermission = new DesktopModulePermissionInfo(permission) { RoleID = objPortal.AdministratorRoleId, AllowAccess = true, PortalDesktopModuleID = portalDesktopModuleID }; + DesktopModulePermissionController.AddDesktopModulePermission(desktopModulePermission); + } + } + } + } + else + { + portalDesktopModuleID = portalDesktopModule.PortalDesktopModuleID; + } + + if (clearCache) + { + DataCache.ClearPortalCache(portalId, true); + } + + return portalDesktopModuleID; + } + + public void UpdateModuleInterfaces(ref DesktopModuleInfo desktopModuleInfo) + { + this.UpdateModuleInterfaces(ref desktopModuleInfo, (UserController.Instance.GetCurrentUserInfo() == null) ? string.Empty : UserController.Instance.GetCurrentUserInfo().Username, true); + } + + public void UpdateModuleInterfaces(ref DesktopModuleInfo desktopModuleInfo, string sender, bool forceAppRestart) + { + this.CheckInterfacesImplementation(ref desktopModuleInfo); + var oAppStartMessage = new EventMessage + { + Sender = sender, + Priority = MessagePriority.High, + ExpirationDate = DateTime.Now.AddYears(-1), + SentDate = DateTime.Now, + Body = string.Empty, + ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", + ProcessorCommand = "UpdateSupportedFeatures", + }; + oAppStartMessage.Attributes.Add("BusinessControllerClass", desktopModuleInfo.BusinessControllerClass); + oAppStartMessage.Attributes.Add("DesktopModuleId", desktopModuleInfo.DesktopModuleID.ToString()); + EventQueueController.SendMessage(oAppStartMessage, "Application_Start"); + if (forceAppRestart) + { + Config.Touch(); + } + } internal static int SaveDesktopModule(DesktopModuleInfo desktopModule, bool saveChildren, bool clearCache, bool saveTerms) { @@ -379,33 +463,6 @@ internal static int SaveDesktopModule(DesktopModuleInfo desktopModule, bool save return desktopModuleID; } - public void UpdateModuleInterfaces(ref DesktopModuleInfo desktopModuleInfo) - { - this.UpdateModuleInterfaces(ref desktopModuleInfo, (UserController.Instance.GetCurrentUserInfo() == null) ? string.Empty : UserController.Instance.GetCurrentUserInfo().Username, true); - } - - public void UpdateModuleInterfaces(ref DesktopModuleInfo desktopModuleInfo, string sender, bool forceAppRestart) - { - this.CheckInterfacesImplementation(ref desktopModuleInfo); - var oAppStartMessage = new EventMessage - { - Sender = sender, - Priority = MessagePriority.High, - ExpirationDate = DateTime.Now.AddYears(-1), - SentDate = DateTime.Now, - Body = string.Empty, - ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", - ProcessorCommand = "UpdateSupportedFeatures", - }; - oAppStartMessage.Attributes.Add("BusinessControllerClass", desktopModuleInfo.BusinessControllerClass); - oAppStartMessage.Attributes.Add("DesktopModuleId", desktopModuleInfo.DesktopModuleID.ToString()); - EventQueueController.SendMessage(oAppStartMessage, "Application_Start"); - if (forceAppRestart) - { - Config.Touch(); - } - } - private void CheckInterfacesImplementation(ref DesktopModuleInfo desktopModuleInfo) { var businessController = Reflection.CreateType(desktopModuleInfo.BusinessControllerClass); @@ -417,63 +474,6 @@ private void CheckInterfacesImplementation(ref DesktopModuleInfo desktopModuleIn #pragma warning restore 0618 desktopModuleInfo.IsUpgradeable = businessController.GetInterfaces().Contains(typeof(IUpgradeable)); } - - public static int AddDesktopModuleToPortal(int portalID, DesktopModuleInfo desktopModule, DesktopModulePermissionCollection permissions, bool clearCache) - { - int portalDesktopModuleID = AddDesktopModuleToPortal(portalID, desktopModule.DesktopModuleID, false, clearCache); - if (portalDesktopModuleID > Null.NullInteger) - { - DesktopModulePermissionController.DeleteDesktopModulePermissionsByPortalDesktopModuleID(portalDesktopModuleID); - foreach (DesktopModulePermissionInfo permission in permissions) - { - permission.PortalDesktopModuleID = portalDesktopModuleID; - DesktopModulePermissionController.AddDesktopModulePermission(permission); - } - } - - return portalDesktopModuleID; - } - - public static int AddDesktopModuleToPortal(int portalId, int desktopModuleId, bool addPermissions, bool clearCache) - { - int portalDesktopModuleID; - PortalDesktopModuleInfo portalDesktopModule = GetPortalDesktopModule(portalId, desktopModuleId); - if (portalDesktopModule == null) - { - portalDesktopModuleID = DataProvider.Instance().AddPortalDesktopModule(portalId, desktopModuleId, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog( - "PortalDesktopModuleID", - portalDesktopModuleID.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTALDESKTOPMODULE_CREATED); - if (addPermissions) - { - ArrayList permissions = PermissionController.GetPermissionsByPortalDesktopModule(); - if (permissions.Count > 0) - { - var permission = permissions[0] as PermissionInfo; - PortalInfo objPortal = PortalController.Instance.GetPortal(portalId); - if (permission != null && objPortal != null) - { - var desktopModulePermission = new DesktopModulePermissionInfo(permission) { RoleID = objPortal.AdministratorRoleId, AllowAccess = true, PortalDesktopModuleID = portalDesktopModuleID }; - DesktopModulePermissionController.AddDesktopModulePermission(desktopModulePermission); - } - } - } - } - else - { - portalDesktopModuleID = portalDesktopModule.PortalDesktopModuleID; - } - - if (clearCache) - { - DataCache.ClearPortalCache(portalId, true); - } - - return portalDesktopModuleID; - } public static void AddDesktopModuleToPortals(int desktopModuleId) { diff --git a/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs b/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs index 0b916b0e6bf..7b6676d4d14 100644 --- a/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs @@ -33,6 +33,20 @@ namespace DotNetNuke.Entities.Modules [Serializable] public class DesktopModuleInfo : ContentItem, IXmlSerializable { + private Dictionary _moduleDefinitions; + private PageInfo _pageInfo; + + public DesktopModuleInfo() + { + this.IsPremium = Null.NullBoolean; + this.IsAdmin = Null.NullBoolean; + this.CodeSubDirectory = Null.NullString; + this.PackageID = Null.NullInteger; + this.DesktopModuleID = Null.NullInteger; + this.SupportedFeatures = Null.NullInteger; + this.Shareable = ModuleSharing.Unknown; + } + [Serializable] public class PageInfo : IXmlSerializable { @@ -139,20 +153,6 @@ public void WriteXml(XmlWriter writer) } } - private Dictionary _moduleDefinitions; - private PageInfo _pageInfo; - - public DesktopModuleInfo() - { - this.IsPremium = Null.NullBoolean; - this.IsAdmin = Null.NullBoolean; - this.CodeSubDirectory = Null.NullString; - this.PackageID = Null.NullInteger; - this.DesktopModuleID = Null.NullInteger; - this.SupportedFeatures = Null.NullInteger; - this.Shareable = ModuleSharing.Unknown; - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the ID of the Desktop Module. diff --git a/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs b/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs index 87dff569331..bdb3fbd5839 100644 --- a/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs +++ b/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs @@ -17,6 +17,59 @@ namespace DotNetNuke.Entities.Modules public class EventMessageProcessor : EventMessageProcessorBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(EventMessageProcessor)); + + public static void CreateImportModuleMessage(ModuleInfo objModule, string content, string version, int userID) + { + var appStartMessage = new EventMessage + { + Priority = MessagePriority.High, + ExpirationDate = DateTime.Now.AddYears(-1), + SentDate = DateTime.Now, + Body = string.Empty, + ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", + ProcessorCommand = "ImportModule", + }; + + // Add custom Attributes for this message + appStartMessage.Attributes.Add("BusinessControllerClass", objModule.DesktopModule.BusinessControllerClass); + appStartMessage.Attributes.Add("ModuleId", objModule.ModuleID.ToString()); + appStartMessage.Attributes.Add("Content", content); + appStartMessage.Attributes.Add("Version", version); + appStartMessage.Attributes.Add("UserID", userID.ToString()); + + // send it to occur on next App_Start Event + EventQueueController.SendMessage(appStartMessage, "Application_Start_FirstRequest"); + } + + public override bool ProcessMessage(EventMessage message) + { + try + { + switch (message.ProcessorCommand) + { + case "UpdateSupportedFeatures": + UpdateSupportedFeatures(message); + break; + case "UpgradeModule": + UpgradeModule(message); + break; + case "ImportModule": + ImportModule(message); + break; + default: + // other events can be added here + break; + } + } + catch (Exception ex) + { + Logger.Error(ex); + message.ExceptionMessage = ex.Message; + return false; + } + + return true; + } private static void ImportModule(EventMessage message) { @@ -120,58 +173,5 @@ private static void UpdateSupportedFeatures(object objController, int desktopMod Exceptions.LogException(exc); } } - - public static void CreateImportModuleMessage(ModuleInfo objModule, string content, string version, int userID) - { - var appStartMessage = new EventMessage - { - Priority = MessagePriority.High, - ExpirationDate = DateTime.Now.AddYears(-1), - SentDate = DateTime.Now, - Body = string.Empty, - ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", - ProcessorCommand = "ImportModule", - }; - - // Add custom Attributes for this message - appStartMessage.Attributes.Add("BusinessControllerClass", objModule.DesktopModule.BusinessControllerClass); - appStartMessage.Attributes.Add("ModuleId", objModule.ModuleID.ToString()); - appStartMessage.Attributes.Add("Content", content); - appStartMessage.Attributes.Add("Version", version); - appStartMessage.Attributes.Add("UserID", userID.ToString()); - - // send it to occur on next App_Start Event - EventQueueController.SendMessage(appStartMessage, "Application_Start_FirstRequest"); - } - - public override bool ProcessMessage(EventMessage message) - { - try - { - switch (message.ProcessorCommand) - { - case "UpdateSupportedFeatures": - UpdateSupportedFeatures(message); - break; - case "UpgradeModule": - UpgradeModule(message); - break; - case "ImportModule": - ImportModule(message); - break; - default: - // other events can be added here - break; - } - } - catch (Exception ex) - { - Logger.Error(ex); - message.ExceptionMessage = ex.Message; - return false; - } - - return true; - } } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleControlController.cs b/DNN Platform/Library/Entities/Modules/ModuleControlController.cs index 8fadf22c06e..105d66e4ed5 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleControlController.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleControlController.cs @@ -27,6 +27,29 @@ public class ModuleControlController private const string key = "ModuleControlID"; private static readonly DataProvider dataProvider = DataProvider.Instance(); + /// ----------------------------------------------------------------------------- + /// + /// AddModuleControl adds a new Module Control to the database. + /// + /// The Module Control to save. + /// ----------------------------------------------------------------------------- + public static void AddModuleControl(ModuleControlInfo objModuleControl) + { + SaveModuleControl(objModuleControl, true); + } + + /// ----------------------------------------------------------------------------- + /// + /// DeleteModuleControl deletes a Module Control in the database. + /// + /// The ID of the Module Control to delete. + /// ----------------------------------------------------------------------------- + public static void DeleteModuleControl(int moduleControlID) + { + dataProvider.DeleteModuleControl(moduleControlID); + DataCache.ClearHostCache(true); + } + /// ----------------------------------------------------------------------------- /// /// GetModuleControls gets a Dictionary of Module Controls from @@ -56,29 +79,6 @@ private static object GetModuleControlsCallBack(CacheItemArgs cacheItemArgs) return CBO.FillDictionary(key, dataProvider.GetModuleControls(), new Dictionary()); } - /// ----------------------------------------------------------------------------- - /// - /// AddModuleControl adds a new Module Control to the database. - /// - /// The Module Control to save. - /// ----------------------------------------------------------------------------- - public static void AddModuleControl(ModuleControlInfo objModuleControl) - { - SaveModuleControl(objModuleControl, true); - } - - /// ----------------------------------------------------------------------------- - /// - /// DeleteModuleControl deletes a Module Control in the database. - /// - /// The ID of the Module Control to delete. - /// ----------------------------------------------------------------------------- - public static void DeleteModuleControl(int moduleControlID) - { - dataProvider.DeleteModuleControl(moduleControlID); - DataCache.ClearHostCache(true); - } - /// ----------------------------------------------------------------------------- /// /// GetModuleControl gets a single Module Control from the database. diff --git a/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs index 9a32b315be3..deb8d88bb88 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs @@ -95,6 +95,25 @@ public ModuleControlInfo() /// An Integer. /// ----------------------------------------------------------------------------- public int ViewOrder { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public int KeyID + { + get + { + return this.ModuleControlID; + } + + set + { + this.ModuleControlID = value; + } + } /// ----------------------------------------------------------------------------- /// @@ -117,25 +136,6 @@ public void Fill(IDataReader dr) // Call the base classes fill method to populate base class proeprties this.FillInternal(dr); } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Key ID. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - public int KeyID - { - get - { - return this.ModuleControlID; - } - - set - { - this.ModuleControlID = value; - } - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Entities/Modules/ModuleController.cs b/DNN Platform/Library/Entities/Modules/ModuleController.cs index d2dcaf978ce..b96d593cde3 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleController.cs @@ -46,6 +46,293 @@ public partial class ModuleController : ServiceLocator + /// Deserializes the module. + /// + /// The node module. + /// ModuleInfo of current module. + /// The portal id. + /// The tab id. + public static void DeserializeModule(XmlNode nodeModule, ModuleInfo module, int portalId, int tabId) + { + var moduleDefinition = GetModuleDefinition(nodeModule); + + // Create dummy pane node for private DeserializeModule method + var docPane = new XmlDocument { XmlResolver = null }; + docPane.LoadXml(string.Format("{0}", module.PaneName)); + + // Create ModuleInfo of Xml + ModuleInfo sourceModule = DeserializeModule(nodeModule, docPane.DocumentElement, portalId, tabId, moduleDefinition.ModuleDefID); + + // Copy properties from sourceModule to given (actual) module + module.ModuleTitle = sourceModule.ModuleTitle; + module.ModuleDefID = sourceModule.ModuleDefID; + module.CacheTime = sourceModule.CacheTime; + module.CacheMethod = sourceModule.CacheMethod; + module.Alignment = sourceModule.Alignment; + module.IconFile = sourceModule.IconFile; + module.AllTabs = sourceModule.AllTabs; + module.Visibility = sourceModule.Visibility; + module.Color = sourceModule.Color; + module.Border = sourceModule.Border; + module.Header = sourceModule.Header; + module.Footer = sourceModule.Footer; + module.InheritViewPermissions = sourceModule.InheritViewPermissions; + module.IsShareable = sourceModule.IsShareable; + module.IsShareableViewOnly = sourceModule.IsShareableViewOnly; + module.StartDate = sourceModule.StartDate; + module.EndDate = sourceModule.EndDate; + module.ContainerSrc = sourceModule.ContainerSrc; + module.DisplayTitle = sourceModule.DisplayTitle; + module.DisplayPrint = sourceModule.DisplayPrint; + module.DisplaySyndicate = sourceModule.DisplaySyndicate; + module.IsWebSlice = sourceModule.IsWebSlice; + + if (module.IsWebSlice) + { + module.WebSliceTitle = sourceModule.WebSliceTitle; + module.WebSliceExpiryDate = sourceModule.WebSliceExpiryDate; + module.WebSliceTTL = sourceModule.WebSliceTTL; + } + + // DNN-24983 get culture from page + var tabInfo = TabController.Instance.GetTab(tabId, portalId, false); + if (tabInfo != null) + { + module.CultureCode = tabInfo.CultureCode; + } + + // save changes + Instance.UpdateModule(module); + + // deserialize Module's settings + XmlNodeList nodeModuleSettings = nodeModule.SelectNodes("modulesettings/modulesetting"); + DeserializeModuleSettings(nodeModuleSettings, module); + + XmlNodeList nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/tabmodulesetting"); + DeserializeTabModuleSettings(nodeTabModuleSettings, module); + + // deserialize Content (if included) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "content"))) + { + GetModuleContent(nodeModule, module.ModuleID, tabId, portalId); + } + + // deserialize Permissions + XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); + DeserializeModulePermissions(nodeModulePermissions, portalId, module); + + // Persist the permissions to the Data base + ModulePermissionController.SaveModulePermissions(module); + } + + /// + /// Deserializes the module. + /// + /// The node module. + /// The node pane. + /// The portal id. + /// The tab id. + /// The merge tabs. + /// The modules. + public static void DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, PortalTemplateModuleAction mergeTabs, Hashtable hModules) + { + var moduleDefinition = GetModuleDefinition(nodeModule); + + // will be instance or module? + int templateModuleID = XmlUtils.GetNodeValueInt(nodeModule, "moduleID"); + bool isInstance = CheckIsInstance(templateModuleID, hModules); + if (moduleDefinition != null) + { + // If Mode is Merge Check if Module exists + if (!FindModule(nodeModule, tabId, mergeTabs)) + { + ModuleInfo module = DeserializeModule(nodeModule, nodePane, portalId, tabId, moduleDefinition.ModuleDefID); + + // if the module is marked as show on all tabs, then check whether the module is exist in current website and it also + // still marked as shown on all tabs, this action will make sure there is no duplicate modules created on new tab. + if (module.AllTabs) + { + var existModule = Instance.GetModule(templateModuleID, Null.NullInteger, false); + if (existModule != null && !existModule.IsDeleted && existModule.AllTabs && existModule.PortalID == portalId) + { + return; + } + } + + // deserialize Module's settings + XmlNodeList nodeModuleSettings = nodeModule.SelectNodes("modulesettings/modulesetting"); + DeserializeModuleSettings(nodeModuleSettings, module); + XmlNodeList nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/tabmodulesetting"); + DeserializeTabModuleSettings(nodeTabModuleSettings, module); + + // DNN-24983 get culture from page + var tabInfo = TabController.Instance.GetTab(tabId, portalId, false); + if (tabInfo != null) + { + module.CultureCode = tabInfo.CultureCode; + } + + int intModuleId; + if (!isInstance) + { + // Add new module + intModuleId = Instance.AddModule(module); + if (templateModuleID > 0) + { + hModules.Add(templateModuleID, intModuleId); + } + } + else + { + // Add instance + module.ModuleID = Convert.ToInt32(hModules[templateModuleID]); + intModuleId = Instance.AddModule(module); + } + + // save localization info + string oldGuid = XmlUtils.GetNodeValue(nodeModule, "uniqueId"); + if (!ParsedLocalizedModuleGuid.ContainsKey(oldGuid)) + { + ParsedLocalizedModuleGuid.Add(oldGuid, module.UniqueId.ToString()); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "content")) && !isInstance) + { + GetModuleContent(nodeModule, intModuleId, tabId, portalId); + } + + // Process permissions only once + if (!isInstance && portalId != Null.NullInteger) + { + XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); + DeserializeModulePermissions(nodeModulePermissions, portalId, module); + + // Persist the permissions to the Data base + ModulePermissionController.SaveModulePermissions(module); + } + } + } + } + + /// + /// 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. + public bool IsSharedModule(ModuleInfo module) + { + var contentController = Util.GetContentController(); + var content = contentController.GetContentItem(module.ContentItemId); + return module.TabID != content.TabID; + } + + /// + /// 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. + public int GetMasterTabId(ModuleInfo module) + { + var contentController = Util.GetContentController(); + var content = contentController.GetContentItem(module.ContentItemId); + return content.TabID; + } + + internal Hashtable GetModuleSettings(int moduleId, int tabId) + { + string cacheKey = string.Format(DataCache.ModuleSettingsCacheKey, tabId); + + var moduleSettings = CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.ModuleCacheTimeOut, + DataCache.ModuleCachePriority), + c => + { + var moduleSettingsDic = new Dictionary(); + IDataReader dr = DataProvider.Instance().GetModuleSettingsByTab(tabId); + while (dr.Read()) + { + int mId = dr.GetInt32(0); + Hashtable settings; + if (!moduleSettingsDic.TryGetValue(mId, out settings)) + { + settings = new Hashtable(); + moduleSettingsDic[mId] = settings; + } + + if (!dr.IsDBNull(2)) + { + settings[dr.GetString(1)] = dr.GetString(2); + } + else + { + settings[dr.GetString(1)] = string.Empty; + } + } + + CBO.CloseDataReader(dr, true); + return moduleSettingsDic; + }); + + return moduleSettings.ContainsKey(moduleId) ? moduleSettings[moduleId] : new Hashtable(); + } + + internal Hashtable GetTabModuleSettings(int tabmoduleId, int tabId) + { + string cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tabId); + + var tabModuleSettings = CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.TabModuleCacheTimeOut, + DataCache.TabModuleCachePriority), + c => + { + var tabModuleSettingsDic = new Dictionary(); + using (IDataReader dr = DataProvider.Instance().GetTabModuleSettingsByTab(tabId)) + { + while (dr.Read()) + { + int tMId = dr.GetInt32(0); + Hashtable settings; + if (!tabModuleSettingsDic.TryGetValue(tMId, out settings)) + { + settings = new Hashtable(); + tabModuleSettingsDic[tMId] = settings; + } + + if (!dr.IsDBNull(2)) + { + settings[dr.GetString(1)] = dr.GetString(2); + } + else + { + settings[dr.GetString(1)] = string.Empty; + } + } + } + + return tabModuleSettingsDic; + }); + + return tabModuleSettings.ContainsKey(tabmoduleId) ? tabModuleSettings[tabmoduleId] : new Hashtable(); + } + protected override Func GetFactory() { return () => new ModuleController(); @@ -104,44 +391,6 @@ private static void AddContent(XmlNode nodeModule, ModuleInfo module) } } - private void AddModuleInternal(ModuleInfo module) - { - // add module - if (Null.IsNull(module.ModuleID)) - { - var currentUser = UserController.Instance.GetCurrentUserInfo(); - this.CreateContentItem(module); - - // Add Module - module.ModuleID = dataProvider.AddModule( - module.ContentItemId, - module.PortalID, - module.ModuleDefID, - module.AllTabs, - module.StartDate, - module.EndDate, - module.InheritViewPermissions, - module.IsShareable, - module.IsShareableViewOnly, - module.IsDeleted, - currentUser.UserID); - - // Now we have the ModuleID - update the contentItem - var contentController = Util.GetContentController(); - contentController.UpdateContentItem(module); - - EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.MODULE_CREATED); - - // set module permissions - ModulePermissionController.SaveModulePermissions(module); - } - - // Save ModuleSettings - this.UpdateModuleSettings(module); - - EventManager.Instance.OnModuleCreated(new ModuleEventArgs { Module = module }); - } - private static void AddModulePermission(ref ModuleInfo module, int portalId, string roleName, PermissionInfo permission, string permissionKey) { var perm = module.ModulePermissions.Where(tp => tp.RoleName == roleName && tp.PermissionKey == permissionKey).SingleOrDefault(); @@ -149,10 +398,10 @@ private static void AddModulePermission(ref ModuleInfo module, int portalId, str { var modulePermission = new ModulePermissionInfo(permission); -// ReSharper disable ImplicitlyCapturedClosure + // ReSharper disable ImplicitlyCapturedClosure var role = RoleController.Instance.GetRole(portalId, r => (r.RoleName == roleName)); -// ReSharper restore ImplicitlyCapturedClosure + // ReSharper restore ImplicitlyCapturedClosure if (role != null) { modulePermission.RoleID = role.RoleID; @@ -163,27 +412,6 @@ private static void AddModulePermission(ref ModuleInfo module, int portalId, str } } - private ModulePermissionInfo AddModulePermission(ModuleInfo module, PermissionInfo permission, int roleId, int userId, bool allowAccess) - { - var modulePermission = new ModulePermissionInfo - { - ModuleID = module.ModuleID, - PermissionID = permission.PermissionID, - RoleID = roleId, - UserID = userId, - PermissionKey = permission.PermissionKey, - AllowAccess = allowAccess, - }; - - // add the permission to the collection - if (!module.ModulePermissions.Contains(modulePermission)) - { - module.ModulePermissions.Add(modulePermission); - } - - return modulePermission; - } - private static bool CheckIsInstance(int templateModuleID, Hashtable hModules) { // will be instance or module? @@ -209,113 +437,79 @@ private static void ClearModuleSettingsCache(int moduleId) } } - private static void ClearTabModuleSettingsCache(int tabModuleId, string settingName) - { - var portalId = -1; - foreach (var tab in TabController.Instance.GetTabsByTabModuleID(tabModuleId).Values) - { - var cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tab.TabID); - DataCache.RemoveCache(cacheKey); - - if (portalId != tab.PortalID) - { - portalId = tab.PortalID; - cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName ?? string.Empty); - DataCache.RemoveCache(cacheKey); - } - } - } - - private void CopyTabModuleSettingsInternal(ModuleInfo fromModule, ModuleInfo toModule) + private void AddModuleInternal(ModuleInfo module) { - // Copy each setting to the new TabModule instance - foreach (DictionaryEntry setting in fromModule.TabModuleSettings) + // add module + if (Null.IsNull(module.ModuleID)) { - this.UpdateTabModuleSetting(toModule.TabModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); - } - } + var currentUser = UserController.Instance.GetCurrentUserInfo(); + this.CreateContentItem(module); - /// - /// Checks whether module VIEW permission is inherited from its tab. - /// - /// The module. - /// The module permission. - private bool IsModuleViewPermissionInherited(ModuleInfo module, ModulePermissionInfo permission) - { - Requires.NotNull(module); + // Add Module + module.ModuleID = dataProvider.AddModule( + module.ContentItemId, + module.PortalID, + module.ModuleDefID, + module.AllTabs, + module.StartDate, + module.EndDate, + module.InheritViewPermissions, + module.IsShareable, + module.IsShareableViewOnly, + module.IsDeleted, + currentUser.UserID); - Requires.NotNull(permission); + // Now we have the ModuleID - update the contentItem + var contentController = Util.GetContentController(); + contentController.UpdateContentItem(module); - var permissionViewKey = "VIEW"; + EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.MODULE_CREATED); - if (!module.InheritViewPermissions || permission.PermissionKey != permissionViewKey) - { - return false; + // set module permissions + ModulePermissionController.SaveModulePermissions(module); } - var tabPermissions = TabPermissionController.GetTabPermissions(module.TabID, module.PortalID); + // Save ModuleSettings + this.UpdateModuleSettings(module); - return tabPermissions?.Where(x => x.RoleID == permission.RoleID && x.PermissionKey == permissionViewKey).Any() == true; + EventManager.Instance.OnModuleCreated(new ModuleEventArgs { Module = module }); } - /// - /// Checks whether given permission is granted for translator role. - /// - /// The module permission. - /// The portal ID. - /// The culture code. - private bool IsTranslatorRolePermission(ModulePermissionInfo permission, int portalId, string culture) + private ModulePermissionInfo AddModulePermission(ModuleInfo module, PermissionInfo permission, int roleId, int userId, bool allowAccess) { - Requires.NotNull(permission); + var modulePermission = new ModulePermissionInfo + { + ModuleID = module.ModuleID, + PermissionID = permission.PermissionID, + RoleID = roleId, + UserID = userId, + PermissionKey = permission.PermissionKey, + AllowAccess = allowAccess, + }; - if (string.IsNullOrWhiteSpace(culture) || portalId == Null.NullInteger) + // add the permission to the collection + if (!module.ModulePermissions.Contains(modulePermission)) { - return false; + module.ModulePermissions.Add(modulePermission); } - var translatorSettingKey = $"DefaultTranslatorRoles-{culture}"; - - var translatorSettingValue = - PortalController.GetPortalSetting(translatorSettingKey, portalId, null) ?? - HostController.Instance.GetString(translatorSettingKey, null); - - var translatorRoles = - translatorSettingValue?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - - return translatorRoles?.Any(r => r.Equals(permission.RoleName, StringComparison.OrdinalIgnoreCase)) == true; + return modulePermission; } - /// - /// Copies permissions from source to new tab. - /// - /// Source module. - /// New module. - private void CopyModulePermisions(ModuleInfo sourceModule, ModuleInfo newModule) + private static void ClearTabModuleSettingsCache(int tabModuleId, string settingName) { - Requires.NotNull(sourceModule); - - Requires.NotNull(newModule); - - foreach (ModulePermissionInfo permission in sourceModule.ModulePermissions) + var portalId = -1; + foreach (var tab in TabController.Instance.GetTabsByTabModuleID(tabModuleId).Values) { - // skip inherited view and translator permissions - if (this.IsModuleViewPermissionInherited(newModule, permission) || - this.IsTranslatorRolePermission(permission, sourceModule.PortalID, sourceModule.CultureCode)) + var cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tab.TabID); + DataCache.RemoveCache(cacheKey); + + if (portalId != tab.PortalID) { - continue; + portalId = tab.PortalID; + cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName ?? string.Empty); + DataCache.RemoveCache(cacheKey); } - - // need to force vew permission to be copied - permission.PermissionKey = newModule.InheritViewPermissions && permission.PermissionKey == "VIEW" ? - null : - permission.PermissionKey; - - this.AddModulePermission( - newModule, - permission, - permission.RoleID, - permission.UserID, - permission.AllowAccess); } } @@ -453,6 +647,99 @@ private static void DeserializeModulePermissions(XmlNodeList nodeModulePermissio } } + private void CopyTabModuleSettingsInternal(ModuleInfo fromModule, ModuleInfo toModule) + { + // 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)); + } + } + + /// + /// Checks whether module VIEW permission is inherited from its tab. + /// + /// The module. + /// The module permission. + private bool IsModuleViewPermissionInherited(ModuleInfo module, ModulePermissionInfo permission) + { + Requires.NotNull(module); + + Requires.NotNull(permission); + + var permissionViewKey = "VIEW"; + + if (!module.InheritViewPermissions || permission.PermissionKey != permissionViewKey) + { + return false; + } + + var tabPermissions = TabPermissionController.GetTabPermissions(module.TabID, module.PortalID); + + return tabPermissions?.Where(x => x.RoleID == permission.RoleID && x.PermissionKey == permissionViewKey).Any() == true; + } + + /// + /// Checks whether given permission is granted for translator role. + /// + /// The module permission. + /// The portal ID. + /// The culture code. + private bool IsTranslatorRolePermission(ModulePermissionInfo permission, int portalId, string culture) + { + Requires.NotNull(permission); + + if (string.IsNullOrWhiteSpace(culture) || portalId == Null.NullInteger) + { + return false; + } + + var translatorSettingKey = $"DefaultTranslatorRoles-{culture}"; + + var translatorSettingValue = + PortalController.GetPortalSetting(translatorSettingKey, portalId, null) ?? + HostController.Instance.GetString(translatorSettingKey, null); + + var translatorRoles = + translatorSettingValue?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + + return translatorRoles?.Any(r => r.Equals(permission.RoleName, StringComparison.OrdinalIgnoreCase)) == true; + } + + /// + /// Copies permissions from source to new tab. + /// + /// Source module. + /// New module. + private void CopyModulePermisions(ModuleInfo sourceModule, ModuleInfo newModule) + { + Requires.NotNull(sourceModule); + + Requires.NotNull(newModule); + + foreach (ModulePermissionInfo permission in sourceModule.ModulePermissions) + { + // skip inherited view and translator permissions + if (this.IsModuleViewPermissionInherited(newModule, permission) || + this.IsTranslatorRolePermission(permission, sourceModule.PortalID, sourceModule.CultureCode)) + { + continue; + } + + // need to force vew permission to be copied + permission.PermissionKey = newModule.InheritViewPermissions && permission.PermissionKey == "VIEW" ? + null : + permission.PermissionKey; + + this.AddModulePermission( + newModule, + permission, + permission.RoleID, + permission.UserID, + permission.AllowAccess); + } + } + private static void DeserializeModuleSettings(XmlNodeList nodeModuleSettings, ModuleInfo objModule) { foreach (XmlNode moduleSettingNode in nodeModuleSettings) @@ -576,85 +863,16 @@ private static ModuleDefinitionInfo GetModuleDefinition(XmlNode nodeModule) return moduleDefinition; } - internal Hashtable GetModuleSettings(int moduleId, int tabId) - { - string cacheKey = string.Format(DataCache.ModuleSettingsCacheKey, tabId); - - var moduleSettings = CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - DataCache.ModuleCacheTimeOut, - DataCache.ModuleCachePriority), - c => - { - var moduleSettingsDic = new Dictionary(); - IDataReader dr = DataProvider.Instance().GetModuleSettingsByTab(tabId); - while (dr.Read()) - { - int mId = dr.GetInt32(0); - Hashtable settings; - if (!moduleSettingsDic.TryGetValue(mId, out settings)) - { - settings = new Hashtable(); - moduleSettingsDic[mId] = settings; - } - - if (!dr.IsDBNull(2)) - { - settings[dr.GetString(1)] = dr.GetString(2); - } - else - { - settings[dr.GetString(1)] = string.Empty; - } - } - - CBO.CloseDataReader(dr, true); - return moduleSettingsDic; - }); - - return moduleSettings.ContainsKey(moduleId) ? moduleSettings[moduleId] : new Hashtable(); - } - - internal Hashtable GetTabModuleSettings(int tabmoduleId, int tabId) - { - string cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tabId); - - var tabModuleSettings = CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - DataCache.TabModuleCacheTimeOut, - DataCache.TabModuleCachePriority), - c => - { - var tabModuleSettingsDic = new Dictionary(); - using (IDataReader dr = DataProvider.Instance().GetTabModuleSettingsByTab(tabId)) - { - while (dr.Read()) - { - int tMId = dr.GetInt32(0); - Hashtable settings; - if (!tabModuleSettingsDic.TryGetValue(tMId, out settings)) - { - settings = new Hashtable(); - tabModuleSettingsDic[tMId] = settings; - } - - if (!dr.IsDBNull(2)) - { - settings[dr.GetString(1)] = dr.GetString(2); - } - else - { - settings[dr.GetString(1)] = string.Empty; - } - } - } - - return tabModuleSettingsDic; - }); + private static void SetCloneModuleContext(bool cloneModuleContext) + { + Thread.SetData( + Thread.GetNamedDataSlot("CloneModuleContext"), + cloneModuleContext ? bool.TrueString : bool.FalseString); + } - return tabModuleSettings.ContainsKey(tabmoduleId) ? tabModuleSettings[tabmoduleId] : new Hashtable(); + private static void UpdateTabModuleVersion(int tabModuleId) + { + dataProvider.UpdateTabModuleVersion(tabModuleId, Guid.NewGuid()); } private int LocalizeModuleInternal(ModuleInfo sourceModule) @@ -786,26 +1004,6 @@ private int LocalizeModuleInternal(ModuleInfo sourceModule) return moduleId; } - private static void SetCloneModuleContext(bool cloneModuleContext) - { - Thread.SetData( - Thread.GetNamedDataSlot("CloneModuleContext"), - cloneModuleContext ? bool.TrueString : bool.FalseString); - } - - private static Hashtable ParsedLocalizedModuleGuid - { - get - { - if (HttpContext.Current.Items["ParsedLocalizedModuleGuid"] == null) - { - HttpContext.Current.Items["ParsedLocalizedModuleGuid"] = new Hashtable(); - } - - return (Hashtable)HttpContext.Current.Items["ParsedLocalizedModuleGuid"]; - } - } - private void UpdateModuleSettingInternal(int moduleId, string settingName, string settingValue, bool updateVersion) { IDataReader dr = null; @@ -879,11 +1077,6 @@ private void UpdateTabModuleSettings(ModuleInfo updatedTabModule) } } - private static void UpdateTabModuleVersion(int tabModuleId) - { - dataProvider.UpdateTabModuleVersion(tabModuleId, Guid.NewGuid()); - } - private void UpdateTabModuleVersionsByModuleID(int moduleID) { // Update the version guid of each TabModule linked to the updated module @@ -959,30 +1152,6 @@ private void UpdateContentItem(ModuleInfo module) } } - /// - /// 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. - public bool IsSharedModule(ModuleInfo module) - { - var contentController = Util.GetContentController(); - var content = contentController.GetContentItem(module.ContentItemId); - return module.TabID != content.TabID; - } - - /// - /// 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. - public int GetMasterTabId(ModuleInfo module) - { - var contentController = Util.GetContentController(); - var content = contentController.GetContentItem(module.ContentItemId); - return content.TabID; - } - /// /// add a module to a page. /// @@ -1776,19 +1945,6 @@ public Dictionary GetTabModules(int tabId) c => this.GetModulesCurrentPage(tabId)); } - private Dictionary GetModulesCurrentPage(int tabId) - { - var modules = CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); - - var dictionary = new Dictionary(); - foreach (var module in modules) - { - dictionary[module.ModuleID] = module; - } - - return dictionary; - } - /// /// Get a list of all TabModule references of a module instance. /// @@ -1860,6 +2016,19 @@ public void InitialModulePermission(ModuleInfo module, int tabId, int permission } } + private Dictionary GetModulesCurrentPage(int tabId) + { + var modules = CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); + + var dictionary = new Dictionary(); + foreach (var module in modules) + { + dictionary[module.ModuleID] = module; + } + + return dictionary; + } + public void LocalizeModule(ModuleInfo sourceModule, Locale locale) { try @@ -2327,175 +2496,6 @@ public void UpdateTranslationStatus(ModuleInfo localizedModule, bool isTranslate this.ClearCache(localizedModule.TabID); } - /// - /// Deserializes the module. - /// - /// The node module. - /// ModuleInfo of current module. - /// The portal id. - /// The tab id. - public static void DeserializeModule(XmlNode nodeModule, ModuleInfo module, int portalId, int tabId) - { - var moduleDefinition = GetModuleDefinition(nodeModule); - - // Create dummy pane node for private DeserializeModule method - var docPane = new XmlDocument { XmlResolver = null }; - docPane.LoadXml(string.Format("{0}", module.PaneName)); - - // Create ModuleInfo of Xml - ModuleInfo sourceModule = DeserializeModule(nodeModule, docPane.DocumentElement, portalId, tabId, moduleDefinition.ModuleDefID); - - // Copy properties from sourceModule to given (actual) module - module.ModuleTitle = sourceModule.ModuleTitle; - module.ModuleDefID = sourceModule.ModuleDefID; - module.CacheTime = sourceModule.CacheTime; - module.CacheMethod = sourceModule.CacheMethod; - module.Alignment = sourceModule.Alignment; - module.IconFile = sourceModule.IconFile; - module.AllTabs = sourceModule.AllTabs; - module.Visibility = sourceModule.Visibility; - module.Color = sourceModule.Color; - module.Border = sourceModule.Border; - module.Header = sourceModule.Header; - module.Footer = sourceModule.Footer; - module.InheritViewPermissions = sourceModule.InheritViewPermissions; - module.IsShareable = sourceModule.IsShareable; - module.IsShareableViewOnly = sourceModule.IsShareableViewOnly; - module.StartDate = sourceModule.StartDate; - module.EndDate = sourceModule.EndDate; - module.ContainerSrc = sourceModule.ContainerSrc; - module.DisplayTitle = sourceModule.DisplayTitle; - module.DisplayPrint = sourceModule.DisplayPrint; - module.DisplaySyndicate = sourceModule.DisplaySyndicate; - module.IsWebSlice = sourceModule.IsWebSlice; - - if (module.IsWebSlice) - { - module.WebSliceTitle = sourceModule.WebSliceTitle; - module.WebSliceExpiryDate = sourceModule.WebSliceExpiryDate; - module.WebSliceTTL = sourceModule.WebSliceTTL; - } - - // DNN-24983 get culture from page - var tabInfo = TabController.Instance.GetTab(tabId, portalId, false); - if (tabInfo != null) - { - module.CultureCode = tabInfo.CultureCode; - } - - // save changes - Instance.UpdateModule(module); - - // deserialize Module's settings - XmlNodeList nodeModuleSettings = nodeModule.SelectNodes("modulesettings/modulesetting"); - DeserializeModuleSettings(nodeModuleSettings, module); - - XmlNodeList nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/tabmodulesetting"); - DeserializeTabModuleSettings(nodeTabModuleSettings, module); - - // deserialize Content (if included) - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "content"))) - { - GetModuleContent(nodeModule, module.ModuleID, tabId, portalId); - } - - // deserialize Permissions - XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); - DeserializeModulePermissions(nodeModulePermissions, portalId, module); - - // Persist the permissions to the Data base - ModulePermissionController.SaveModulePermissions(module); - } - - /// - /// Deserializes the module. - /// - /// The node module. - /// The node pane. - /// The portal id. - /// The tab id. - /// The merge tabs. - /// The modules. - public static void DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, PortalTemplateModuleAction mergeTabs, Hashtable hModules) - { - var moduleDefinition = GetModuleDefinition(nodeModule); - - // will be instance or module? - int templateModuleID = XmlUtils.GetNodeValueInt(nodeModule, "moduleID"); - bool isInstance = CheckIsInstance(templateModuleID, hModules); - if (moduleDefinition != null) - { - // If Mode is Merge Check if Module exists - if (!FindModule(nodeModule, tabId, mergeTabs)) - { - ModuleInfo module = DeserializeModule(nodeModule, nodePane, portalId, tabId, moduleDefinition.ModuleDefID); - - // if the module is marked as show on all tabs, then check whether the module is exist in current website and it also - // still marked as shown on all tabs, this action will make sure there is no duplicate modules created on new tab. - if (module.AllTabs) - { - var existModule = Instance.GetModule(templateModuleID, Null.NullInteger, false); - if (existModule != null && !existModule.IsDeleted && existModule.AllTabs && existModule.PortalID == portalId) - { - return; - } - } - - // deserialize Module's settings - XmlNodeList nodeModuleSettings = nodeModule.SelectNodes("modulesettings/modulesetting"); - DeserializeModuleSettings(nodeModuleSettings, module); - XmlNodeList nodeTabModuleSettings = nodeModule.SelectNodes("tabmodulesettings/tabmodulesetting"); - DeserializeTabModuleSettings(nodeTabModuleSettings, module); - - // DNN-24983 get culture from page - var tabInfo = TabController.Instance.GetTab(tabId, portalId, false); - if (tabInfo != null) - { - module.CultureCode = tabInfo.CultureCode; - } - - int intModuleId; - if (!isInstance) - { - // Add new module - intModuleId = Instance.AddModule(module); - if (templateModuleID > 0) - { - hModules.Add(templateModuleID, intModuleId); - } - } - else - { - // Add instance - module.ModuleID = Convert.ToInt32(hModules[templateModuleID]); - intModuleId = Instance.AddModule(module); - } - - // save localization info - string oldGuid = XmlUtils.GetNodeValue(nodeModule, "uniqueId"); - if (!ParsedLocalizedModuleGuid.ContainsKey(oldGuid)) - { - ParsedLocalizedModuleGuid.Add(oldGuid, module.UniqueId.ToString()); - } - - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "content")) && !isInstance) - { - GetModuleContent(nodeModule, intModuleId, tabId, portalId); - } - - // Process permissions only once - if (!isInstance && portalId != Null.NullInteger) - { - XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission"); - DeserializeModulePermissions(nodeModulePermissions, portalId, module); - - // Persist the permissions to the Data base - ModulePermissionController.SaveModulePermissions(module); - } - } - } - } - /// /// SerializeModule. /// diff --git a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs index d1dcaf6bf9c..b2437dedddd 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs @@ -515,6 +515,34 @@ public TabInfo ParentTab } } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + [XmlIgnore] + public override int KeyID + { + get + { + return this.ModuleID; + } + + set + { + this.ModuleID = value; + } + } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + /// ----------------------------------------------------------------------------- /// /// Fills a ModuleInfo from a Data Reader. @@ -612,26 +640,6 @@ public override void Fill(IDataReader dr) } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Key ID. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - [XmlIgnore] - public override int KeyID - { - get - { - return this.ModuleID; - } - - set - { - this.ModuleID = value; - } - } - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { string outputFormat = string.Empty; @@ -944,65 +952,57 @@ public string GetProperty(string propertyName, string format, CultureInfo format return result; } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } public ModuleInfo Clone() { - var objModuleInfo = new ModuleInfo - { - PortalID = this.PortalID, - OwnerPortalID = this.OwnerPortalID, - TabID = this.TabID, - TabModuleID = this.TabModuleID, - ModuleID = this.ModuleID, - ModuleOrder = this.ModuleOrder, - PaneName = this.PaneName, - ModuleTitle = this.ModuleTitle, - CacheTime = this.CacheTime, - CacheMethod = this.CacheMethod, - Alignment = this.Alignment, - Color = this.Color, - Border = this.Border, - IconFile = this.IconFile, - AllTabs = this.AllTabs, - Visibility = this.Visibility, - IsDeleted = this.IsDeleted, - Header = this.Header, - Footer = this.Footer, - StartDate = this.StartDate, - EndDate = this.EndDate, - ContainerSrc = this.ContainerSrc, - DisplayTitle = this.DisplayTitle, - DisplayPrint = this.DisplayPrint, - DisplaySyndicate = this.DisplaySyndicate, - IsWebSlice = this.IsWebSlice, - WebSliceTitle = this.WebSliceTitle, - WebSliceExpiryDate = this.WebSliceExpiryDate, - WebSliceTTL = this.WebSliceTTL, - InheritViewPermissions = this.InheritViewPermissions, - IsShareable = this.IsShareable, - IsShareableViewOnly = this.IsShareableViewOnly, - DesktopModuleID = this.DesktopModuleID, - ModuleDefID = this.ModuleDefID, - ModuleControlId = this.ModuleControlId, - ContainerPath = this.ContainerPath, - PaneModuleIndex = this.PaneModuleIndex, - PaneModuleCount = this.PaneModuleCount, - IsDefaultModule = this.IsDefaultModule, - AllModules = this.AllModules, - UniqueId = Guid.NewGuid(), - VersionGuid = Guid.NewGuid(), - DefaultLanguageGuid = this.DefaultLanguageGuid, - LocalizedVersionGuid = this.LocalizedVersionGuid, - CultureCode = this.CultureCode, - }; + var objModuleInfo = new ModuleInfo + { + PortalID = this.PortalID, + OwnerPortalID = this.OwnerPortalID, + TabID = this.TabID, + TabModuleID = this.TabModuleID, + ModuleID = this.ModuleID, + ModuleOrder = this.ModuleOrder, + PaneName = this.PaneName, + ModuleTitle = this.ModuleTitle, + CacheTime = this.CacheTime, + CacheMethod = this.CacheMethod, + Alignment = this.Alignment, + Color = this.Color, + Border = this.Border, + IconFile = this.IconFile, + AllTabs = this.AllTabs, + Visibility = this.Visibility, + IsDeleted = this.IsDeleted, + Header = this.Header, + Footer = this.Footer, + StartDate = this.StartDate, + EndDate = this.EndDate, + ContainerSrc = this.ContainerSrc, + DisplayTitle = this.DisplayTitle, + DisplayPrint = this.DisplayPrint, + DisplaySyndicate = this.DisplaySyndicate, + IsWebSlice = this.IsWebSlice, + WebSliceTitle = this.WebSliceTitle, + WebSliceExpiryDate = this.WebSliceExpiryDate, + WebSliceTTL = this.WebSliceTTL, + InheritViewPermissions = this.InheritViewPermissions, + IsShareable = this.IsShareable, + IsShareableViewOnly = this.IsShareableViewOnly, + DesktopModuleID = this.DesktopModuleID, + ModuleDefID = this.ModuleDefID, + ModuleControlId = this.ModuleControlId, + ContainerPath = this.ContainerPath, + PaneModuleIndex = this.PaneModuleIndex, + PaneModuleCount = this.PaneModuleCount, + IsDefaultModule = this.IsDefaultModule, + AllModules = this.AllModules, + UniqueId = Guid.NewGuid(), + VersionGuid = Guid.NewGuid(), + DefaultLanguageGuid = this.DefaultLanguageGuid, + LocalizedVersionGuid = this.LocalizedVersionGuid, + CultureCode = this.CultureCode, + }; // localized properties this.Clone(objModuleInfo, this); diff --git a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs index 5c0c27105cd..05e5eac65d7 100644 --- a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs @@ -45,15 +45,6 @@ public class PortalModuleBase : UserControlBase, IModuleControl private string _localResourceFile; private ModuleInstanceContext _moduleContext; - /// - /// Gets the Dependency Provider to resolve registered - /// services with the container. - /// - /// - /// The Dependency Service. - /// - protected IServiceProvider DependencyProvider { get; } - public PortalModuleBase() { this.DependencyProvider = Globals.DependencyProvider; @@ -84,6 +75,15 @@ public Control ContainerControl } } + /// + /// Gets the Dependency Provider to resolve registered + /// services with the container. + /// + /// + /// The Dependency Service. + /// + protected IServiceProvider DependencyProvider { get; } + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether the EditMode property is used to determine whether the user is in the @@ -319,6 +319,71 @@ public ModuleInstanceContext ModuleContext } } + // CONVERSION: Remove obsoleted methods (FYI some core modules use these, such as Links) + + /// ----------------------------------------------------------------------------- + /// + /// Gets the CacheDirectory property is used to return the location of the "Cache" + /// Directory for the Module. + /// + /// + /// + /// ----------------------------------------------------------------------------- + [Obsolete("This property is deprecated. Plaese use ModuleController.CacheDirectory(). Scheduled removal in v11.0.0.")] + public string CacheDirectory + { + get + { + return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache"; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the CacheFileName property is used to store the FileName for this Module's + /// Cache. + /// + /// + /// + /// ----------------------------------------------------------------------------- + [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] + public string CacheFileName + { + get + { + string strCacheKey = "TabModule:"; + strCacheKey += this.TabModuleId + ":"; + strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); + return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + "\\" + Globals.CleanFileName(strCacheKey) + ".resources"; + } + } + + [Obsolete("This property is deprecated. Please use ModuleController.CacheKey(TabModuleID). Scheduled removal in v11.0.0.")] + public string CacheKey + { + get + { + string strCacheKey = "TabModule:"; + strCacheKey += this.TabModuleId + ":"; + strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); + return strCacheKey; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string EditUrl() + { + return this.ModuleContext.EditUrl(); + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string EditUrl(string ControlKey) + { + return this.ModuleContext.EditUrl(ControlKey); + } + protected override void OnInit(EventArgs e) { if (this._tracelLogger.IsDebugEnabled) @@ -347,20 +412,6 @@ protected override void OnLoad(EventArgs e) } } - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string EditUrl() - { - return this.ModuleContext.EditUrl(); - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string EditUrl(string ControlKey) - { - return this.ModuleContext.EditUrl(ControlKey); - } - [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(string KeyName, string KeyValue) @@ -388,6 +439,11 @@ public string EditUrl(int TabID, string ControlKey, bool PageRedirect, params st { return this.ModuleContext.NavigateUrl(TabID, ControlKey, PageRedirect, AdditionalParameters); } + + public int GetNextActionID() + { + return this.ModuleContext.GetNextActionID(); + } /// ----------------------------------------------------------------------------- /// @@ -415,62 +471,6 @@ protected string LocalizeSafeJsString(string key) { return Localization.GetSafeJSString(key, this.LocalResourceFile); } - - public int GetNextActionID() - { - return this.ModuleContext.GetNextActionID(); - } - - // CONVERSION: Remove obsoleted methods (FYI some core modules use these, such as Links) - - /// ----------------------------------------------------------------------------- - /// - /// Gets the CacheDirectory property is used to return the location of the "Cache" - /// Directory for the Module. - /// - /// - /// - /// ----------------------------------------------------------------------------- - [Obsolete("This property is deprecated. Plaese use ModuleController.CacheDirectory(). Scheduled removal in v11.0.0.")] - public string CacheDirectory - { - get - { - return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache"; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the CacheFileName property is used to store the FileName for this Module's - /// Cache. - /// - /// - /// - /// ----------------------------------------------------------------------------- - [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] - public string CacheFileName - { - get - { - string strCacheKey = "TabModule:"; - strCacheKey += this.TabModuleId + ":"; - strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); - return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + "\\" + Globals.CleanFileName(strCacheKey) + ".resources"; - } - } - - [Obsolete("This property is deprecated. Please use ModuleController.CacheKey(TabModuleID). Scheduled removal in v11.0.0.")] - public string CacheKey - { - get - { - string strCacheKey = "TabModule:"; - strCacheKey += this.TabModuleId + ":"; - strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); - return strCacheKey; - } - } [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] public string GetCacheFileName(int tabModuleId) diff --git a/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs b/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs index 387b5dbe7bf..4736a7b222c 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs @@ -23,7 +23,7 @@ namespace DotNetNuke.Entities.Modules.Settings public abstract class SettingsRepository : ISettingsRepository where T : class, new() { - private IList Mapping { get; } + public const string CachePrefix = "ModuleSettingsPersister_"; private readonly IModuleController _moduleController; @@ -33,6 +33,17 @@ protected SettingsRepository() this._moduleController = ModuleController.Instance; } + protected virtual string MappingCacheKey + { + get + { + var type = typeof(T); + return SettingsRepository.CachePrefix + type.FullName.Replace(".", "_"); + } + } + + private IList Mapping { get; } + public T GetSettings(ModuleInfo moduleContext) { return CBO.GetCachedObject(new CacheItemArgs(this.CacheKey(moduleContext.TabModuleID), 20, CacheItemPriority.AboveNormal, moduleContext), this.Load, false); @@ -81,23 +92,6 @@ public void SaveSettings(ModuleInfo moduleContext, T settings) DataCache.SetCache(this.CacheKey(moduleContext.TabModuleID), settings); } - private static string GetSettingValueAsString(object settingValue) - { - var dateTimeValue = settingValue as DateTime?; - if (dateTimeValue != null) - { - return dateTimeValue.Value.ToString("o", CultureInfo.InvariantCulture); - } - - var timeSpanValue = settingValue as TimeSpan?; - if (timeSpanValue != null) - { - return timeSpanValue.Value.ToString("c", CultureInfo.InvariantCulture); - } - - return Convert.ToString(settingValue, CultureInfo.InvariantCulture); - } - protected IList LoadMapping() { var cacheKey = this.MappingCacheKey; @@ -114,17 +108,6 @@ protected IList LoadMapping() return mapping; } - public const string CachePrefix = "ModuleSettingsPersister_"; - - protected virtual string MappingCacheKey - { - get - { - var type = typeof(T); - return SettingsRepository.CachePrefix + type.FullName.Replace(".", "_"); - } - } - protected virtual IList CreateMapping() { var mapping = new List(); @@ -140,6 +123,42 @@ protected virtual IList CreateMapping() return mapping; } + private static string GetSettingValueAsString(object settingValue) + { + var dateTimeValue = settingValue as DateTime?; + if (dateTimeValue != null) + { + return dateTimeValue.Value.ToString("o", CultureInfo.InvariantCulture); + } + + var timeSpanValue = settingValue as TimeSpan?; + if (timeSpanValue != null) + { + return timeSpanValue.Value.ToString("c", CultureInfo.InvariantCulture); + } + + return Convert.ToString(settingValue, CultureInfo.InvariantCulture); + } + + private static object CallSerializerMethod(string serializerTypeName, Type typeArgument, object value, string methodName) + { + var serializerType = Framework.Reflection.CreateType(serializerTypeName, true); + if (serializerType == null) + { + return null; + } + + var serializer = Framework.Reflection.CreateInstance(serializerType); + if (serializer == null) + { + return null; + } + + var serializerInterfaceType = typeof(ISettingsSerializer<>).MakeGenericType(typeArgument); + var method = serializerInterfaceType.GetMethod(methodName); + return method.Invoke(serializer, new[] { value, }); + } + private T Load(CacheItemArgs args) { var ctlModule = (ModuleInfo)args.ParamList[0]; @@ -305,24 +324,5 @@ private string ChangeFormatForBooleansIfNeeded(Type propertyType, string propert return propertyValue; } - - private static object CallSerializerMethod(string serializerTypeName, Type typeArgument, object value, string methodName) - { - var serializerType = Framework.Reflection.CreateType(serializerTypeName, true); - if (serializerType == null) - { - return null; - } - - var serializer = Framework.Reflection.CreateInstance(serializerType); - if (serializer == null) - { - return null; - } - - var serializerInterfaceType = typeof(ISettingsSerializer<>).MakeGenericType(typeArgument); - var method = serializerInterfaceType.GetMethod(methodName); - return method.Invoke(serializer, new[] { value, }); - } } } diff --git a/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs b/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs index df5832c8a3e..3911d5f537e 100644 --- a/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs @@ -44,19 +44,6 @@ public SkinControlInfo() /// An Integer. /// ----------------------------------------------------------------------------- public int PackageID { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a SkinControlInfo from a Data Reader. - /// - /// The Data Reader to use. - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - this.SkinControlID = Null.SetNullInteger(dr["SkinControlID"]); - this.PackageID = Null.SetNullInteger(dr["PackageID"]); - this.FillInternal(dr); - } /// ----------------------------------------------------------------------------- /// @@ -77,6 +64,19 @@ public int KeyID } } + /// ----------------------------------------------------------------------------- + /// + /// Fills a SkinControlInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.SkinControlID = Null.SetNullInteger(dr["SkinControlID"]); + this.PackageID = Null.SetNullInteger(dr["PackageID"]); + this.FillInternal(dr); + } + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the SkinControlInfo. diff --git a/DNN Platform/Library/Entities/Modules/UserModuleBase.cs b/DNN Platform/Library/Entities/Modules/UserModuleBase.cs index 9d621fd333e..bfc0c6d5947 100644 --- a/DNN Platform/Library/Entities/Modules/UserModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/UserModuleBase.cs @@ -49,6 +49,59 @@ public class UserModuleBase : PortalModuleBase { private UserInfo _User; + /// + /// Gets or sets and sets the User associated with this control. + /// + public UserInfo User + { + get + { + return this._User ?? (this._User = this.AddUser ? this.InitialiseUser() : UserController.GetUserById(this.UserPortalID, this.UserId)); + } + + set + { + this._User = value; + if (this._User != null) + { + this.UserId = this._User.UserID; + } + } + } + + /// + /// Gets or sets and sets the UserId associated with this control. + /// + public new int UserId + { + get + { + int _UserId = Null.NullInteger; + if (this.ViewState["UserId"] == null) + { + if (this.Request.QueryString["userid"] != null) + { + int userId; + + // Use Int32.MaxValue as invalid UserId + _UserId = int.TryParse(this.Request.QueryString["userid"], out userId) ? userId : int.MaxValue; + this.ViewState["UserId"] = _UserId; + } + } + else + { + _UserId = Convert.ToInt32(this.ViewState["UserId"]); + } + + return _UserId; + } + + set + { + this.ViewState["UserId"] = value; + } + } + /// /// Gets a value indicating whether gets whether we are in Add User mode. /// @@ -188,59 +241,6 @@ protected int UserPortalID } } - /// - /// Gets or sets and sets the User associated with this control. - /// - public UserInfo User - { - get - { - return this._User ?? (this._User = this.AddUser ? this.InitialiseUser() : UserController.GetUserById(this.UserPortalID, this.UserId)); - } - - set - { - this._User = value; - if (this._User != null) - { - this.UserId = this._User.UserID; - } - } - } - - /// - /// Gets or sets and sets the UserId associated with this control. - /// - public new int UserId - { - get - { - int _UserId = Null.NullInteger; - if (this.ViewState["UserId"] == null) - { - if (this.Request.QueryString["userid"] != null) - { - int userId; - - // Use Int32.MaxValue as invalid UserId - _UserId = int.TryParse(this.Request.QueryString["userid"], out userId) ? userId : int.MaxValue; - this.ViewState["UserId"] = _UserId; - } - } - else - { - _UserId = Convert.ToInt32(this.ViewState["UserId"]); - } - - return _UserId; - } - - set - { - this.ViewState["UserId"] = value; - } - } - /// /// Gets a Setting for the Module. /// @@ -286,6 +286,31 @@ public static void UpdateSettings(int portalId, Hashtable settings) } } + /// + /// AddLocalizedModuleMessage adds a localized module message. + /// + /// The localized message. + /// The type of message. + /// A flag that determines whether the message should be displayed. + protected void AddLocalizedModuleMessage(string message, ModuleMessage.ModuleMessageType type, bool display) + { + if (display) + { + UI.Skins.Skin.AddModuleMessage(this, message, type); + } + } + + /// + /// AddModuleMessage adds a module message. + /// + /// The message. + /// The type of message. + /// A flag that determines whether the message should be displayed. + protected void AddModuleMessage(string message, ModuleMessage.ModuleMessageType type, bool display) + { + this.AddLocalizedModuleMessage(Localization.GetString(message, this.LocalResourceFile), type, display); + } + /// /// InitialiseUser initialises a "new" user. /// @@ -401,31 +426,6 @@ private string LookupCountry() return country; } - /// - /// AddLocalizedModuleMessage adds a localized module message. - /// - /// The localized message. - /// The type of message. - /// A flag that determines whether the message should be displayed. - protected void AddLocalizedModuleMessage(string message, ModuleMessage.ModuleMessageType type, bool display) - { - if (display) - { - UI.Skins.Skin.AddModuleMessage(this, message, type); - } - } - - /// - /// AddModuleMessage adds a module message. - /// - /// The message. - /// The type of message. - /// A flag that determines whether the message should be displayed. - protected void AddModuleMessage(string message, ModuleMessage.ModuleMessageType type, bool display) - { - this.AddLocalizedModuleMessage(Localization.GetString(message, this.LocalResourceFile), type, display); - } - protected string CompleteUserCreation(UserCreateStatus createStatus, UserInfo newUser, bool notify, bool register) { var strMessage = string.Empty; diff --git a/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs b/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs index 028d80a3829..7265adeccfb 100644 --- a/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs +++ b/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs @@ -53,6 +53,8 @@ public class UserUserControlBase : UserModuleBase public event UserUpdateErrorEventHandler UserUpdateError; + protected override bool AddUser => !this.Request.IsAuthenticated || base.AddUser; + /// ----------------------------------------------------------------------------- /// /// Raises the UserCreateCompleted Event. @@ -176,8 +178,6 @@ public void OnUserUpdateError(UserUpdateErrorArgs e) } } - protected override bool AddUser => !this.Request.IsAuthenticated || base.AddUser; - /// ----------------------------------------------------------------------------- /// /// The BaseUserEventArgs class provides a base for User EventArgs classes. diff --git a/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs b/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs index 97b2170c6a8..64c02e67441 100644 --- a/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs +++ b/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs @@ -15,11 +15,6 @@ namespace DotNetNuke.Entities.Portals.Internal public class PortalTemplateIO : ServiceLocator, IPortalTemplateIO { - protected override Func GetFactory() - { - return () => new PortalTemplateIO(); - } - public IEnumerable EnumerateTemplates() { string path = Globals.HostMapPath; @@ -41,6 +36,11 @@ public IEnumerable EnumerateLanguageFiles() return new string[0]; } + + protected override Func GetFactory() + { + return () => new PortalTemplateIO(); + } public string GetResourceFilePath(string templateFilePath) { diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs index 23f25e0bf06..d16205619d6 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs @@ -9,22 +9,6 @@ namespace DotNetNuke.Entities.Portals [Serializable] public class PortalAliasCollection : DictionaryBase { - /// - /// Gets or sets the value associated with the specified key. - /// - public PortalAliasInfo this[string key] - { - get - { - return (PortalAliasInfo)this.Dictionary[key]; - } - - set - { - this.Dictionary[key] = value; - } - } - /// /// Gets a value indicating whether gets a value indicating if the collection contains keys that are not null. /// @@ -51,6 +35,22 @@ public ICollection Values return this.Dictionary.Values; } } + + /// + /// Gets or sets the value associated with the specified key. + /// + public PortalAliasInfo this[string key] + { + get + { + return (PortalAliasInfo)this.Dictionary[key]; + } + + set + { + this.Dictionary[key] = value; + } + } public bool Contains(string key) { diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasController.cs b/DNN Platform/Library/Entities/Portals/PortalAliasController.cs index 9d70e2b99ea..10605964014 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasController.cs @@ -29,6 +29,129 @@ namespace DotNetNuke.Entities.Portals /// public partial class PortalAliasController : ServiceLocator, IPortalAliasController { + /// + /// Gets the portal alias by portal. + /// + /// The portal id. + /// The portal alias. + /// Portal alias. + public static string GetPortalAliasByPortal(int portalId, string portalAlias) + { + string retValue = string.Empty; + bool foundAlias = false; + PortalAliasInfo portalAliasInfo = Instance.GetPortalAlias(portalAlias, portalId); + if (portalAliasInfo != null) + { + retValue = portalAliasInfo.HTTPAlias; + foundAlias = true; + } + + if (!foundAlias) + { + // searching from longest to shortest alias ensures that the most specific portal is matched first + // In some cases this method has been called with "portalaliases" that were not exactly the real portal alias + // the startswith behaviour is preserved here to support those non-specific uses + var controller = new PortalAliasController(); + var portalAliases = controller.GetPortalAliasesInternal(); + var portalAliasCollection = portalAliases.OrderByDescending(k => k.Key.Length); + + foreach (var currentAlias in portalAliasCollection) + { + // check if the alias key starts with the portal alias value passed in - we use + // StartsWith because child portals are redirected to the parent portal domain name + // 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 ) + string httpAlias = currentAlias.Value.HTTPAlias.ToLowerInvariant(); + if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) + { + retValue = currentAlias.Value.HTTPAlias; + break; + } + + httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); + if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) + { + retValue = currentAlias.Value.HTTPAlias; + break; + } + } + } + + return retValue; + } + + /// + /// Gets the portal alias by tab. + /// + /// The tab ID. + /// The portal alias. + /// Portal alias. + public static string GetPortalAliasByTab(int tabId, string portalAlias) + { + string retValue = Null.NullString; + int intPortalId = -2; + + // get the tab + TabInfo tab = TabController.Instance.GetTab(tabId, Null.NullInteger); + if (tab != null) + { + // ignore deleted tabs + if (!tab.IsDeleted) + { + intPortalId = tab.PortalID; + } + } + + switch (intPortalId) + { + case -2: // tab does not exist + break; + case -1: // host tab + // host tabs are not verified to determine if they belong to the portal alias + retValue = portalAlias; + break; + default: // portal tab + retValue = GetPortalAliasByPortal(intPortalId, portalAlias); + break; + } + + return retValue; + } + + public int AddPortalAlias(PortalAliasInfo portalAlias) + { + // Add Alias + var dataProvider = DataProvider.Instance(); + int Id = dataProvider.AddPortalAlias( + portalAlias.PortalID, + portalAlias.HTTPAlias.ToLowerInvariant().Trim('/'), + portalAlias.CultureCode, + portalAlias.Skin, + portalAlias.BrowserType.ToString(), + portalAlias.IsPrimary, + UserController.Instance.GetCurrentUserInfo().UserID); + + // Log Event + LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_CREATED); + + // clear portal alias cache + ClearCache(true); + + return Id; + } + + public void DeletePortalAlias(PortalAliasInfo portalAlias) + { + // Delete Alias + DataProvider.Instance().DeletePortalAlias(portalAlias.PortalAliasID); + + // Log Event + LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_DELETED); + + // clear portal alias cache + ClearCache(false, portalAlias.PortalID); + } + protected override Func GetFactory() { return () => new PortalAliasController(); @@ -50,6 +173,28 @@ private static void ClearCache(bool refreshServiceRoutes, int portalId = -1) } } + private static void LogEvent(PortalAliasInfo portalAlias, EventLogController.EventLogType logType) + { + int userId = UserController.Instance.GetCurrentUserInfo().UserID; + EventLogController.Instance.AddLog(portalAlias, PortalController.Instance.GetCurrentPortalSettings(), userId, string.Empty, logType); + } + + private static bool ValidateAlias(string portalAlias, bool ischild, bool isDomain) + { + string validChars = "abcdefghijklmnopqrstuvwxyz0123456789-/"; + if (!ischild) + { + validChars += ".:"; + } + + if (!isDomain) + { + validChars += "_"; + } + + return portalAlias.All(c => validChars.Contains(c.ToString())); + } + private PortalAliasInfo GetPortalAliasLookupInternal(string alias) { return this.GetPortalAliasesInternal().SingleOrDefault(pa => pa.Key == alias).Value; @@ -130,62 +275,6 @@ private PortalAliasInfo GetPortalAliasInternal(string httpAlias) return portalAlias; } - private static void LogEvent(PortalAliasInfo portalAlias, EventLogController.EventLogType logType) - { - int userId = UserController.Instance.GetCurrentUserInfo().UserID; - EventLogController.Instance.AddLog(portalAlias, PortalController.Instance.GetCurrentPortalSettings(), userId, string.Empty, logType); - } - - private static bool ValidateAlias(string portalAlias, bool ischild, bool isDomain) - { - string validChars = "abcdefghijklmnopqrstuvwxyz0123456789-/"; - if (!ischild) - { - validChars += ".:"; - } - - if (!isDomain) - { - validChars += "_"; - } - - return portalAlias.All(c => validChars.Contains(c.ToString())); - } - - public int AddPortalAlias(PortalAliasInfo portalAlias) - { - // Add Alias - var dataProvider = DataProvider.Instance(); - int Id = dataProvider.AddPortalAlias( - portalAlias.PortalID, - portalAlias.HTTPAlias.ToLowerInvariant().Trim('/'), - portalAlias.CultureCode, - portalAlias.Skin, - portalAlias.BrowserType.ToString(), - portalAlias.IsPrimary, - UserController.Instance.GetCurrentUserInfo().UserID); - - // Log Event - LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_CREATED); - - // clear portal alias cache - ClearCache(true); - - return Id; - } - - public void DeletePortalAlias(PortalAliasInfo portalAlias) - { - // Delete Alias - DataProvider.Instance().DeletePortalAlias(portalAlias.PortalAliasID); - - // Log Event - LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_DELETED); - - // clear portal alias cache - ClearCache(false, portalAlias.PortalID); - } - public PortalAliasInfo GetPortalAlias(string alias) { return this.GetPortalAliasInternal(alias); @@ -212,6 +301,22 @@ public PortalAliasInfo GetPortalAliasByPortalAliasID(int portalAliasId) return this.GetPortalAliasesInternal().SingleOrDefault(pa => pa.Value.PortalAliasID == portalAliasId).Value; } + public PortalAliasCollection GetPortalAliases() + { + var aliasCollection = new PortalAliasCollection(); + foreach (var alias in this.GetPortalAliasesInternal().Values) + { + aliasCollection.Add(alias.HTTPAlias, alias); + } + + return aliasCollection; + } + + public IEnumerable GetPortalAliasesByPortalId(int portalId) + { + return this.GetPortalAliasesInternal().Values.Where(alias => alias.PortalID == portalId).ToList(); + } + internal Dictionary GetPortalAliasesInternal() { return CBO.GetCachedObject>( @@ -229,22 +334,6 @@ internal Dictionary GetPortalAliasesInternal() true); } - public PortalAliasCollection GetPortalAliases() - { - var aliasCollection = new PortalAliasCollection(); - foreach (var alias in this.GetPortalAliasesInternal().Values) - { - aliasCollection.Add(alias.HTTPAlias, alias); - } - - return aliasCollection; - } - - public IEnumerable GetPortalAliasesByPortalId(int portalId) - { - return this.GetPortalAliasesInternal().Values.Where(alias => alias.PortalID == portalId).ToList(); - } - /// /// Gets the portal by portal alias ID. /// @@ -274,95 +363,6 @@ public void UpdatePortalAlias(PortalAliasInfo portalAlias) // clear portal alias cache ClearCache(false); } - - /// - /// Gets the portal alias by portal. - /// - /// The portal id. - /// The portal alias. - /// Portal alias. - public static string GetPortalAliasByPortal(int portalId, string portalAlias) - { - string retValue = string.Empty; - bool foundAlias = false; - PortalAliasInfo portalAliasInfo = Instance.GetPortalAlias(portalAlias, portalId); - if (portalAliasInfo != null) - { - retValue = portalAliasInfo.HTTPAlias; - foundAlias = true; - } - - if (!foundAlias) - { - // searching from longest to shortest alias ensures that the most specific portal is matched first - // In some cases this method has been called with "portalaliases" that were not exactly the real portal alias - // the startswith behaviour is preserved here to support those non-specific uses - var controller = new PortalAliasController(); - var portalAliases = controller.GetPortalAliasesInternal(); - var portalAliasCollection = portalAliases.OrderByDescending(k => k.Key.Length); - - foreach (var currentAlias in portalAliasCollection) - { - // check if the alias key starts with the portal alias value passed in - we use - // StartsWith because child portals are redirected to the parent portal domain name - // 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 ) - string httpAlias = currentAlias.Value.HTTPAlias.ToLowerInvariant(); - if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) - { - retValue = currentAlias.Value.HTTPAlias; - break; - } - - httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); - if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) - { - retValue = currentAlias.Value.HTTPAlias; - break; - } - } - } - - return retValue; - } - - /// - /// Gets the portal alias by tab. - /// - /// The tab ID. - /// The portal alias. - /// Portal alias. - public static string GetPortalAliasByTab(int tabId, string portalAlias) - { - string retValue = Null.NullString; - int intPortalId = -2; - - // get the tab - TabInfo tab = TabController.Instance.GetTab(tabId, Null.NullInteger); - if (tab != null) - { - // ignore deleted tabs - if (!tab.IsDeleted) - { - intPortalId = tab.PortalID; - } - } - - switch (intPortalId) - { - case -2: // tab does not exist - break; - case -1: // host tab - // host tabs are not verified to determine if they belong to the portal alias - retValue = portalAlias; - break; - default: // portal tab - retValue = GetPortalAliasByPortal(intPortalId, portalAlias); - break; - } - - return retValue; - } /// /// Validates the alias. diff --git a/DNN Platform/Library/Entities/Portals/PortalController.cs b/DNN Platform/Library/Entities/Portals/PortalController.cs index 9abc2150348..9aab05c1cd0 100644 --- a/DNN Platform/Library/Entities/Portals/PortalController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalController.cs @@ -58,16 +58,359 @@ namespace DotNetNuke.Entities.Portals /// public partial class PortalController : ServiceLocator, IPortalController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalController)); - public const string HtmlText_TimeToAutoSave = "HtmlText_TimeToAutoSave"; public const string HtmlText_AutoSaveEnabled = "HtmlText_AutoSaveEnabled"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalController)); + protected const string HttpContextKeyPortalSettingsDictionary = "PortalSettingsDictionary{0}{1}"; - protected override Func GetFactory() - { - return () => new PortalController(); + /// + /// Adds the portal dictionary. + /// + /// The portal id. + /// The tab id. + public static void AddPortalDictionary(int portalId, int tabId) + { + var portalDic = GetPortalDictionary(); + portalDic[tabId] = portalId; + DataCache.SetCache(DataCache.PortalDictionaryCacheKey, portalDic); + } + + /// + /// Creates the root folder for a child portal. + /// + /// + /// If call this method, it will create the specific folder if the folder doesn't exist; + /// and will copy subhost.aspx to the folder if there is no 'Default.aspx'. + /// + /// The child path. + /// + /// If the method executed successful, it will return NullString, otherwise return error message. + /// + /// + /// + /// string childPhysicalPath = Server.MapPath(childPath); + /// message = PortalController.CreateChildPortalFolder(childPhysicalPath); + /// + /// + public static string CreateChildPortalFolder(string ChildPath) + { + string message = Null.NullString; + + // Set up Child Portal + try + { + // create the subdirectory for the new portal + if (!Directory.Exists(ChildPath)) + { + Directory.CreateDirectory(ChildPath); + } + + // create the subhost default.aspx file + if (!File.Exists(ChildPath + "\\" + Globals.glbDefaultPage)) + { + File.Copy(Globals.HostMapPath + "subhost.aspx", ChildPath + "\\" + Globals.glbDefaultPage); + } + } + catch (Exception Exc) + { + Logger.Error(Exc); + message += Localization.GetString("ChildPortal.Error") + Exc.Message + Exc.StackTrace; + } + + return message; + } + + /// + /// Creates a new portal alias. + /// + /// Id of the portal. + /// Portal Alias to be created. + public void AddPortalAlias(int portalId, string portalAlias) + { + // Check if the Alias exists + PortalAliasInfo portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias, portalId); + + // If alias does not exist add new + if (portalAliasInfo == null) + { + portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = portalAlias, IsPrimary = true }; + PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); + } + } + + /// + /// Copies the page template. + /// + /// The template file. + /// The mapped home directory. + public void CopyPageTemplate(string templateFile, string mappedHomeDirectory) + { + string hostTemplateFile = string.Format("{0}Templates\\{1}", Globals.HostMapPath, templateFile); + if (File.Exists(hostTemplateFile)) + { + string portalTemplateFolder = string.Format("{0}Templates\\", mappedHomeDirectory); + if (!Directory.Exists(portalTemplateFolder)) + { + // Create Portal Templates folder + Directory.CreateDirectory(portalTemplateFolder); + } + + string portalTemplateFile = portalTemplateFolder + templateFile; + if (!File.Exists(portalTemplateFile)) + { + File.Copy(hostTemplateFile, portalTemplateFile); + } + } + } + + internal static void EnsureRequiredEventLogTypesExist() + { + if (!DoesLogTypeExists(EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString())) + { + // Add 404 Log + var logTypeInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), + LogTypeFriendlyName = "HTTP Error Code 404 Page Not Found", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationFailure", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeInfo); + + // Add LogType + var logTypeConf = new LogTypeConfigInfo + { + LoggingIsActive = true, + LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), + KeepMostRecent = "100", + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = Null.NullString, + MailToAddress = Null.NullString, + LogTypePortalID = "*", + }; + LogController.Instance.AddLogTypeConfigInfo(logTypeConf); + } + + if (!DoesLogTypeExists(EventLogController.EventLogType.IP_LOGIN_BANNED.ToString())) + { + // Add IP filter log type + var logTypeFilterInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), + LogTypeFriendlyName = "HTTP Error Code Forbidden IP address rejected", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationFailure", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeFilterInfo); + + // Add LogType + var logTypeFilterConf = new LogTypeConfigInfo + { + LoggingIsActive = true, + LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), + KeepMostRecent = "100", + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = Null.NullString, + MailToAddress = Null.NullString, + LogTypePortalID = "*", + }; + LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); + } + + if (!DoesLogTypeExists(EventLogController.EventLogType.TABURL_CREATED.ToString())) + { + var logTypeInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), + LogTypeFriendlyName = "TabURL created", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationSuccess", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeInfo); + + logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); + logTypeInfo.LogTypeFriendlyName = "TabURL updated"; + LogController.Instance.AddLogType(logTypeInfo); + + logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); + logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; + LogController.Instance.AddLogType(logTypeInfo); + + // Add LogType + var logTypeUrlConf = new LogTypeConfigInfo + { + LoggingIsActive = false, + LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), + KeepMostRecent = "100", + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = Null.NullString, + MailToAddress = Null.NullString, + LogTypePortalID = "*", + }; + LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + + logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); + LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + + logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); + LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + } + + if (!DoesLogTypeExists(EventLogController.EventLogType.SCRIPT_COLLISION.ToString())) + { + // Add IP filter log type + var logTypeFilterInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), + LogTypeFriendlyName = "Javscript library registration resolved script collision", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationFailure", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeFilterInfo); + + // Add LogType + var logTypeFilterConf = new LogTypeConfigInfo + { + LoggingIsActive = true, + LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), + KeepMostRecent = "100", + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = Null.NullString, + MailToAddress = Null.NullString, + LogTypePortalID = "*", + }; + LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); + } + } + + protected override Func GetFactory() + { + return () => new PortalController(); + } + + private static void CreateDefaultPortalRoles(int portalId, int administratorId, ref int administratorRoleId, ref int registeredRoleId, ref int subscriberRoleId, int unverifiedRoleId) + { + // create required roles if not already created + if (administratorRoleId == -1) + { + administratorRoleId = CreateRole(portalId, "Administrators", "Administrators of this Website", 0, 0, "M", 0, 0, "N", false, false); + } + + if (registeredRoleId == -1) + { + registeredRoleId = CreateRole(portalId, "Registered Users", "Registered Users", 0, 0, "M", 0, 0, "N", false, true); + } + + if (subscriberRoleId == -1) + { + subscriberRoleId = CreateRole(portalId, "Subscribers", "A public role for site subscriptions", 0, 0, "M", 0, 0, "N", true, true); + } + + if (unverifiedRoleId == -1) + { + CreateRole(portalId, "Unverified Users", "Unverified Users", 0, 0, "M", 0, 0, "N", false, false); + } + + RoleController.Instance.AddUserRole(portalId, administratorId, administratorRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + RoleController.Instance.AddUserRole(portalId, administratorId, registeredRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + RoleController.Instance.AddUserRole(portalId, administratorId, subscriberRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + + private static string CreateProfileDefinitions(int portalId, string templateFilePath) + { + string strMessage = Null.NullString; + try + { + // add profile definitions + XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; + + // open the XML template file + try + { + xmlDoc.Load(templateFilePath); + } + catch (Exception ex) + { + Logger.Error(ex); + } + + // parse profile definitions if available + var node = xmlDoc.SelectSingleNode("//portal/profiledefinitions"); + if (node != null) + { + ParseProfileDefinitions(node, portalId); + } + else // template does not contain profile definitions ( ie. was created prior to DNN 3.3.0 ) + { + ProfileController.AddDefaultDefinitions(portalId); + } + } + catch (Exception ex) + { + strMessage = Localization.GetString("CreateProfileDefinitions.Error"); + Exceptions.LogException(ex); + } + + return strMessage; + } + + private static int CreatePortal(string portalName, string homeDirectory, string cultureCode) + { + // add portal + int PortalId = -1; + try + { + // Use host settings as default values for these parameters + // This can be overwritten on the portal template + var datExpiryDate = Host.Host.DemoPeriod > Null.NullInteger + ? Convert.ToDateTime(Globals.GetMediumDate(DateTime.Now.AddDays(Host.Host.DemoPeriod).ToString(CultureInfo.InvariantCulture))) + : Null.NullDate; + + PortalId = DataProvider.Instance().CreatePortal( + portalName, + Host.Host.HostCurrency, + datExpiryDate, + Host.Host.HostFee, + Host.Host.HostSpace, + Host.Host.PageQuota, + Host.Host.UserQuota, + 0, // site log history function has been removed. + homeDirectory, + cultureCode, + UserController.Instance.GetCurrentUserInfo().UserID); + + // clear portal cache + DataCache.ClearHostCache(true); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + try + { + EnsureRequiredEventLogTypesExist(); + } + catch (Exception) + { + // should be no exception, but suppress just in case + } + + return PortalId; } private void AddFolderPermissions(int portalId, int folderId) @@ -96,34 +439,6 @@ private void AddFolderPermissions(int portalId, int folderId) FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); } - private static void CreateDefaultPortalRoles(int portalId, int administratorId, ref int administratorRoleId, ref int registeredRoleId, ref int subscriberRoleId, int unverifiedRoleId) - { - // create required roles if not already created - if (administratorRoleId == -1) - { - administratorRoleId = CreateRole(portalId, "Administrators", "Administrators of this Website", 0, 0, "M", 0, 0, "N", false, false); - } - - if (registeredRoleId == -1) - { - registeredRoleId = CreateRole(portalId, "Registered Users", "Registered Users", 0, 0, "M", 0, 0, "N", false, true); - } - - if (subscriberRoleId == -1) - { - subscriberRoleId = CreateRole(portalId, "Subscribers", "A public role for site subscriptions", 0, 0, "M", 0, 0, "N", true, true); - } - - if (unverifiedRoleId == -1) - { - CreateRole(portalId, "Unverified Users", "Unverified Users", 0, 0, "M", 0, 0, "N", false, false); - } - - RoleController.Instance.AddUserRole(portalId, administratorId, administratorRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - RoleController.Instance.AddUserRole(portalId, administratorId, registeredRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - RoleController.Instance.AddUserRole(portalId, administratorId, subscriberRoleId, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - private void CreatePortalInternal(int portalId, string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal, ref string message) { @@ -390,89 +705,6 @@ private void CreatePortalInternal(int portalId, string portalName, UserInfo admi } } - private static string CreateProfileDefinitions(int portalId, string templateFilePath) - { - string strMessage = Null.NullString; - try - { - // add profile definitions - XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; - - // open the XML template file - try - { - xmlDoc.Load(templateFilePath); - } - catch (Exception ex) - { - Logger.Error(ex); - } - - // parse profile definitions if available - var node = xmlDoc.SelectSingleNode("//portal/profiledefinitions"); - if (node != null) - { - ParseProfileDefinitions(node, portalId); - } - else // template does not contain profile definitions ( ie. was created prior to DNN 3.3.0 ) - { - ProfileController.AddDefaultDefinitions(portalId); - } - } - catch (Exception ex) - { - strMessage = Localization.GetString("CreateProfileDefinitions.Error"); - Exceptions.LogException(ex); - } - - return strMessage; - } - - private static int CreatePortal(string portalName, string homeDirectory, string cultureCode) - { - // add portal - int PortalId = -1; - try - { - // Use host settings as default values for these parameters - // This can be overwritten on the portal template - var datExpiryDate = Host.Host.DemoPeriod > Null.NullInteger - ? Convert.ToDateTime(Globals.GetMediumDate(DateTime.Now.AddDays(Host.Host.DemoPeriod).ToString(CultureInfo.InvariantCulture))) - : Null.NullDate; - - PortalId = DataProvider.Instance().CreatePortal( - portalName, - Host.Host.HostCurrency, - datExpiryDate, - Host.Host.HostFee, - Host.Host.HostSpace, - Host.Host.PageQuota, - Host.Host.UserQuota, - 0, // site log history function has been removed. - homeDirectory, - cultureCode, - UserController.Instance.GetCurrentUserInfo().UserID); - - // clear portal cache - DataCache.ClearHostCache(true); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - - try - { - EnsureRequiredEventLogTypesExist(); - } - catch (Exception) - { - // should be no exception, but suppress just in case - } - - return PortalId; - } - private static int CreateRole(RoleInfo role) { int roleId; @@ -527,182 +759,50 @@ private static void CreateRoleGroup(RoleGroupInfo roleGroup) private static void DeletePortalInternal(int portalId) { - UserController.DeleteUsers(portalId, false, true); - - var portal = Instance.GetPortal(portalId); - - DataProvider.Instance().DeletePortalInfo(portalId); - - try - { - var log = new LogInfo - { - BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.PORTAL_DELETED.ToString(), - }; - log.LogProperties.Add(new LogDetailInfo("Delete Portal:", portal.PortalName)); - log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString())); - LogController.Instance.AddLog(log); - } - catch (Exception exc) - { - Logger.Error(exc); - } - - DataCache.ClearHostCache(true); - - // queue remove portal from search index - var document = new SearchDocumentToDelete - { - PortalId = portalId, - }; - - DataProvider.Instance().AddSearchDeletedItems(document); - } - - private static bool DoesLogTypeExists(string logTypeKey) - { - LogTypeInfo logType; - Dictionary logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); - logTypeDictionary.TryGetValue(logTypeKey, out logType); - if (logType == null) - { - return false; - } - - return true; - } - - internal static void EnsureRequiredEventLogTypesExist() - { - if (!DoesLogTypeExists(EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString())) - { - // Add 404 Log - var logTypeInfo = new LogTypeInfo - { - LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), - LogTypeFriendlyName = "HTTP Error Code 404 Page Not Found", - LogTypeDescription = string.Empty, - LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType", - }; - LogController.Instance.AddLogType(logTypeInfo); - - // Add LogType - var logTypeConf = new LogTypeConfigInfo - { - LoggingIsActive = true, - LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), - KeepMostRecent = "100", - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = Null.NullString, - MailToAddress = Null.NullString, - LogTypePortalID = "*", - }; - LogController.Instance.AddLogTypeConfigInfo(logTypeConf); - } - - if (!DoesLogTypeExists(EventLogController.EventLogType.IP_LOGIN_BANNED.ToString())) - { - // Add IP filter log type - var logTypeFilterInfo = new LogTypeInfo - { - LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), - LogTypeFriendlyName = "HTTP Error Code Forbidden IP address rejected", - LogTypeDescription = string.Empty, - LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType", - }; - LogController.Instance.AddLogType(logTypeFilterInfo); - - // Add LogType - var logTypeFilterConf = new LogTypeConfigInfo - { - LoggingIsActive = true, - LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), - KeepMostRecent = "100", - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = Null.NullString, - MailToAddress = Null.NullString, - LogTypePortalID = "*", - }; - LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); - } - - if (!DoesLogTypeExists(EventLogController.EventLogType.TABURL_CREATED.ToString())) - { - var logTypeInfo = new LogTypeInfo - { - LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), - LogTypeFriendlyName = "TabURL created", - LogTypeDescription = string.Empty, - LogTypeCSSClass = "OperationSuccess", - LogTypeOwner = "DotNetNuke.Logging.EventLogType", - }; - LogController.Instance.AddLogType(logTypeInfo); - - logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); - logTypeInfo.LogTypeFriendlyName = "TabURL updated"; - LogController.Instance.AddLogType(logTypeInfo); - - logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); - logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; - LogController.Instance.AddLogType(logTypeInfo); - - // Add LogType - var logTypeUrlConf = new LogTypeConfigInfo - { - LoggingIsActive = false, - LogTypeKey = EventLogController.EventLogType.TABURL_CREATED.ToString(), - KeepMostRecent = "100", - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = Null.NullString, - MailToAddress = Null.NullString, - LogTypePortalID = "*", - }; - LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + UserController.DeleteUsers(portalId, false, true); - logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); - LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + var portal = Instance.GetPortal(portalId); - logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); - LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); - } + DataProvider.Instance().DeletePortalInfo(portalId); - if (!DoesLogTypeExists(EventLogController.EventLogType.SCRIPT_COLLISION.ToString())) + try { - // Add IP filter log type - var logTypeFilterInfo = new LogTypeInfo + var log = new LogInfo { - LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), - LogTypeFriendlyName = "Javscript library registration resolved script collision", - LogTypeDescription = string.Empty, - LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType", + BypassBuffering = true, + LogTypeKey = EventLogController.EventLogType.PORTAL_DELETED.ToString(), }; - LogController.Instance.AddLogType(logTypeFilterInfo); + log.LogProperties.Add(new LogDetailInfo("Delete Portal:", portal.PortalName)); + log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString())); + LogController.Instance.AddLog(log); + } + catch (Exception exc) + { + Logger.Error(exc); + } - // Add LogType - var logTypeFilterConf = new LogTypeConfigInfo - { - LoggingIsActive = true, - LogTypeKey = EventLogController.EventLogType.SCRIPT_COLLISION.ToString(), - KeepMostRecent = "100", - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = Null.NullString, - MailToAddress = Null.NullString, - LogTypePortalID = "*", - }; - LogController.Instance.AddLogTypeConfigInfo(logTypeFilterConf); + DataCache.ClearHostCache(true); + + // queue remove portal from search index + var document = new SearchDocumentToDelete + { + PortalId = portalId, + }; + + DataProvider.Instance().AddSearchDeletedItems(document); + } + + private static bool DoesLogTypeExists(string logTypeKey) + { + LogTypeInfo logType; + Dictionary logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); + logTypeDictionary.TryGetValue(logTypeKey, out logType); + if (logType == null) + { + return false; } + + return true; } private static PortalSettings GetCurrentPortalSettingsInternal() @@ -931,34 +1031,6 @@ private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, in FolderPermissionController.SaveFolderPermissions(folder); } - private void CreatePredefinedFolderTypes(int portalId) - { - try - { - EnsureRequiredProvidersForFolderTypes(); - } - catch (Exception ex) - { - Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error"), ex); - } - - var webConfig = Config.Load(); - foreach (FolderTypeConfig folderTypeConfig in FolderMappingsConfigController.Instance.FolderTypes) - { - try - { - EnsureFolderProviderRegistration(folderTypeConfig, webConfig); - FolderMappingController.Instance.AddFolderMapping(this.GetFolderMappingFromConfig( - folderTypeConfig, - portalId)); - } - catch (Exception ex) - { - Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error") + ": " + folderTypeConfig.Name, ex); - } - } - } - private static void EnsureRequiredProvidersForFolderTypes() { if (ComponentFactory.GetComponent() == null) @@ -980,38 +1052,30 @@ private static void EnsureFolderProviderRegistration(FolderTypeConfig } } - private void ParseExtensionUrlProviders(XPathNavigator providersNavigator, int portalId) + private void CreatePredefinedFolderTypes(int portalId) { - var providers = ExtensionUrlProviderController.GetProviders(portalId); - foreach (XPathNavigator providerNavigator in providersNavigator.Select("extensionUrlProvider")) + try { - HtmlUtils.WriteKeepAlive(); - var providerName = XmlUtils.GetNodeValue(providerNavigator, "name"); - var provider = providers.SingleOrDefault(p => p.ProviderName.Equals(providerName, StringComparison.OrdinalIgnoreCase)); - if (provider == null) - { - continue; - } + EnsureRequiredProvidersForFolderTypes(); + } + catch (Exception ex) + { + Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error"), ex); + } - var active = XmlUtils.GetNodeValueBoolean(providerNavigator, "active"); - if (active) - { - ExtensionUrlProviderController.EnableProvider(provider.ExtensionUrlProviderId, portalId); - } - else + var webConfig = Config.Load(); + foreach (FolderTypeConfig folderTypeConfig in FolderMappingsConfigController.Instance.FolderTypes) + { + try { - ExtensionUrlProviderController.DisableProvider(provider.ExtensionUrlProviderId, portalId); + EnsureFolderProviderRegistration(folderTypeConfig, webConfig); + FolderMappingController.Instance.AddFolderMapping(this.GetFolderMappingFromConfig( + folderTypeConfig, + portalId)); } - - var settingsNavigator = providerNavigator.SelectSingleNode("settings"); - if (settingsNavigator != null) + catch (Exception ex) { - foreach (XPathNavigator settingNavigator in settingsNavigator.Select("setting")) - { - var name = XmlUtils.GetAttributeValue(settingNavigator, "name"); - var value = XmlUtils.GetAttributeValue(settingNavigator, "value"); - ExtensionUrlProviderController.SaveSetting(provider.ExtensionUrlProviderId, portalId, name, value); - } + Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error") + ": " + folderTypeConfig.Name, ex); } } } @@ -1040,59 +1104,6 @@ private static bool EnableBrowserLanguageInDefault(int portalId) return retValue; } - private string EnsureSettingValue(string folderProviderType, FolderTypeSettingConfig settingNode, int portalId) - { - var ensuredSettingValue = - settingNode.Value.Replace("{PortalId}", (portalId != -1) ? portalId.ToString(CultureInfo.InvariantCulture) : "_default").Replace("{HostId}", Host.Host.GUID); - if (settingNode.Encrypt) - { - return FolderProvider.Instance(folderProviderType).EncryptValue(ensuredSettingValue); - - // return PortalSecurity.Instance.Encrypt(Host.Host.GUID, ensuredSettingValue.Trim()); - } - - return ensuredSettingValue; - } - - private string GetCultureCode(string languageFileName) - { - // e.g. "default template.template.en-US.resx" - return languageFileName.GetLocaleCodeFromFileName(); - } - - private FolderMappingInfo GetFolderMappingFromConfig(FolderTypeConfig node, int portalId) - { - var folderMapping = new FolderMappingInfo - { - PortalID = portalId, - MappingName = node.Name, - FolderProviderType = node.Provider, - }; - - foreach (FolderTypeSettingConfig settingNode in node.Settings) - { - var settingValue = this.EnsureSettingValue(folderMapping.FolderProviderType, settingNode, portalId); - folderMapping.FolderMappingSettings.Add(settingNode.Name, settingValue); - } - - return folderMapping; - } - - private FolderMappingInfo GetFolderMappingFromStorageLocation(int portalId, XmlNode folderNode) - { - var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0")); - - switch (storageLocation) - { - case (int)FolderController.StorageLocationTypes.SecureFileSystem: - return FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"); - case (int)FolderController.StorageLocationTypes.DatabaseSecure: - return FolderMappingController.Instance.GetFolderMapping(portalId, "Database"); - default: - return FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - } - } - private static Dictionary GetPortalSettingsDictionary(int portalId, string cultureCode) { var httpContext = HttpContext.Current; @@ -1126,36 +1137,119 @@ private static Dictionary GetPortalSettingsDictionary(int portal } } - return dictionary; + return dictionary; + } + + private static string GetActivePortalLanguageFromHttpContext(HttpContext httpContext, int portalId) + { + var cultureCode = string.Empty; + + // Lookup culturecode but cache it in the HttpContext for performance + var activeLanguageKey = string.Format("ActivePortalLanguage{0}", portalId); + if (httpContext != null) + { + cultureCode = (string)httpContext.Items[activeLanguageKey]; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + cultureCode = GetActivePortalLanguage(portalId); + if (httpContext != null) + { + httpContext.Items[activeLanguageKey] = cultureCode; + } + } + + return cultureCode; + } + + private void ParseExtensionUrlProviders(XPathNavigator providersNavigator, int portalId) + { + var providers = ExtensionUrlProviderController.GetProviders(portalId); + foreach (XPathNavigator providerNavigator in providersNavigator.Select("extensionUrlProvider")) + { + HtmlUtils.WriteKeepAlive(); + var providerName = XmlUtils.GetNodeValue(providerNavigator, "name"); + var provider = providers.SingleOrDefault(p => p.ProviderName.Equals(providerName, StringComparison.OrdinalIgnoreCase)); + if (provider == null) + { + continue; + } + + var active = XmlUtils.GetNodeValueBoolean(providerNavigator, "active"); + if (active) + { + ExtensionUrlProviderController.EnableProvider(provider.ExtensionUrlProviderId, portalId); + } + else + { + ExtensionUrlProviderController.DisableProvider(provider.ExtensionUrlProviderId, portalId); + } + + var settingsNavigator = providerNavigator.SelectSingleNode("settings"); + if (settingsNavigator != null) + { + foreach (XPathNavigator settingNavigator in settingsNavigator.Select("setting")) + { + var name = XmlUtils.GetAttributeValue(settingNavigator, "name"); + var value = XmlUtils.GetAttributeValue(settingNavigator, "value"); + ExtensionUrlProviderController.SaveSetting(provider.ExtensionUrlProviderId, portalId, name, value); + } + } + } + } + + private string EnsureSettingValue(string folderProviderType, FolderTypeSettingConfig settingNode, int portalId) + { + var ensuredSettingValue = + settingNode.Value.Replace("{PortalId}", (portalId != -1) ? portalId.ToString(CultureInfo.InvariantCulture) : "_default").Replace("{HostId}", Host.Host.GUID); + if (settingNode.Encrypt) + { + return FolderProvider.Instance(folderProviderType).EncryptValue(ensuredSettingValue); + + // return PortalSecurity.Instance.Encrypt(Host.Host.GUID, ensuredSettingValue.Trim()); + } + + return ensuredSettingValue; } - private static string GetActivePortalLanguageFromHttpContext(HttpContext httpContext, int portalId) + private string GetCultureCode(string languageFileName) { - var cultureCode = string.Empty; + // e.g. "default template.template.en-US.resx" + return languageFileName.GetLocaleCodeFromFileName(); + } - // Lookup culturecode but cache it in the HttpContext for performance - var activeLanguageKey = string.Format("ActivePortalLanguage{0}", portalId); - if (httpContext != null) + private FolderMappingInfo GetFolderMappingFromConfig(FolderTypeConfig node, int portalId) + { + var folderMapping = new FolderMappingInfo { - cultureCode = (string)httpContext.Items[activeLanguageKey]; - } + PortalID = portalId, + MappingName = node.Name, + FolderProviderType = node.Provider, + }; - if (string.IsNullOrEmpty(cultureCode)) + foreach (FolderTypeSettingConfig settingNode in node.Settings) { - cultureCode = GetActivePortalLanguage(portalId); - if (httpContext != null) - { - httpContext.Items[activeLanguageKey] = cultureCode; - } + var settingValue = this.EnsureSettingValue(folderMapping.FolderProviderType, settingNode, portalId); + folderMapping.FolderMappingSettings.Add(settingNode.Name, settingValue); } - return cultureCode; + return folderMapping; } - private string GetTemplateName(string languageFileName) + private FolderMappingInfo GetFolderMappingFromStorageLocation(int portalId, XmlNode folderNode) { - // e.g. "default template.template.en-US.resx" - return languageFileName.GetFileNameFromLocalizedResxFile(); + var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0")); + + switch (storageLocation) + { + case (int)FolderController.StorageLocationTypes.SecureFileSystem: + return FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"); + case (int)FolderController.StorageLocationTypes.DatabaseSecure: + return FolderMappingController.Instance.GetFolderMapping(portalId, "Database"); + default: + return FolderMappingController.Instance.GetDefaultFolderMapping(portalId); + } } private static LocaleCollection ParseEnabledLocales(XmlNode nodeEnabledLocales, int portalId) @@ -1189,6 +1283,144 @@ private static LocaleCollection ParseEnabledLocales(XmlNode nodeEnabledLocales, return returnCollection; } + private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int portalId) + { + var listController = new ListController(); + Dictionary colDataTypes = listController.GetListEntryInfoDictionary("DataType"); + + int orderCounter = -1; + ProfilePropertyDefinition objProfileDefinition; + bool preferredTimeZoneFound = false; + foreach (XmlNode node in nodeProfileDefinitions.SelectNodes("//profiledefinition")) + { + orderCounter += 2; + ListEntryInfo typeInfo; + if (!colDataTypes.TryGetValue("DataType:" + XmlUtils.GetNodeValue(node.CreateNavigator(), "datatype"), out typeInfo)) + { + typeInfo = colDataTypes["DataType:Unknown"]; + } + + objProfileDefinition = new ProfilePropertyDefinition(portalId); + objProfileDefinition.DataType = typeInfo.EntryID; + objProfileDefinition.DefaultValue = string.Empty; + objProfileDefinition.ModuleDefId = Null.NullInteger; + objProfileDefinition.PropertyCategory = XmlUtils.GetNodeValue(node.CreateNavigator(), "propertycategory"); + objProfileDefinition.PropertyName = XmlUtils.GetNodeValue(node.CreateNavigator(), "propertyname"); + objProfileDefinition.Required = false; + objProfileDefinition.Visible = true; + objProfileDefinition.ViewOrder = orderCounter; + objProfileDefinition.Length = XmlUtils.GetNodeValueInt(node, "length"); + + switch (XmlUtils.GetNodeValueInt(node, "defaultvisibility", 2)) + { + case 0: + objProfileDefinition.DefaultVisibility = UserVisibilityMode.AllUsers; + break; + case 1: + objProfileDefinition.DefaultVisibility = UserVisibilityMode.MembersOnly; + break; + case 2: + objProfileDefinition.DefaultVisibility = UserVisibilityMode.AdminOnly; + break; + } + + if (objProfileDefinition.PropertyName == "PreferredTimeZone") + { + preferredTimeZoneFound = true; + } + + ProfileController.AddPropertyDefinition(objProfileDefinition); + } + + // 6.0 requires the old TimeZone property to be marked as Deleted + ProfilePropertyDefinition pdf = ProfileController.GetPropertyDefinitionByName(portalId, "TimeZone"); + if (pdf != null) + { + ProfileController.DeletePropertyDefinition(pdf); + } + + // 6.0 introduced a new property called as PreferredTimeZone. If this property is not present in template + // it should be added. Situation will mostly happen while using an older template file. + if (!preferredTimeZoneFound) + { + orderCounter += 2; + + ListEntryInfo typeInfo = colDataTypes["DataType:TimeZoneInfo"]; + if (typeInfo == null) + { + typeInfo = colDataTypes["DataType:Unknown"]; + } + + objProfileDefinition = new ProfilePropertyDefinition(portalId); + objProfileDefinition.DataType = typeInfo.EntryID; + objProfileDefinition.DefaultValue = string.Empty; + objProfileDefinition.ModuleDefId = Null.NullInteger; + objProfileDefinition.PropertyCategory = "Preferences"; + objProfileDefinition.PropertyName = "PreferredTimeZone"; + objProfileDefinition.Required = false; + objProfileDefinition.Visible = true; + objProfileDefinition.ViewOrder = orderCounter; + objProfileDefinition.Length = 0; + objProfileDefinition.DefaultVisibility = UserVisibilityMode.AdminOnly; + ProfileController.AddPropertyDefinition(objProfileDefinition); + } + } + + private static void ParsePortalDesktopModules(XPathNavigator nav, int portalID) + { + foreach (XPathNavigator desktopModuleNav in nav.Select("portalDesktopModule")) + { + HtmlUtils.WriteKeepAlive(); + var friendlyName = XmlUtils.GetNodeValue(desktopModuleNav, "friendlyname"); + if (!string.IsNullOrEmpty(friendlyName)) + { + var desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); + if (desktopModule != null) + { + // Parse the permissions + DesktopModulePermissionCollection permissions = new DesktopModulePermissionCollection(); + foreach (XPathNavigator permissionNav in + desktopModuleNav.Select("portalDesktopModulePermissions/portalDesktopModulePermission")) + { + string code = XmlUtils.GetNodeValue(permissionNav, "permissioncode"); + string key = XmlUtils.GetNodeValue(permissionNav, "permissionkey"); + DesktopModulePermissionInfo desktopModulePermission = null; + ArrayList arrPermissions = new PermissionController().GetPermissionByCodeAndKey(code, key); + if (arrPermissions.Count > 0) + { + PermissionInfo permission = arrPermissions[0] as PermissionInfo; + if (permission != null) + { + desktopModulePermission = new DesktopModulePermissionInfo(permission); + } + } + + desktopModulePermission.AllowAccess = bool.Parse(XmlUtils.GetNodeValue(permissionNav, "allowaccess")); + string rolename = XmlUtils.GetNodeValue(permissionNav, "rolename"); + if (!string.IsNullOrEmpty(rolename)) + { + RoleInfo role = RoleController.Instance.GetRole(portalID, r => r.RoleName == rolename); + if (role != null) + { + desktopModulePermission.RoleID = role.RoleID; + } + } + + permissions.Add(desktopModulePermission); + } + + DesktopModuleController.AddDesktopModuleToPortal(portalID, desktopModule, permissions, false); + } + } + } + } + + private string GetTemplateName(string languageFileName) + { + // e.g. "default template.template.en-US.resx" + return languageFileName.GetFileNameFromLocalizedResxFile(); + } + private void ParseFolders(XmlNode nodeFolders, int portalId) { var folderManager = FolderManager.Instance; @@ -1246,145 +1478,49 @@ private void ParseFolders(XmlNode nodeFolders, int portalId) folderManager.UpdateFolder(objInfo); } - var nodeFolderPermissions = node.SelectNodes("folderpermissions/permission"); - ParseFolderPermissions(nodeFolderPermissions, portalId, (FolderInfo)objInfo); - - var nodeFiles = node.SelectNodes("files/file"); - - ParseFiles(nodeFiles, portalId, (FolderInfo)objInfo); - } - } - } - - private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int portalId) - { - var listController = new ListController(); - Dictionary colDataTypes = listController.GetListEntryInfoDictionary("DataType"); - - int orderCounter = -1; - ProfilePropertyDefinition objProfileDefinition; - bool preferredTimeZoneFound = false; - foreach (XmlNode node in nodeProfileDefinitions.SelectNodes("//profiledefinition")) - { - orderCounter += 2; - ListEntryInfo typeInfo; - if (!colDataTypes.TryGetValue("DataType:" + XmlUtils.GetNodeValue(node.CreateNavigator(), "datatype"), out typeInfo)) - { - typeInfo = colDataTypes["DataType:Unknown"]; - } - - objProfileDefinition = new ProfilePropertyDefinition(portalId); - objProfileDefinition.DataType = typeInfo.EntryID; - objProfileDefinition.DefaultValue = string.Empty; - objProfileDefinition.ModuleDefId = Null.NullInteger; - objProfileDefinition.PropertyCategory = XmlUtils.GetNodeValue(node.CreateNavigator(), "propertycategory"); - objProfileDefinition.PropertyName = XmlUtils.GetNodeValue(node.CreateNavigator(), "propertyname"); - objProfileDefinition.Required = false; - objProfileDefinition.Visible = true; - objProfileDefinition.ViewOrder = orderCounter; - objProfileDefinition.Length = XmlUtils.GetNodeValueInt(node, "length"); - - switch (XmlUtils.GetNodeValueInt(node, "defaultvisibility", 2)) - { - case 0: - objProfileDefinition.DefaultVisibility = UserVisibilityMode.AllUsers; - break; - case 1: - objProfileDefinition.DefaultVisibility = UserVisibilityMode.MembersOnly; - break; - case 2: - objProfileDefinition.DefaultVisibility = UserVisibilityMode.AdminOnly; - break; - } - - if (objProfileDefinition.PropertyName == "PreferredTimeZone") - { - preferredTimeZoneFound = true; - } - - ProfileController.AddPropertyDefinition(objProfileDefinition); - } - - // 6.0 requires the old TimeZone property to be marked as Deleted - ProfilePropertyDefinition pdf = ProfileController.GetPropertyDefinitionByName(portalId, "TimeZone"); - if (pdf != null) - { - ProfileController.DeletePropertyDefinition(pdf); - } - - // 6.0 introduced a new property called as PreferredTimeZone. If this property is not present in template - // it should be added. Situation will mostly happen while using an older template file. - if (!preferredTimeZoneFound) - { - orderCounter += 2; + var nodeFolderPermissions = node.SelectNodes("folderpermissions/permission"); + ParseFolderPermissions(nodeFolderPermissions, portalId, (FolderInfo)objInfo); - ListEntryInfo typeInfo = colDataTypes["DataType:TimeZoneInfo"]; - if (typeInfo == null) - { - typeInfo = colDataTypes["DataType:Unknown"]; - } + var nodeFiles = node.SelectNodes("files/file"); - objProfileDefinition = new ProfilePropertyDefinition(portalId); - objProfileDefinition.DataType = typeInfo.EntryID; - objProfileDefinition.DefaultValue = string.Empty; - objProfileDefinition.ModuleDefId = Null.NullInteger; - objProfileDefinition.PropertyCategory = "Preferences"; - objProfileDefinition.PropertyName = "PreferredTimeZone"; - objProfileDefinition.Required = false; - objProfileDefinition.Visible = true; - objProfileDefinition.ViewOrder = orderCounter; - objProfileDefinition.Length = 0; - objProfileDefinition.DefaultVisibility = UserVisibilityMode.AdminOnly; - ProfileController.AddPropertyDefinition(objProfileDefinition); + ParseFiles(nodeFiles, portalId, (FolderInfo)objInfo); + } } } - private static void ParsePortalDesktopModules(XPathNavigator nav, int portalID) + private static void UpdatePortalSettingInternal(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) { - foreach (XPathNavigator desktopModuleNav in nav.Select("portalDesktopModule")) + string currentSetting = GetPortalSetting(settingName, portalID, string.Empty, cultureCode); + + if (currentSetting != settingValue) { - HtmlUtils.WriteKeepAlive(); - var friendlyName = XmlUtils.GetNodeValue(desktopModuleNav, "friendlyname"); - if (!string.IsNullOrEmpty(friendlyName)) + if (isSecure && !string.IsNullOrEmpty(settingName) && !string.IsNullOrEmpty(settingValue)) { - var desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); - if (desktopModule != null) - { - // Parse the permissions - DesktopModulePermissionCollection permissions = new DesktopModulePermissionCollection(); - foreach (XPathNavigator permissionNav in - desktopModuleNav.Select("portalDesktopModulePermissions/portalDesktopModulePermission")) - { - string code = XmlUtils.GetNodeValue(permissionNav, "permissioncode"); - string key = XmlUtils.GetNodeValue(permissionNav, "permissionkey"); - DesktopModulePermissionInfo desktopModulePermission = null; - ArrayList arrPermissions = new PermissionController().GetPermissionByCodeAndKey(code, key); - if (arrPermissions.Count > 0) - { - PermissionInfo permission = arrPermissions[0] as PermissionInfo; - if (permission != null) - { - desktopModulePermission = new DesktopModulePermissionInfo(permission); - } - } - - desktopModulePermission.AllowAccess = bool.Parse(XmlUtils.GetNodeValue(permissionNav, "allowaccess")); - string rolename = XmlUtils.GetNodeValue(permissionNav, "rolename"); - if (!string.IsNullOrEmpty(rolename)) - { - RoleInfo role = RoleController.Instance.GetRole(portalID, r => r.RoleName == rolename); - if (role != null) - { - desktopModulePermission.RoleID = role.RoleID; - } - } + settingValue = Security.FIPSCompliant.EncryptAES(settingValue, Config.GetDecryptionkey(), Host.Host.GUID); + } - permissions.Add(desktopModulePermission); - } + DataProvider.Instance().UpdatePortalSetting(portalID, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID, cultureCode, isSecure); + EventLogController.Instance.AddLog(settingName + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), settingValue, GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_UPDATED); + if (clearCache) + { + DataCache.ClearPortalCache(portalID, false); + DataCache.RemoveCache(DataCache.PortalDictionaryCacheKey); - DesktopModuleController.AddDesktopModuleToPortal(portalID, desktopModule, permissions, false); + var httpContext = HttpContext.Current; + if (httpContext != null) + { + var cultureCodeForKey = GetActivePortalLanguageFromHttpContext(httpContext, portalID); + var dictionaryKey = string.Format(HttpContextKeyPortalSettingsDictionary, portalID, cultureCodeForKey); + httpContext.Items[dictionaryKey] = null; } } + + EventManager.Instance.OnPortalSettingUpdated(new PortalSettingUpdatedEventArgs + { + PortalId = portalID, + SettingName = settingName, + SettingValue = settingValue, + }); } } @@ -2119,42 +2255,6 @@ private void UpdatePortalInternal(PortalInfo portal, bool clearCache) } } - private static void UpdatePortalSettingInternal(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) - { - string currentSetting = GetPortalSetting(settingName, portalID, string.Empty, cultureCode); - - if (currentSetting != settingValue) - { - if (isSecure && !string.IsNullOrEmpty(settingName) && !string.IsNullOrEmpty(settingValue)) - { - settingValue = Security.FIPSCompliant.EncryptAES(settingValue, Config.GetDecryptionkey(), Host.Host.GUID); - } - - DataProvider.Instance().UpdatePortalSetting(portalID, settingName, settingValue, UserController.Instance.GetCurrentUserInfo().UserID, cultureCode, isSecure); - EventLogController.Instance.AddLog(settingName + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), settingValue, GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_UPDATED); - if (clearCache) - { - DataCache.ClearPortalCache(portalID, false); - DataCache.RemoveCache(DataCache.PortalDictionaryCacheKey); - - var httpContext = HttpContext.Current; - if (httpContext != null) - { - var cultureCodeForKey = GetActivePortalLanguageFromHttpContext(httpContext, portalID); - var dictionaryKey = string.Format(HttpContextKeyPortalSettingsDictionary, portalID, cultureCodeForKey); - httpContext.Items[dictionaryKey] = null; - } - } - - EventManager.Instance.OnPortalSettingUpdated(new PortalSettingUpdatedEventArgs - { - PortalId = portalID, - SettingName = settingName, - SettingValue = settingValue, - }); - } - } - private void UpdatePortalSetup(int portalId, int administratorId, int administratorRoleId, int registeredRoleId, int splashTabId, int homeTabId, int loginTabId, int registerTabId, int userTabId, int searchTabId, int custom404TabId, int custom500TabId, int termsTabId, int privacyTabId, int adminTabId, string cultureCode) { @@ -2179,49 +2279,6 @@ private void UpdatePortalSetup(int portalId, int administratorId, int administra DataCache.ClearHostCache(true); } - /// - /// Creates a new portal alias. - /// - /// Id of the portal. - /// Portal Alias to be created. - public void AddPortalAlias(int portalId, string portalAlias) - { - // Check if the Alias exists - PortalAliasInfo portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias, portalId); - - // If alias does not exist add new - if (portalAliasInfo == null) - { - portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = portalAlias, IsPrimary = true }; - PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); - } - } - - /// - /// Copies the page template. - /// - /// The template file. - /// The mapped home directory. - public void CopyPageTemplate(string templateFile, string mappedHomeDirectory) - { - string hostTemplateFile = string.Format("{0}Templates\\{1}", Globals.HostMapPath, templateFile); - if (File.Exists(hostTemplateFile)) - { - string portalTemplateFolder = string.Format("{0}Templates\\", mappedHomeDirectory); - if (!Directory.Exists(portalTemplateFolder)) - { - // Create Portal Templates folder - Directory.CreateDirectory(portalTemplateFolder); - } - - string portalTemplateFile = portalTemplateFolder + templateFile; - if (!File.Exists(portalTemplateFile)) - { - File.Copy(hostTemplateFile, portalTemplateFile); - } - } - } - /// /// Creates the portal. /// @@ -2844,63 +2901,6 @@ void IPortalController.UpdatePortalSetting(int portalID, string settingName, str UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); } - /// - /// Adds the portal dictionary. - /// - /// The portal id. - /// The tab id. - public static void AddPortalDictionary(int portalId, int tabId) - { - var portalDic = GetPortalDictionary(); - portalDic[tabId] = portalId; - DataCache.SetCache(DataCache.PortalDictionaryCacheKey, portalDic); - } - - /// - /// Creates the root folder for a child portal. - /// - /// - /// If call this method, it will create the specific folder if the folder doesn't exist; - /// and will copy subhost.aspx to the folder if there is no 'Default.aspx'. - /// - /// The child path. - /// - /// If the method executed successful, it will return NullString, otherwise return error message. - /// - /// - /// - /// string childPhysicalPath = Server.MapPath(childPath); - /// message = PortalController.CreateChildPortalFolder(childPhysicalPath); - /// - /// - public static string CreateChildPortalFolder(string ChildPath) - { - string message = Null.NullString; - - // Set up Child Portal - try - { - // create the subdirectory for the new portal - if (!Directory.Exists(ChildPath)) - { - Directory.CreateDirectory(ChildPath); - } - - // create the subhost default.aspx file - if (!File.Exists(ChildPath + "\\" + Globals.glbDefaultPage)) - { - File.Copy(Globals.HostMapPath + "subhost.aspx", ChildPath + "\\" + Globals.glbDefaultPage); - } - } - catch (Exception Exc) - { - Logger.Error(Exc); - message += Localization.GetString("ChildPortal.Error") + Exc.Message + Exc.StackTrace; - } - - return message; - } - /// /// Deletes all expired portals. /// @@ -3643,8 +3643,8 @@ public static void IncrementOverridingPortalsCrmVersion() public class PortalTemplateInfo { - private string _resourceFilePath; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalController)); + private string _resourceFilePath; public PortalTemplateInfo(string templateFilePath, string cultureCode) { @@ -3654,6 +3654,19 @@ public PortalTemplateInfo(string templateFilePath, string cultureCode) this.InitNameAndDescription(); } + public string Name { get; private set; } + + public string CultureCode { get; private set; } + + public string TemplateFilePath { get; private set; } + + private static string ReadLanguageFileValue(XDocument xmlDoc, string name) + { + return (from f in xmlDoc.Descendants("data") + where (string)f.Attribute("name") == name + select (string)f.Element("value")).SingleOrDefault(); + } + private void InitNameAndDescription() { if (!string.IsNullOrEmpty(this.LanguageFilePath)) @@ -3708,13 +3721,6 @@ private void LoadNameAndDescriptionFromLanguageFile() } } - private static string ReadLanguageFileValue(XDocument xmlDoc, string name) - { - return (from f in xmlDoc.Descendants("data") - where (string)f.Attribute("name") == name - select (string)f.Element("value")).SingleOrDefault(); - } - private void InitLocalizationFields(string cultureCode) { this.LanguageFilePath = PortalTemplateIO.Instance.GetLanguageFilePath(this.TemplateFilePath, cultureCode); @@ -3731,12 +3737,6 @@ private void InitLocalizationFields(string cultureCode) } } - public string Name { get; private set; } - - public string CultureCode { get; private set; } - - public string TemplateFilePath { get; private set; } - public string LanguageFilePath { get; private set; } public string Description { get; private set; } diff --git a/DNN Platform/Library/Entities/Portals/PortalGroupController.cs b/DNN Platform/Library/Entities/Portals/PortalGroupController.cs index a9ad84a2eca..d983fc31f9b 100644 --- a/DNN Platform/Library/Entities/Portals/PortalGroupController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalGroupController.cs @@ -23,9 +23,9 @@ namespace DotNetNuke.Entities.Portals public class PortalGroupController : ComponentBase, IPortalGroupController { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalGroupController)); private readonly IDataService _dataService; private readonly IPortalController _portalController; - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalGroupController)); public PortalGroupController() : this(DataService.Instance, PortalController.Instance) @@ -42,15 +42,118 @@ public PortalGroupController(IDataService dataService, IPortalController portalC this._portalController = portalController; } - private object GetPortalGroupsCallback(CacheItemArgs cacheItemArgs) + public void AddPortalToGroup(PortalInfo portal, PortalGroupInfo portalGroup, UserCopiedCallback callback) { - return CBO.FillCollection(this._dataService.GetPortalGroups()); + Requires.NotNull("portal", portal); + Requires.PropertyNotNegative("portal", "PortalId", portal.PortalID); + Requires.NotNull("portalGroup", portalGroup); + Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); + Requires.PropertyNotNegative("portalGroup", "MasterPortalId", portalGroup.MasterPortalId); + + this.OnAddPortalToGroupStart(callback, portal); + + var users = UserController.GetUsers(portal.PortalID); + var masterUsers = UserController.GetUsers(portalGroup.MasterPortalId); + var totalUsers = users.Count + masterUsers.Count; + var userNo = 0; + + if (users.Count > 0) + { + var masterPortal = this._portalController.GetPortal(portalGroup.MasterPortalId); + + foreach (UserInfo user in users) + { + userNo += 1; + + UserController.MoveUserToPortal(user, masterPortal, true); + + this.OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); + } + } + + if (masterUsers.Count > 0) + { + var autoAssignRoles = RoleController.Instance.GetRoles( + portal.PortalID, + role => + role.AutoAssignment && + role.Status == RoleStatus.Approved); + foreach (UserInfo user in masterUsers) + { + userNo += 1; + foreach (var autoAssignRole in autoAssignRoles) + { + RoleController.Instance.AddUserRole(portalGroup.MasterPortalId, user.UserID, autoAssignRole.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + + this.OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); + } + } + + this.OnAddPortalToGroupFinishing(callback, portal, users.Count); + + this.RemoveProfileDefinitions(portal); + + // Add portal to group + portal.PortalGroupID = portalGroup.PortalGroupId; + PortalController.Instance.UpdatePortalInfo(portal); + this.LogEvent(EventLogController.EventLogType.PORTAL_ADDEDTOPORTALGROUP, portalGroup, portal); + + this.OnAddPortalToGroupFinished(callback, portal, portalGroup, users.Count); + } + + public int AddPortalGroup(PortalGroupInfo portalGroup) + { + // Argument Contract + Requires.NotNull("portalGroup", portalGroup); + + portalGroup.PortalGroupId = this._dataService.AddPortalGroup(portalGroup, UserController.Instance.GetCurrentUserInfo().UserID); + + // Update portal + var portal = this._portalController.GetPortal(portalGroup.MasterPortalId); + if (portal != null) + { + portal.PortalGroupID = portalGroup.PortalGroupId; + this._portalController.UpdatePortalInfo(portal); + } + + this.LogEvent(EventLogController.EventLogType.PORTALGROUP_CREATED, portalGroup, null); + + ClearCache(); + + return portalGroup.PortalGroupId; + } + + public void DeletePortalGroup(PortalGroupInfo portalGroup) + { + // Argument Contract + Requires.NotNull("portalGroup", portalGroup); + Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); + + // Update portal + var portal = this._portalController.GetPortal(portalGroup.MasterPortalId); + if (portal != null) + { + this.DeleteSharedModules(portal); + portal.PortalGroupID = -1; + PortalController.Instance.UpdatePortalInfo(portal); + } + + this._dataService.DeletePortalGroup(portalGroup); + this.LogEvent(EventLogController.EventLogType.PORTALGROUP_DELETED, portalGroup, null); + + ClearCache(); } private static void ClearCache() { DataCache.RemoveCache(DataCache.PortalGroupsCacheKey); } + + private object GetPortalGroupsCallback(CacheItemArgs cacheItemArgs) + { + return CBO.FillCollection(this._dataService.GetPortalGroups()); + } private void OnAddPortalToGroupStart(UserCopiedCallback callback, PortalInfo portal) { @@ -148,66 +251,6 @@ private void LogEvent(EventLogController.EventLogType eventType, PortalGroupInfo Logger.Error(exc); } } - - public void AddPortalToGroup(PortalInfo portal, PortalGroupInfo portalGroup, UserCopiedCallback callback) - { - Requires.NotNull("portal", portal); - Requires.PropertyNotNegative("portal", "PortalId", portal.PortalID); - Requires.NotNull("portalGroup", portalGroup); - Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); - Requires.PropertyNotNegative("portalGroup", "MasterPortalId", portalGroup.MasterPortalId); - - this.OnAddPortalToGroupStart(callback, portal); - - var users = UserController.GetUsers(portal.PortalID); - var masterUsers = UserController.GetUsers(portalGroup.MasterPortalId); - var totalUsers = users.Count + masterUsers.Count; - var userNo = 0; - - if (users.Count > 0) - { - var masterPortal = this._portalController.GetPortal(portalGroup.MasterPortalId); - - foreach (UserInfo user in users) - { - userNo += 1; - - UserController.MoveUserToPortal(user, masterPortal, true); - - this.OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); - } - } - - if (masterUsers.Count > 0) - { - var autoAssignRoles = RoleController.Instance.GetRoles( - portal.PortalID, - role => - role.AutoAssignment && - role.Status == RoleStatus.Approved); - foreach (UserInfo user in masterUsers) - { - userNo += 1; - foreach (var autoAssignRole in autoAssignRoles) - { - RoleController.Instance.AddUserRole(portalGroup.MasterPortalId, user.UserID, autoAssignRole.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - - this.OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); - } - } - - this.OnAddPortalToGroupFinishing(callback, portal, users.Count); - - this.RemoveProfileDefinitions(portal); - - // Add portal to group - portal.PortalGroupID = portalGroup.PortalGroupId; - PortalController.Instance.UpdatePortalInfo(portal); - this.LogEvent(EventLogController.EventLogType.PORTAL_ADDEDTOPORTALGROUP, portalGroup, portal); - - this.OnAddPortalToGroupFinished(callback, portal, portalGroup, users.Count); - } private void RemoveProfileDefinitions(PortalInfo portal) { @@ -265,49 +308,6 @@ private IEnumerable GetSharedModulesByPortal(PortalInfo portal) (p) => CBO.FillCollection(this._dataService.GetSharedModulesByPortal(portal))); } - public int AddPortalGroup(PortalGroupInfo portalGroup) - { - // Argument Contract - Requires.NotNull("portalGroup", portalGroup); - - portalGroup.PortalGroupId = this._dataService.AddPortalGroup(portalGroup, UserController.Instance.GetCurrentUserInfo().UserID); - - // Update portal - var portal = this._portalController.GetPortal(portalGroup.MasterPortalId); - if (portal != null) - { - portal.PortalGroupID = portalGroup.PortalGroupId; - this._portalController.UpdatePortalInfo(portal); - } - - this.LogEvent(EventLogController.EventLogType.PORTALGROUP_CREATED, portalGroup, null); - - ClearCache(); - - return portalGroup.PortalGroupId; - } - - public void DeletePortalGroup(PortalGroupInfo portalGroup) - { - // Argument Contract - Requires.NotNull("portalGroup", portalGroup); - Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); - - // Update portal - var portal = this._portalController.GetPortal(portalGroup.MasterPortalId); - if (portal != null) - { - this.DeleteSharedModules(portal); - portal.PortalGroupID = -1; - PortalController.Instance.UpdatePortalInfo(portal); - } - - this._dataService.DeletePortalGroup(portalGroup); - this.LogEvent(EventLogController.EventLogType.PORTALGROUP_DELETED, portalGroup, null); - - ClearCache(); - } - public IEnumerable GetPortalGroups() { return CBO.GetCachedObject>( diff --git a/DNN Platform/Library/Entities/Portals/PortalInfo.cs b/DNN Platform/Library/Entities/Portals/PortalInfo.cs index 0c7c6091b1e..851f9d25fa1 100644 --- a/DNN Platform/Library/Entities/Portals/PortalInfo.cs +++ b/DNN Platform/Library/Entities/Portals/PortalInfo.cs @@ -54,6 +54,8 @@ public class PortalInfo : BaseEntityInfo, IHydratable private string _administratorRoleName; private int _pages = Null.NullInteger; private string _registeredRoleName; + + private int _users; /// /// Initializes a new instance of the class. @@ -312,9 +314,9 @@ public string HomeSystemDirectory /// txtUserQuota.Text = objPortal.UserQuota.ToString /// [XmlElement("hostspace")] - public int HostSpace { get; set; } - - /// + public int HostSpace { get; set; } + + /// /// Gets or sets keywords (separated by ,) for this portal. /// /// Keywords seperated by . @@ -598,8 +600,6 @@ public string HomeSystemDirectory [XmlElement("usertabid")] public int UserTabId { get; set; } - private int _users; - /// /// Gets or sets actual number of actual users for this portal. /// @@ -755,6 +755,24 @@ public string RegisteredRoleName [XmlIgnore] [Obsolete("Deprecated in DNN 6.0. Scheduled removal in v10.0.0.")] public int TimeZoneOffset { get; set; } + + /// + /// Gets or sets and sets the Key ID. + /// + /// KeyId of the IHydratable.Key. + /// + public int KeyID + { + get + { + return this.PortalID; + } + + set + { + this.PortalID = value; + } + } /// /// Fills a PortalInfo from a Data Reader. @@ -856,23 +874,5 @@ public void Fill(IDataReader dr) this.Users = Null.NullInteger; this.Pages = Null.NullInteger; } - - /// - /// Gets or sets and sets the Key ID. - /// - /// KeyId of the IHydratable.Key. - /// - public int KeyID - { - get - { - return this.PortalID; - } - - set - { - this.PortalID = value; - } - } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalSettings.cs b/DNN Platform/Library/Entities/Portals/PortalSettings.cs index 75fd62c5ba5..8203daa6e72 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettings.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettings.cs @@ -27,6 +27,23 @@ namespace DotNetNuke.Entities.Portals [Serializable] public partial class PortalSettings : BaseEntityInfo, IPropertyAccess, IPortalSettings { + public PortalSettings() + { + this.Registration = new RegistrationSettings(); + } + + public PortalSettings(int portalId) + : this(Null.NullInteger, portalId) + { + } + + public PortalSettings(int tabId, int portalId) + { + this.PortalId = portalId; + var portal = PortalController.Instance.GetPortal(portalId); + this.BuildPortalSettings(tabId, portal); + } + public enum ControlPanelPermission { TabEditor, @@ -55,23 +72,6 @@ public enum UserDeleteAction HardDelete = 3, } - public PortalSettings() - { - this.Registration = new RegistrationSettings(); - } - - public PortalSettings(int portalId) - : this(Null.NullInteger, portalId) - { - } - - public PortalSettings(int tabId, int portalId) - { - this.PortalId = portalId; - var portal = PortalController.Instance.GetPortal(portalId); - this.BuildPortalSettings(tabId, portal); - } - /// ----------------------------------------------------------------------------- /// /// Initializes a new instance of the class. @@ -106,6 +106,20 @@ public PortalSettings(int tabId, PortalInfo portal) this.BuildPortalSettings(tabId, portal); } + public static PortalSettings Current + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } + } + + public TabInfo ActiveTab { get; set; } + + public int AdministratorId { get; set; } + + public int AdministratorRoleId { get; set; } + private void BuildPortalSettings(int tabId, PortalInfo portal) { PortalSettingsController.Instance().LoadPortalSettings(this); @@ -133,12 +147,6 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) } } - public TabInfo ActiveTab { get; set; } - - public int AdministratorId { get; set; } - - public int AdministratorRoleId { get; set; } - public string AdministratorRoleName { get; set; } public int AdminTabId { get; set; } @@ -438,14 +446,6 @@ public bool ControlPanelVisible } } - public static PortalSettings Current - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - public string DefaultPortalAlias { get diff --git a/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs b/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs index 0cbb6336ac2..12450eb24e0 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs @@ -86,37 +86,6 @@ public virtual TabInfo GetActiveTab(int tabId, PortalSettings portalSettings) return activeTab; } - protected List GetBreadcrumbs(int tabId, int portalId) - { - var breadCrumbs = new List(); - GetBreadCrumbs(breadCrumbs, tabId, portalId); - return breadCrumbs; - } - - private static void GetBreadCrumbs(IList breadCrumbs, int tabId, int portalId) - { - var portalTabs = TabController.Instance.GetTabsByPortal(portalId); - var hostTabs = TabController.Instance.GetTabsByPortal(Null.NullInteger); - while (true) - { - TabInfo tab; - if (portalTabs.TryGetValue(tabId, out tab) || hostTabs.TryGetValue(tabId, out tab)) - { - // add tab to breadcrumb collection - breadCrumbs.Insert(0, tab.Clone()); - - // get the tab parent - if (!Null.IsNull(tab.ParentId) && tabId != tab.ParentId) - { - tabId = tab.ParentId; - continue; - } - } - - break; - } - } - public virtual PortalSettings.PortalAliasMapping GetPortalAliasMappingMode(int portalId) { var aliasMapping = PortalSettings.PortalAliasMapping.None; @@ -140,33 +109,6 @@ public virtual PortalSettings.PortalAliasMapping GetPortalAliasMappingMode(int p return aliasMapping; } - private static TabInfo GetSpecialTab(int portalId, int tabId) - { - TabInfo activeTab = null; - - if (tabId > 0) - { - var tab = TabController.Instance.GetTab(tabId, portalId, false); - if (tab != null) - { - activeTab = tab.Clone(); - } - } - - return activeTab; - } - - // This method is called few times wiht each request; it would be - // better to have it cache the "activeTab" for a short period. - private static TabInfo GetTab(int tabId, TabCollection tabs) - { - TabInfo tab; - var activeTab = tabId != Null.NullInteger && tabs.TryGetValue(tabId, out tab) && !tab.IsDeleted - ? tab.Clone() - : null; - return activeTab; - } - public virtual IList GetTabModules(PortalSettings portalSettings) { return portalSettings.ActiveTab.Modules.Cast().Select(m => m).ToList(); @@ -217,6 +159,64 @@ public virtual void LoadPortal(PortalInfo portal, PortalSettings portalSettings) portalSettings.CultureCode = portal.CultureCode; } + protected List GetBreadcrumbs(int tabId, int portalId) + { + var breadCrumbs = new List(); + GetBreadCrumbs(breadCrumbs, tabId, portalId); + return breadCrumbs; + } + + private static void GetBreadCrumbs(IList breadCrumbs, int tabId, int portalId) + { + var portalTabs = TabController.Instance.GetTabsByPortal(portalId); + var hostTabs = TabController.Instance.GetTabsByPortal(Null.NullInteger); + while (true) + { + TabInfo tab; + if (portalTabs.TryGetValue(tabId, out tab) || hostTabs.TryGetValue(tabId, out tab)) + { + // add tab to breadcrumb collection + breadCrumbs.Insert(0, tab.Clone()); + + // get the tab parent + if (!Null.IsNull(tab.ParentId) && tabId != tab.ParentId) + { + tabId = tab.ParentId; + continue; + } + } + + break; + } + } + + private static TabInfo GetSpecialTab(int portalId, int tabId) + { + TabInfo activeTab = null; + + if (tabId > 0) + { + var tab = TabController.Instance.GetTab(tabId, portalId, false); + if (tab != null) + { + activeTab = tab.Clone(); + } + } + + return activeTab; + } + + // This method is called few times wiht each request; it would be + // better to have it cache the "activeTab" for a short period. + private static TabInfo GetTab(int tabId, TabCollection tabs) + { + TabInfo tab; + var activeTab = tabId != Null.NullInteger && tabs.TryGetValue(tabId, out tab) && !tab.IsDeleted + ? tab.Clone() + : null; + return activeTab; + } + public virtual void LoadPortalSettings(PortalSettings portalSettings) { var settings = PortalController.Instance.GetPortalSettings(portalSettings.PortalId); diff --git a/DNN Platform/Library/Entities/Profile/ProfileController.cs b/DNN Platform/Library/Entities/Profile/ProfileController.cs index d56bede8ede..a8463561b1b 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileController.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileController.cs @@ -41,10 +41,84 @@ public class ProfileController private static readonly ProfileProvider _profileProvider = ProfileProvider.Instance(); private static int _orderCounter; - private static void AddDefaultDefinition(int portalId, string category, string name, string strType, int length, UserVisibilityMode defaultVisibility, Dictionary types) + /// ----------------------------------------------------------------------------- + /// + /// Adds the default property definitions for a portal. + /// + /// Id of the Portal. + /// ----------------------------------------------------------------------------- + public static void AddDefaultDefinitions(int portalId) { - _orderCounter += 2; - AddDefaultDefinition(portalId, category, name, strType, length, _orderCounter, defaultVisibility, types); + portalId = GetEffectivePortalId(portalId); + + _orderCounter = 1; + var listController = new ListController(); + Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); + + AddDefaultDefinition(portalId, "Name", "Prefix", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Name", "FirstName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Name", "MiddleName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Name", "LastName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Name", "Suffix", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); + AddDefaultDefinition(portalId, "Address", "Unit", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "Street", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "City", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "Region", "Region", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "Country", "Country", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Address", "PostalCode", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "Telephone", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "Cell", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "Fax", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "Website", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Contact Info", "IM", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "Biography", "Multi-line Text", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "TimeZone", "TimeZone", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "PreferredTimeZone", "TimeZoneInfo", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "PreferredLocale", "Locale", 0, UserVisibilityMode.AdminOnly, dataTypes); + AddDefaultDefinition(portalId, "Preferences", "Photo", "Image", 0, UserVisibilityMode.AllUsers, dataTypes); + + // 6.0 requires the old TimeZone property to be marked as Deleted + ProfilePropertyDefinition pdf = GetPropertyDefinitionByName(portalId, "TimeZone"); + if (pdf != null) + { + DeletePropertyDefinition(pdf); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Adds a Property Defintion to the Data Store. + /// + /// An ProfilePropertyDefinition object. + /// The Id of the definition (or if negative the errorcode of the error). + /// ----------------------------------------------------------------------------- + public static int AddPropertyDefinition(ProfilePropertyDefinition definition) + { + int portalId = GetEffectivePortalId(definition.PortalId); + if (definition.Required) + { + definition.Visible = true; + } + + int intDefinition = _dataProvider.AddPropertyDefinition( + portalId, + definition.ModuleDefId, + definition.DataType, + definition.DefaultValue, + definition.PropertyCategory, + definition.PropertyName, + definition.ReadOnly, + definition.Required, + definition.ValidationExpression, + definition.ViewOrder, + definition.Visible, + definition.Length, + (int)definition.DefaultVisibility, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(definition, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PROFILEPROPERTY_CREATED); + ClearProfileDefinitionCache(definition.PortalId); + ClearAllUsersInfoProfileCacheByPortal(definition.PortalId); + return intDefinition; } internal static void AddDefaultDefinition(int portalId, string category, string name, string type, int length, int viewOrder, UserVisibilityMode defaultVisibility, @@ -66,6 +140,12 @@ internal static void AddDefaultDefinition(int portalId, string category, string }; AddPropertyDefinition(propertyDefinition); } + + private static void AddDefaultDefinition(int portalId, string category, string name, string strType, int length, UserVisibilityMode defaultVisibility, Dictionary types) + { + _orderCounter += 2; + AddDefaultDefinition(portalId, category, name, strType, length, _orderCounter, defaultVisibility, types); + } private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader dr) { @@ -189,86 +269,6 @@ private static IEnumerable GetPropertyDefinitions(int return definitions; } - - /// ----------------------------------------------------------------------------- - /// - /// Adds the default property definitions for a portal. - /// - /// Id of the Portal. - /// ----------------------------------------------------------------------------- - public static void AddDefaultDefinitions(int portalId) - { - portalId = GetEffectivePortalId(portalId); - - _orderCounter = 1; - var listController = new ListController(); - Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); - - AddDefaultDefinition(portalId, "Name", "Prefix", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Name", "FirstName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Name", "MiddleName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Name", "LastName", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Name", "Suffix", "Text", 50, UserVisibilityMode.AllUsers, dataTypes); - AddDefaultDefinition(portalId, "Address", "Unit", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "Street", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "City", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "Region", "Region", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "Country", "Country", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Address", "PostalCode", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "Telephone", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "Cell", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "Fax", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "Website", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Contact Info", "IM", "Text", 50, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "Biography", "Multi-line Text", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "TimeZone", "TimeZone", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "PreferredTimeZone", "TimeZoneInfo", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "PreferredLocale", "Locale", 0, UserVisibilityMode.AdminOnly, dataTypes); - AddDefaultDefinition(portalId, "Preferences", "Photo", "Image", 0, UserVisibilityMode.AllUsers, dataTypes); - - // 6.0 requires the old TimeZone property to be marked as Deleted - ProfilePropertyDefinition pdf = GetPropertyDefinitionByName(portalId, "TimeZone"); - if (pdf != null) - { - DeletePropertyDefinition(pdf); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Adds a Property Defintion to the Data Store. - /// - /// An ProfilePropertyDefinition object. - /// The Id of the definition (or if negative the errorcode of the error). - /// ----------------------------------------------------------------------------- - public static int AddPropertyDefinition(ProfilePropertyDefinition definition) - { - int portalId = GetEffectivePortalId(definition.PortalId); - if (definition.Required) - { - definition.Visible = true; - } - - int intDefinition = _dataProvider.AddPropertyDefinition( - portalId, - definition.ModuleDefId, - definition.DataType, - definition.DefaultValue, - definition.PropertyCategory, - definition.PropertyName, - definition.ReadOnly, - definition.Required, - definition.ValidationExpression, - definition.ViewOrder, - definition.Visible, - definition.Length, - (int)definition.DefaultVisibility, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog(definition, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PROFILEPROPERTY_CREATED); - ClearProfileDefinitionCache(definition.PortalId); - ClearAllUsersInfoProfileCacheByPortal(definition.PortalId); - return intDefinition; - } /// ----------------------------------------------------------------------------- /// @@ -577,33 +577,6 @@ public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitio return user; } - private static void CreateThumbnails(int fileId) - { - CreateThumbnail(fileId, "l", 64, 64); - CreateThumbnail(fileId, "s", 50, 50); - CreateThumbnail(fileId, "xs", 32, 32); - } - - private static void CreateThumbnail(int fileId, string type, int width, int height) - { - var file = FileManager.Instance.GetFile(fileId); - if (file != null) - { - var folder = FolderManager.Instance.GetFolder(file.FolderId); - var extension = "." + file.Extension; - var sizedPhoto = file.FileName.Replace(extension, "_" + type + extension); - if (!FileManager.Instance.FileExists(folder, sizedPhoto)) - { - using (var content = FileManager.Instance.GetFileContent(file)) - { - var sizedContent = ImageUtils.CreateImage(content, height, width, extension); - - FileManager.Instance.AddFile(folder, sizedPhoto, sizedContent); - } - } - } - } - /// ----------------------------------------------------------------------------- /// /// Validates the Profile properties for the User (determines if all required properties @@ -658,6 +631,33 @@ public static List SearchProfilePropertyValues(int portalId, string prop return res; } + + private static void CreateThumbnails(int fileId) + { + CreateThumbnail(fileId, "l", 64, 64); + CreateThumbnail(fileId, "s", 50, 50); + CreateThumbnail(fileId, "xs", 32, 32); + } + + private static void CreateThumbnail(int fileId, string type, int width, int height) + { + var file = FileManager.Instance.GetFile(fileId); + if (file != null) + { + var folder = FolderManager.Instance.GetFolder(file.FolderId); + var extension = "." + file.Extension; + var sizedPhoto = file.FileName.Replace(extension, "_" + type + extension); + if (!FileManager.Instance.FileExists(folder, sizedPhoto)) + { + using (var content = FileManager.Instance.GetFileContent(file)) + { + var sizedContent = ImageUtils.CreateImage(content, height, width, extension); + + FileManager.Instance.AddFile(folder, sizedPhoto, sizedContent); + } + } + } + } [Obsolete("This method has been deprecated. Please use GetPropertyDefinition(ByVal definitionId As Integer, ByVal portalId As Integer) instead. Scheduled removal in v11.0.0.")] public static ProfilePropertyDefinition GetPropertyDefinition(int definitionId) diff --git a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs index 2303b1f7b5b..150b1897082 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs @@ -36,10 +36,10 @@ public class ProfilePropertyDefinition : BaseEntityInfo private int _length; private int _moduleDefId = Null.NullInteger; private int _portalId; - private ProfileVisibility _profileVisibility = new ProfileVisibility - { - VisibilityMode = UserVisibilityMode.AdminOnly, - }; + private ProfileVisibility _profileVisibility = new ProfileVisibility + { + VisibilityMode = UserVisibilityMode.AdminOnly, + }; private string _propertyCategory; private string _propertyName; @@ -477,45 +477,6 @@ public ProfileVisibility ProfileVisibility } } - /// ----------------------------------------------------------------------------- - /// - /// Clears the IsDirty Flag. - /// - /// ----------------------------------------------------------------------------- - public void ClearIsDirty() - { - this.IsDirty = false; - } - - /// - /// Clone a ProfilePropertyDefinition. - /// - /// A ProfilePropertyDefinition. - public ProfilePropertyDefinition Clone() - { - var clone = new ProfilePropertyDefinition(this.PortalId) - { - DataType = this.DataType, - DefaultValue = this.DefaultValue, - Length = this.Length, - ModuleDefId = this.ModuleDefId, - PropertyCategory = this.PropertyCategory, - PropertyDefinitionId = this.PropertyDefinitionId, - PropertyName = this.PropertyName, - PropertyValue = this.PropertyValue, - ReadOnly = this.ReadOnly, - Required = this.Required, - ValidationExpression = this.ValidationExpression, - ViewOrder = this.ViewOrder, - DefaultVisibility = this.DefaultVisibility, - ProfileVisibility = this.ProfileVisibility.Clone(), - Visible = this.Visible, - Deleted = this.Deleted, - }; - clone.ClearIsDirty(); - return clone; - } - [Obsolete("Deprecated in 6.2 as profile visibility has been extended, keep for compatible with upgrade.. Scheduled removal in v10.0.0.")] [Browsable(false)] [XmlIgnore] @@ -536,5 +497,44 @@ public UserVisibilityMode Visibility this.ProfileVisibility.VisibilityMode = value; } } + + /// ----------------------------------------------------------------------------- + /// + /// Clears the IsDirty Flag. + /// + /// ----------------------------------------------------------------------------- + public void ClearIsDirty() + { + this.IsDirty = false; + } + + /// + /// Clone a ProfilePropertyDefinition. + /// + /// A ProfilePropertyDefinition. + public ProfilePropertyDefinition Clone() + { + var clone = new ProfilePropertyDefinition(this.PortalId) + { + DataType = this.DataType, + DefaultValue = this.DefaultValue, + Length = this.Length, + ModuleDefId = this.ModuleDefId, + PropertyCategory = this.PropertyCategory, + PropertyDefinitionId = this.PropertyDefinitionId, + PropertyName = this.PropertyName, + PropertyValue = this.PropertyValue, + ReadOnly = this.ReadOnly, + Required = this.Required, + ValidationExpression = this.ValidationExpression, + ViewOrder = this.ViewOrder, + DefaultVisibility = this.DefaultVisibility, + ProfileVisibility = this.ProfileVisibility.Clone(), + Visible = this.Visible, + Deleted = this.Deleted, + }; + clone.ClearIsDirty(); + return clone; + } } } diff --git a/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs b/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs index 8333dec14eb..44baf3c7f44 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs @@ -63,12 +63,12 @@ public ProfileVisibility(int portalId, string extendedVisibility) public ProfileVisibility Clone() { - var pv = new ProfileVisibility() - { - VisibilityMode = this.VisibilityMode, - RoleVisibilities = new List(this.RoleVisibilities), - RelationshipVisibilities = new List(this.RelationshipVisibilities), - }; + var pv = new ProfileVisibility() + { + VisibilityMode = this.VisibilityMode, + RoleVisibilities = new List(this.RoleVisibilities), + RelationshipVisibilities = new List(this.RelationshipVisibilities), + }; return pv; } diff --git a/DNN Platform/Library/Entities/Tabs/TabCollection.cs b/DNN Platform/Library/Entities/Tabs/TabCollection.cs index 036785c5fcb..d5009f5ee78 100644 --- a/DNN Platform/Library/Entities/Tabs/TabCollection.cs +++ b/DNN Platform/Library/Entities/Tabs/TabCollection.cs @@ -50,6 +50,12 @@ public TabCollection(SerializationInfo info, StreamingContext context) this._localizedTabs = new Dictionary>(); } + public TabCollection(IEnumerable tabs) + : this() + { + this.AddRange(tabs); + } + public override void OnDeserialization(object sender) { base.OnDeserialization(sender); @@ -60,11 +66,33 @@ public override void OnDeserialization(object sender) this.AddInternal(tab); } } + + public void Add(TabInfo tab) + { + // Call base class to add to base Dictionary + this.Add(tab.TabID, tab); - public TabCollection(IEnumerable tabs) - : this() + // Update all child collections + this.AddInternal(tab); + } + + public void AddRange(IEnumerable tabs) { - this.AddRange(tabs); + foreach (TabInfo tab in tabs) + { + this.Add(tab); + } + } + + private static bool IsLocalizationEnabled() + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return (portalSettings != null) ? portalSettings.ContentLocalizationEnabled : Null.NullBoolean; + } + + private static bool IsLocalizationEnabled(int portalId) + { + return PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalId, false); } private void AddInternal(TabInfo tab) @@ -181,34 +209,6 @@ private List GetDescendants(int tabId, int tabLevel) return descendantTabs; } - private static bool IsLocalizationEnabled() - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return (portalSettings != null) ? portalSettings.ContentLocalizationEnabled : Null.NullBoolean; - } - - private static bool IsLocalizationEnabled(int portalId) - { - return PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalId, false); - } - - public void Add(TabInfo tab) - { - // Call base class to add to base Dictionary - this.Add(tab.TabID, tab); - - // Update all child collections - this.AddInternal(tab); - } - - public void AddRange(IEnumerable tabs) - { - foreach (TabInfo tab in tabs) - { - this.Add(tab); - } - } - public List AsList() { return this._list; diff --git a/DNN Platform/Library/Entities/Tabs/TabController.cs b/DNN Platform/Library/Entities/Tabs/TabController.cs index f9c73be51f9..0bd83530206 100644 --- a/DNN Platform/Library/Entities/Tabs/TabController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabController.cs @@ -46,17 +46,17 @@ namespace DotNetNuke.Entities.Tabs /// 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(); + protected override Func GetFactory() { return () => new TabController(); } - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabController)); - private readonly DataProvider _dataProvider = DataProvider.Instance(); - - 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); - /// /// Gets the current page in current http request. /// @@ -75,31 +75,149 @@ public static TabInfo CurrentPage } } - private bool IsAdminTab(TabInfo tab) + /// + /// Copies the design to children. + /// + /// The parent tab. + /// The skin SRC. + /// The container SRC. + public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, string containerSrc) { - var portal = PortalController.Instance.GetPortal(tab.PortalID); - return portal.AdminTabId == tab.TabID || this.IsAdminTabRecursive(tab, portal.AdminTabId); + CopyDesignToChildren(parentTab, skinSrc, containerSrc, + PortalController.GetActivePortalLanguage(parentTab.PortalID)); } - private bool IsAdminTabRecursive(TabInfo tab, int adminTabId) + /// + /// 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) { - if (tab.ParentId == Null.NullInteger) + bool clearCache = Null.NullBoolean; + List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); + foreach (TabInfo tab in childTabs) { - return false; + if (TabPermissionController.CanAdminPage(tab)) + { + // Update ContentItem If neccessary + 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 (tab.ParentId == adminTabId) + if (clearCache) { - return true; + DataCache.ClearTabsCache(childTabs[0].PortalID); } + } - var parentTab = this.GetTab(tab.ParentId, tab.PortalID); - return this.IsAdminTabRecursive(parentTab, adminTabId); + /// + /// Adds localized copies of the page in all missing languages. + /// + /// + /// + public void AddMissingLanguages(int portalId, int tabId) + { + 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) + { + this.CreateLocalizedCopyInternal(workingTab, locale, false, true, insertAfterOriginal: true); + } + } + } + } } - private bool IsHostTab(TabInfo tab) + /// + /// Adds a tab. + /// + /// The tab to be added. + /// The tab is added to the end of the current Level. + /// + public int AddTab(TabInfo tab) { - return tab.PortalID == Null.NullInteger; + return this.AddTab(tab, true); + } + + 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); } private static void AddAllTabsModules(TabInfo tab) @@ -120,6 +238,114 @@ private static void AddAllTabsModules(TabInfo tab) } } + 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.ToLowerInvariant() == "administrators") + { + 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 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 bool IsHostTab(TabInfo tab) + { + return tab.PortalID == Null.NullInteger; + } + private int AddTabInternal(TabInfo tab, int afterTabId, int beforeTabId, bool includeAllTabsModules) { ValidateTabPath(tab); @@ -356,87 +582,6 @@ private void CreateTabRedirects(TabInfo tab) } } - 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.ToLowerInvariant() == "administrators") - { - 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); @@ -449,6 +594,25 @@ private static void DeserializeTabUrls(XmlNode nodeTabUrl, TabUrlInfo objTabUrl) 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)) + { + Dictionary portalDic = PortalController.GetPortalDictionary(); + if (portalDic != null && portalDic.ContainsKey(tabId)) + { + portalId = portalDic[tabId]; + } + } + + return portalId; + } + private Dictionary> GetAliasSkins(int portalId) { string cacheKey = string.Format(DataCache.TabAliasSkinCacheKey, portalId); @@ -563,30 +727,6 @@ private object GetCustomAliasesCallback(CacheItemArgs cacheItemArgs) return dic; } - 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)) - { - Dictionary portalDic = PortalController.GetPortalDictionary(); - if (portalDic != null && portalDic.ContainsKey(tabId)) - { - portalId = portalDic[tabId]; - } - } - - return portalId; - } - - private IEnumerable GetSiblingTabs(TabInfo objTab) - { - return this.GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, true).WithParentId(objTab.ParentId); - } - private static object GetTabPathDictionaryCallback(CacheItemArgs cacheItemArgs) { string cultureCode = Convert.ToString(cacheItemArgs.ParamList[0]); @@ -606,10 +746,35 @@ private static object GetTabPathDictionaryCallback(CacheItemArgs cacheItemArgs) } finally { - CBO.CloseDataReader(dr, true); + CBO.CloseDataReader(dr, true); + } + + return tabpathDic; + } + + 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, + string.Format( + "Page Exists in portal: {0}, path: {1}, culture: {2}", + tab.PortalID, tab.TabPath, tab.CultureCode)); } + } - return tabpathDic; + private IEnumerable GetSiblingTabs(TabInfo objTab) + { + return this.GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, true).WithParentId(objTab.ParentId); } private Dictionary GetTabSettingsByPortal(int portalId) @@ -650,18 +815,6 @@ private Dictionary GetTabSettingsByPortal(int portalId) }); } - 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); - } - private object GetTabUrlsCallback(CacheItemArgs cacheItemArgs) { var portalID = (int)cacheItemArgs.ParamList[0]; @@ -851,26 +1004,6 @@ private void UpdateTabSettings(ref TabInfo updatedTab) } } - 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, - string.Format( - "Page Exists in portal: {0}, path: {1}, culture: {2}", - tab.PortalID, tab.TabPath, tab.CultureCode)); - } - } - /// /// update content item for the tab when tab name changed. /// @@ -886,60 +1019,6 @@ private void UpdateContentItem(TabInfo tab) } } - /// - /// Adds localized copies of the page in all missing languages. - /// - /// - /// - public void AddMissingLanguages(int portalId, int tabId) - { - 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) - { - this.CreateLocalizedCopyInternal(workingTab, locale, false, true, insertAfterOriginal: true); - } - } - } - } - } - - /// - /// Adds a tab. - /// - /// The tab to be added. - /// The tab is added to the end of the current Level. - /// - public int AddTab(TabInfo tab) - { - return this.AddTab(tab, true); - } - /// /// Adds a tab. /// @@ -1095,32 +1174,6 @@ public void CreateLocalizedCopy(TabInfo originalTab, Locale locale, bool clearCa this.CreateLocalizedCopyInternal(originalTab, locale, true, clearCache); } - 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); - } - } - /// /// Deletes a tab permanently from the database. /// @@ -1161,6 +1214,32 @@ public void DeleteTab(int tabId, int portalId, bool deleteDescendants) this.DeleteTab(tabId, portalId); } + 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); + } + } + /// /// Delete a Setting of a tab instance. /// @@ -2136,85 +2215,6 @@ public void MarkAsPublished(TabInfo tab) EventManager.Instance.OnTabMarkedAsPublished(new TabEventArgs { Tab = tab }); } - /// - /// 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 neccessary - 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. /// @@ -2753,16 +2753,6 @@ public static bool IsSpecialTab(int tabId, int portalId) return isSpecial; } - /// - /// Determines whether is host or admin tab. - /// - /// The tab info. - /// - public bool IsHostOrAdminPage(TabInfo tab) - { - return this.IsHostTab(tab) || this.IsAdminTab(tab); - } - /// /// Determines whether is special tab. /// @@ -2790,6 +2780,16 @@ public static XmlNode SerializeTab(XmlDocument tabXml, TabInfo objTab, bool incl return SerializeTab(tabXml, null, objTab, null, includeContent); } + /// + /// Determines whether is host or admin tab. + /// + /// The tab info. + /// + public bool IsHostOrAdminPage(TabInfo tab) + { + return this.IsHostTab(tab) || this.IsAdminTab(tab); + } + /// /// SerializeTab. /// diff --git a/DNN Platform/Library/Entities/Tabs/TabInfo.cs b/DNN Platform/Library/Entities/Tabs/TabInfo.cs index 18ca9a6d2f6..47e49957304 100644 --- a/DNN Platform/Library/Entities/Tabs/TabInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabInfo.cs @@ -36,6 +36,10 @@ namespace DotNetNuke.Entities.Tabs [Serializable] public class TabInfo : ContentItem, IPropertyAccess { + private static readonly Regex SkinSrcRegex = new Regex(@"([^/]+$)", RegexOptions.CultureInvariant); + private static Dictionary _docTypeCache = new Dictionary(); + private static ReaderWriterLockSlim _docTypeCacheLock = new ReaderWriterLockSlim(); + private string _administratorRoles; private string _authorizedRoles; private TabInfo _defaultLanguageTab; @@ -585,6 +589,14 @@ public List TabUrls [XmlIgnore] public bool UseBaseFriendlyUrls { get; set; } + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { string outputFormat = string.Empty; @@ -750,121 +762,6 @@ public string GetProperty(string propertyName, string format, CultureInfo format return result; } - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - - private static Dictionary _docTypeCache = new Dictionary(); - private static ReaderWriterLockSlim _docTypeCacheLock = new ReaderWriterLockSlim(); - private static readonly Regex SkinSrcRegex = new Regex(@"([^/]+$)", RegexOptions.CultureInvariant); - - /// - /// Look for skin level doctype configuration file, and inject the value into the top of default.aspx - /// when no configuration if found, the doctype for versions prior to 4.4 is used to maintain backwards compatibility with existing skins. - /// Adds xmlns and lang parameters when appropiate. - /// - /// - private string CheckIfDoctypeConfigExists() - { - if (string.IsNullOrEmpty(this.SkinSrc)) - { - return string.Empty; - } - - // loading an XML document from disk for each page request is expensive - // let's implement some local caching - if (!_docTypeCache.ContainsKey(this.SkinSrc)) - { - // appply lock after IF, locking is more expensive than worst case scenario (check disk twice) - _docTypeCacheLock.EnterWriteLock(); - try - { - var docType = this.LoadDocType(); - _docTypeCache[this.SkinSrc] = docType == null ? string.Empty : docType.FirstChild.InnerText; - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - _docTypeCacheLock.ExitWriteLock(); - } - } - - // return if file exists from cache - _docTypeCacheLock.EnterReadLock(); - try - { - return _docTypeCache[this.SkinSrc]; - } - finally - { - _docTypeCacheLock.ExitReadLock(); - } - } - - private XmlDocument LoadDocType() - { - var xmlSkinDocType = new XmlDocument { XmlResolver = null }; - - // default to the skinname.doctype.xml to allow the individual skin to override the skin package - var skinFileName = HttpContext.Current.Server.MapPath(this.SkinSrc.Replace(".ascx", ".doctype.xml")); - if (File.Exists(skinFileName)) - { - xmlSkinDocType.Load(skinFileName); - return xmlSkinDocType; - } - - // use the skin.doctype.xml file - var packageFileName = HttpContext.Current.Server.MapPath(SkinSrcRegex.Replace(this.SkinSrc, "skin.doctype.xml")); - if (File.Exists(packageFileName)) - { - xmlSkinDocType.Load(packageFileName); - return xmlSkinDocType; - } - - // no doctype - return null; - } - - private void IconFileGetter(ref string iconFile, string iconRaw) - { - if ((!string.IsNullOrEmpty(iconRaw) && iconRaw.StartsWith("~")) || 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)) - { - var fileId = Convert.ToInt32(iconRaw.Substring(7)); - fileInfo = FileManager.Instance.GetFile(fileId); - } - else - { - fileInfo = FileManager.Instance.GetFile(this.PortalID, iconRaw); - } - - iconFile = fileInfo != null ? FileManager.Instance.GetUrl(fileInfo) : iconRaw; - } - } - - internal void ClearTabUrls() - { - this._tabUrls = null; - } - - internal void ClearSettingsCache() - { - this._settings = null; - } - public TabInfo Clone() { var clonedTab = new TabInfo(this._localizedTabNameDictionary, this._fullUrlDictionary) @@ -972,6 +869,109 @@ public override void Fill(IDataReader dr) this.IsSystem = Null.SetNullBoolean(dr["IsSystem"]); } + internal void ClearTabUrls() + { + this._tabUrls = null; + } + + internal void ClearSettingsCache() + { + this._settings = null; + } + + /// + /// Look for skin level doctype configuration file, and inject the value into the top of default.aspx + /// when no configuration if found, the doctype for versions prior to 4.4 is used to maintain backwards compatibility with existing skins. + /// Adds xmlns and lang parameters when appropiate. + /// + /// + private string CheckIfDoctypeConfigExists() + { + if (string.IsNullOrEmpty(this.SkinSrc)) + { + return string.Empty; + } + + // loading an XML document from disk for each page request is expensive + // let's implement some local caching + if (!_docTypeCache.ContainsKey(this.SkinSrc)) + { + // appply lock after IF, locking is more expensive than worst case scenario (check disk twice) + _docTypeCacheLock.EnterWriteLock(); + try + { + var docType = this.LoadDocType(); + _docTypeCache[this.SkinSrc] = docType == null ? string.Empty : docType.FirstChild.InnerText; + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + finally + { + _docTypeCacheLock.ExitWriteLock(); + } + } + + // return if file exists from cache + _docTypeCacheLock.EnterReadLock(); + try + { + return _docTypeCache[this.SkinSrc]; + } + finally + { + _docTypeCacheLock.ExitReadLock(); + } + } + + private XmlDocument LoadDocType() + { + var xmlSkinDocType = new XmlDocument { XmlResolver = null }; + + // default to the skinname.doctype.xml to allow the individual skin to override the skin package + var skinFileName = HttpContext.Current.Server.MapPath(this.SkinSrc.Replace(".ascx", ".doctype.xml")); + if (File.Exists(skinFileName)) + { + xmlSkinDocType.Load(skinFileName); + return xmlSkinDocType; + } + + // use the skin.doctype.xml file + var packageFileName = HttpContext.Current.Server.MapPath(SkinSrcRegex.Replace(this.SkinSrc, "skin.doctype.xml")); + if (File.Exists(packageFileName)) + { + xmlSkinDocType.Load(packageFileName); + return xmlSkinDocType; + } + + // no doctype + return null; + } + + private void IconFileGetter(ref string iconFile, string iconRaw) + { + if ((!string.IsNullOrEmpty(iconRaw) && iconRaw.StartsWith("~")) || 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)) + { + var fileId = Convert.ToInt32(iconRaw.Substring(7)); + fileInfo = FileManager.Instance.GetFile(fileId); + } + else + { + fileInfo = FileManager.Instance.GetFile(this.PortalID, iconRaw); + } + + iconFile = fileInfo != null ? FileManager.Instance.GetUrl(fileInfo) : iconRaw; + } + } + public string GetCurrentUrl(string cultureCode) { string url = null; diff --git a/DNN Platform/Library/Entities/Tabs/TabModulesController.cs b/DNN Platform/Library/Entities/Tabs/TabModulesController.cs index d895ed60c84..0c430ba545f 100644 --- a/DNN Platform/Library/Entities/Tabs/TabModulesController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabModulesController.cs @@ -101,6 +101,11 @@ public IList GetTabModuleIdsBySetting(string settingName, string expectedVa } } + protected override Func GetFactory() + { + return () => new TabModulesController(); + } + private static void ConfigureModule(ModuleInfo cloneModule, TabInfo tab) { if (Null.IsNull(cloneModule.StartDate)) @@ -137,10 +142,5 @@ private static IEnumerable GetModules(TabInfo tab) return TabVersionBuilder.Instance.GetCurrentModules(tab.TabID); } - - protected override Func GetFactory() - { - return () => new TabModulesController(); - } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs b/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs index 364249000bc..58b0ece57eb 100644 --- a/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs @@ -72,6 +72,11 @@ public bool CanPublishingBePerformed(int tabID, int portalID) return (workflowID == 1) || (workflowID == -1); } + protected override Func GetFactory() + { + return () => new TabPublishingController(); + } + private void PublishTabInternal(TabInfo tab) { var allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); @@ -121,22 +126,17 @@ private TabPermissionInfo GetAlreadyPermission(TabInfo tab, string permissionKey private TabPermissionInfo GetTabPermissionByRole(int tabID, string permissionKey, int roleID) { var permission = PermissionController.GetPermissionsByTab().Cast().SingleOrDefault(p => p.PermissionKey == permissionKey); - var tabPermission = new TabPermissionInfo - { - TabID = tabID, - PermissionID = permission.PermissionID, - PermissionKey = permission.PermissionKey, - PermissionName = permission.PermissionName, - RoleID = roleID, - UserID = Null.NullInteger, - AllowAccess = true, - }; + var tabPermission = new TabPermissionInfo + { + TabID = tabID, + PermissionID = permission.PermissionID, + PermissionKey = permission.PermissionKey, + PermissionName = permission.PermissionName, + RoleID = roleID, + UserID = Null.NullInteger, + AllowAccess = true, + }; return tabPermission; } - - protected override Func GetFactory() - { - return () => new TabPublishingController(); - } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs index 472dced7cac..bc3a2f92985 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs @@ -20,8 +20,8 @@ namespace DotNetNuke.Entities.Tabs.TabVersions public class TabVersionBuilder : ServiceLocator, ITabVersionBuilder { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabVersionBuilder)); private const int DefaultVersionNumber = 1; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TabVersionBuilder)); private readonly ITabController _tabController; private readonly IModuleController _moduleController; private readonly ITabVersionSettings _tabVersionSettings; @@ -103,33 +103,6 @@ public void Discard(int tabId, int createdByUserId) this.DiscardVersion(tabId, tabVersion); } - private void DiscardVersion(int tabId, TabVersion tabVersion) - { - var unPublishedDetails = this._tabVersionDetailController.GetTabVersionDetails(tabVersion.TabVersionId); - - var currentPublishedVersion = this.GetCurrentVersion(tabId); - TabVersionDetail[] publishedChanges = null; - - if (currentPublishedVersion != null) - { - publishedChanges = this.GetVersionModulesDetails(tabId, this.GetCurrentVersion(tabId).Version).ToArray(); - } - - foreach (var unPublishedDetail in unPublishedDetails) - { - if (publishedChanges == null) - { - this.DiscardDetailWithoutPublishedTabVersions(tabId, unPublishedDetail); - } - else - { - this.DiscardDetailWithPublishedTabVersions(tabId, unPublishedDetail, publishedChanges); - } - } - - this._tabVersionController.DeleteTabVersion(tabId, tabVersion.TabVersionId); - } - public void DeleteVersion(int tabId, int createdByUserId, int version) { this.CheckVersioningEnabled(tabId); @@ -196,6 +169,33 @@ public TabVersion RollBackVesion(int tabId, int createdByUserId, int version) return this.PublishVersion(this.GetCurrentPortalId(), tabId, createdByUserId, newVersion); } + private void DiscardVersion(int tabId, TabVersion tabVersion) + { + var unPublishedDetails = this._tabVersionDetailController.GetTabVersionDetails(tabVersion.TabVersionId); + + var currentPublishedVersion = this.GetCurrentVersion(tabId); + TabVersionDetail[] publishedChanges = null; + + if (currentPublishedVersion != null) + { + publishedChanges = this.GetVersionModulesDetails(tabId, this.GetCurrentVersion(tabId).Version).ToArray(); + } + + foreach (var unPublishedDetail in unPublishedDetails) + { + if (publishedChanges == null) + { + this.DiscardDetailWithoutPublishedTabVersions(tabId, unPublishedDetail); + } + else + { + this.DiscardDetailWithPublishedTabVersions(tabId, unPublishedDetail, publishedChanges); + } + } + + this._tabVersionController.DeleteTabVersion(tabId, tabVersion.TabVersionId); + } + public TabVersion CreateNewVersion(int tabId, int createdByUserId) { return this.CreateNewVersion(this.GetCurrentPortalId(), tabId, createdByUserId); @@ -272,6 +272,61 @@ public int GetModuleContentLatestVersion(ModuleInfo module) return versionableController != null ? versionableController.GetLatestVersion(module.ModuleID) : DefaultVersionNumber; } + protected override Func GetFactory() + { + return () => new TabVersionBuilder(); + } + + private static IEnumerable GetSnapShot(IEnumerable tabVersionDetails) + { + var versionModules = new Dictionary(); + foreach (var tabVersionDetail in tabVersionDetails) + { + switch (tabVersionDetail.Action) + { + case TabVersionDetailAction.Added: + case TabVersionDetailAction.Modified: + if (versionModules.ContainsKey(tabVersionDetail.ModuleId)) + { + versionModules[tabVersionDetail.ModuleId] = JoinVersionDetails(versionModules[tabVersionDetail.ModuleId], tabVersionDetail); + } + else + { + versionModules.Add(tabVersionDetail.ModuleId, tabVersionDetail); + } + + break; + case TabVersionDetailAction.Deleted: + if (versionModules.ContainsKey(tabVersionDetail.ModuleId)) + { + versionModules.Remove(tabVersionDetail.ModuleId); + } + + break; + case TabVersionDetailAction.Reset: + versionModules.Clear(); + break; + } + } + + // Return Snapshot ordering by PaneName and ModuleOrder (this is required as Skin.cs does not order by these fields) + return versionModules.Values + .OrderBy(m => m.PaneName) + .ThenBy(m => m.ModuleOrder) + .ToList(); + } + + private static TabVersionDetail JoinVersionDetails(TabVersionDetail tabVersionDetail, TabVersionDetail newVersionDetail) + { + // Movement changes have not ModuleVersion + if (newVersionDetail.ModuleVersion == Null.NullInteger) + { + newVersionDetail.ModuleVersion = tabVersionDetail.ModuleVersion; + } + + return newVersionDetail; + } + private IEnumerable GetCurrentModulesInternal(int tabId) { var versioningEnabled = this._portalSettings != null && @@ -556,14 +611,14 @@ private TabVersion PublishVersion(int portalId, int tabId, int createdByUserID, private IEnumerable CopyVersionDetails(IEnumerable tabVersionDetails) { - return tabVersionDetails.Select(tabVersionDetail => new TabVersionDetail - { - ModuleId = tabVersionDetail.ModuleId, - ModuleOrder = tabVersionDetail.ModuleOrder, - ModuleVersion = tabVersionDetail.ModuleVersion, - PaneName = tabVersionDetail.PaneName, - Action = tabVersionDetail.Action, - }).ToList(); + return tabVersionDetails.Select(tabVersionDetail => new TabVersionDetail + { + ModuleId = tabVersionDetail.ModuleId, + ModuleOrder = tabVersionDetail.ModuleOrder, + ModuleVersion = tabVersionDetail.ModuleVersion, + PaneName = tabVersionDetail.PaneName, + Action = tabVersionDetail.Action, + }).ToList(); } private void CheckVersioningEnabled(int tabId) @@ -765,56 +820,6 @@ private IVersionable GetVersionableController(ModuleInfo moduleInfo) return null; } - private static IEnumerable GetSnapShot(IEnumerable tabVersionDetails) - { - var versionModules = new Dictionary(); - foreach (var tabVersionDetail in tabVersionDetails) - { - switch (tabVersionDetail.Action) - { - case TabVersionDetailAction.Added: - case TabVersionDetailAction.Modified: - if (versionModules.ContainsKey(tabVersionDetail.ModuleId)) - { - versionModules[tabVersionDetail.ModuleId] = JoinVersionDetails(versionModules[tabVersionDetail.ModuleId], tabVersionDetail); - } - else - { - versionModules.Add(tabVersionDetail.ModuleId, tabVersionDetail); - } - - break; - case TabVersionDetailAction.Deleted: - if (versionModules.ContainsKey(tabVersionDetail.ModuleId)) - { - versionModules.Remove(tabVersionDetail.ModuleId); - } - - break; - case TabVersionDetailAction.Reset: - versionModules.Clear(); - break; - } - } - - // Return Snapshot ordering by PaneName and ModuleOrder (this is required as Skin.cs does not order by these fields) - return versionModules.Values - .OrderBy(m => m.PaneName) - .ThenBy(m => m.ModuleOrder) - .ToList(); - } - - private static TabVersionDetail JoinVersionDetails(TabVersionDetail tabVersionDetail, TabVersionDetail newVersionDetail) - { - // Movement changes have not ModuleVersion - if (newVersionDetail.ModuleVersion == Null.NullInteger) - { - newVersionDetail.ModuleVersion = tabVersionDetail.ModuleVersion; - } - - return newVersionDetail; - } - private void CreateFirstTabVersion(int tabId, TabInfo tab, IEnumerable modules) { var tabVersion = this._tabVersionController.CreateTabVersion(tabId, tab.CreatedByUserID, true); @@ -822,15 +827,15 @@ private void CreateFirstTabVersion(int tabId, TabInfo tab, IEnumerable GetFactory() - { - return () => new TabVersionBuilder(); - } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs index 8cde170ecab..882c2c17867 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionController.cs @@ -92,9 +92,9 @@ public void DeleteTabVersionDetailByModule(int moduleId) Provider.DeleteTabVersionDetailByModule(moduleId); } - private void ClearCache(int tabId) + protected override Func GetFactory() { - DataCache.RemoveCache(GetTabVersionsCacheKey(tabId)); + return () => new TabVersionController(); } private static string GetTabVersionsCacheKey(int tabId) @@ -102,9 +102,9 @@ private static string GetTabVersionsCacheKey(int tabId) return string.Format(DataCache.TabVersionsCacheKey, tabId); } - protected override Func GetFactory() + private void ClearCache(int tabId) { - return () => new TabVersionController(); + DataCache.RemoveCache(GetTabVersionsCacheKey(tabId)); } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs index a360144d2ea..79cddbc2617 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs @@ -73,14 +73,14 @@ public void ClearCache(int tabVersionId) DataCache.RemoveCache(GetTabVersionDetailCacheKey(tabVersionId)); } - private static string GetTabVersionDetailCacheKey(int tabVersionId) - { - return string.Format(DataCache.TabVersionDetailsCacheKey, tabVersionId); - } - protected override System.Func GetFactory() { return () => new TabVersionDetailController(); } + + private static string GetTabVersionDetailCacheKey(int tabVersionId) + { + return string.Format(DataCache.TabVersionDetailsCacheKey, tabVersionId); + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs index a63071fcd4e..96f15b8950d 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs @@ -163,6 +163,11 @@ public void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int original } } + protected override Func GetFactory() + { + return () => new TabVersionTracker(); + } + private static void ProcessAdditionDetail(ModuleInfo module, int moduleVersion, int userId, TabVersion targetVersion) { if (IsHostModule(module)) @@ -259,10 +264,5 @@ private static TabVersionDetail CreateNewTabVersionDetailObjectFromModule(int ta Action = action, }; } - - protected override Func GetFactory() - { - return () => new TabVersionTracker(); - } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs b/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs index b195838d044..01318ca0ac3 100644 --- a/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs @@ -30,11 +30,6 @@ public TabWorkflowTracker() this._workflowManager = WorkflowManager.Instance; this._tabWorkflowSettings = TabWorkflowSettings.Instance; } - - protected override Func GetFactory() - { - return () => new TabWorkflowTracker(); - } /// /// Tracks a workflow instance when a module is added to a page. @@ -57,6 +52,11 @@ public void TrackModuleModification(ModuleInfo module, int moduleVersion, int us { this.NotifyWorkflowAboutChanges(module.PortalID, module.TabID, userId); } + + protected override Func GetFactory() + { + return () => new TabWorkflowTracker(); + } /// /// Tracks a workflow instance when a module is deleted from a page. diff --git a/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs b/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs index c7269f7263e..458d69258d7 100644 --- a/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs @@ -20,12 +20,12 @@ namespace DotNetNuke.Entities.Urls public class AdvancedFriendlyUrlProvider : FriendlyUrlProviderBase { + private const string CodePattern = @"(?:\&|\?)language=(?[A-Za-z]{2,3}-[A-Za-z0-9]{2,4}(-[A-Za-z]{2}){0,1})"; + private static readonly Regex FriendlyPathRegex = new Regex("(.[^\\\\?]*)\\\\?(.*)", RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex DefaultPageRegex = new Regex(Globals.glbDefaultPage, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); 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 const string CodePattern = @"(?:\&|\?)language=(?[A-Za-z]{2,3}-[A-Za-z0-9]{2,4}(-[A-Za-z]{2}){0,1})"; private static readonly Regex CodePatternRegex = new Regex(CodePattern, RegexOptions.Compiled); internal AdvancedFriendlyUrlProvider(NameValueCollection attributes) @@ -33,54 +33,6 @@ internal AdvancedFriendlyUrlProvider(NameValueCollection attributes) { } - internal override string FriendlyUrl(TabInfo tab, string path) - { - return this.FriendlyUrl(tab, path, Globals.glbDefaultPage, PortalController.Instance.GetCurrentPortalSettings()); - } - - internal override string FriendlyUrl(TabInfo tab, string path, string pageName) - { - return this.FriendlyUrl(tab, path, pageName, PortalController.Instance.GetCurrentPortalSettings()); - } - - internal override string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings portalSettings) - { - if (portalSettings == null) - { - throw new ArgumentNullException("portalSettings"); - } - - return this.FriendlyUrlInternal(tab, path, pageName, string.Empty, (PortalSettings)portalSettings); - } - - internal override string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) - { - return this.FriendlyUrlInternal(tab, path, pageName, portalAlias, null); - } - - /// - /// Return a FriendlyUrl for the supplied Tab, but don't improve it past the standard DNN Friendly Url version. - /// - /// - internal static string BaseFriendlyUrl(TabInfo tab, string path, string pageName, string httpAlias, FriendlyUrlSettings settings) - { - bool cultureSpecificAlias; - - // Call GetFriendlyAlias to get the Alias part of the url - string friendlyPath = GetFriendlyAlias( - path, - ref httpAlias, - tab.PortalID, - settings, - null, - out cultureSpecificAlias); - - // Call GetFriendlyQueryString to get the QueryString part of the url - friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, settings); - - return friendlyPath; - } - /// /// Return a full-improved Friendly Url for the supplied tab. /// @@ -113,6 +65,29 @@ public static string ImprovedFriendlyUrl( parentTraceId); } + /// + /// Return a FriendlyUrl for the supplied Tab, but don't improve it past the standard DNN Friendly Url version. + /// + /// + internal static string BaseFriendlyUrl(TabInfo tab, string path, string pageName, string httpAlias, FriendlyUrlSettings settings) + { + bool cultureSpecificAlias; + + // Call GetFriendlyAlias to get the Alias part of the url + string friendlyPath = GetFriendlyAlias( + path, + ref httpAlias, + tab.PortalID, + settings, + null, + out cultureSpecificAlias); + + // Call GetFriendlyQueryString to get the QueryString part of the url + friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, settings); + + return friendlyPath; + } + internal static string ImprovedFriendlyUrlWithMessages( TabInfo tab, string path, @@ -162,6 +137,88 @@ internal static string ImprovedFriendlyUrlWithMessages( return friendlyPath; } + internal override string FriendlyUrl(TabInfo tab, string path) + { + return this.FriendlyUrl(tab, path, Globals.glbDefaultPage, PortalController.Instance.GetCurrentPortalSettings()); + } + + internal override string FriendlyUrl(TabInfo tab, string path, string pageName) + { + return this.FriendlyUrl(tab, path, pageName, PortalController.Instance.GetCurrentPortalSettings()); + } + + internal override string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings portalSettings) + { + if (portalSettings == null) + { + throw new ArgumentNullException("portalSettings"); + } + + return this.FriendlyUrlInternal(tab, path, pageName, string.Empty, (PortalSettings)portalSettings); + } + + internal override string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) + { + return this.FriendlyUrlInternal(tab, path, pageName, portalAlias, null); + } + + internal static string GetCultureOfPath(string path) + { + string code = string.Empty; + MatchCollection matches = CodePatternRegex.Matches(path); + if (matches.Count > 0) + { + foreach (Match langMatch in matches) + { + if (langMatch.Success) + { + Group langGroup = langMatch.Groups["cc"]; + if (langGroup.Success) + { + code = langGroup.Value; + break; + } + } + } + } + + return code; + } + + internal static string ForceLowerCaseIfAllowed(TabInfo tab, string url, FriendlyUrlSettings settings) + { + // 606 : include regex to stop lower case in certain circumstances + // 840 : change to re-introduce lower case restrictions on admin / host tabs + if (tab != null) + { + if (!(tab.IsSuperTab || RewriteController.IsAdminTab(tab.PortalID, tab.TabPath, settings))) + { + bool forceLowerCase = settings.ForceLowerCase; + if (forceLowerCase) + { + if (!string.IsNullOrEmpty(settings.ForceLowerCaseRegex)) + { + var rx = RegexUtils.GetCachedRegex(settings.ForceLowerCaseRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + forceLowerCase = !rx.IsMatch(url); + } + } + + if (forceLowerCase) + { + // don't force lower case for Urls excluded from being 'friendly' + forceLowerCase = !RewriteController.IsExcludedFromFriendlyUrls(tab, settings, false); + } + + if (forceLowerCase) + { + url = url.ToLowerInvariant(); + } + } + } + + return url; + } + private static string AddPage(string path, string pageName) { string friendlyPath = path; @@ -398,6 +455,43 @@ private static string DeterminePageNameAndExtension(ref string pageName, Friendl return pageAndExtension; } + private static PortalAliasInfo GetAliasForPortal(string httpAlias, int portalId, ref List messages) + { + // if no match found, then call database to find (don't rely on cache for this one, because it is an exception event, not an expected event) + PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAlias(httpAlias, portalId); + if (alias == null) + { + // no match between alias and portal id + var aliasArray = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); + 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"); + } + else + { + messages.Add("Portal Id " + portalId.ToString() + + " does not match http alias and no usable alias could be found"); + } + } + + return alias; + } + + private static string GetCultureOfSettings(PortalSettings portalSettings) + { + // note! should be replaced with compiled call to portalSettings.CultureCode property when base supported version is increased. + string cultureCode = string.Empty; + PropertyInfo cultureCodePi = portalSettings.GetType().GetProperty("CultureCode"); + if (cultureCodePi != null) + { + cultureCode = (string)cultureCodePi.GetValue(portalSettings, null); + } + + return cultureCode; + } + private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, string portalAlias, PortalSettings portalSettings) { Guid parentTraceId = Guid.Empty; @@ -461,11 +555,11 @@ private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, st if (tab != null && portalSettings.SSLEnabled && tab.IsSecure && friendlyPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { - friendlyPath = "https://" + friendlyPath.Substring("http://".Length); + friendlyPath = "https://" + friendlyPath.Substring("http://".Length); // If portal's "SSL URL" setting is defined: Use "SSL URL" instaed of current portal alias - var sslUrl = portalSettings.SSLURL; - if (!string.IsNullOrEmpty(sslUrl)) + var sslUrl = portalSettings.SSLURL; + if (!string.IsNullOrEmpty(sslUrl)) { friendlyPath = friendlyPath.Replace("https://" + portalAlias, "https://" + sslUrl); } @@ -474,66 +568,6 @@ private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, st return friendlyPath; } - private static PortalAliasInfo GetAliasForPortal(string httpAlias, int portalId, ref List messages) - { - // if no match found, then call database to find (don't rely on cache for this one, because it is an exception event, not an expected event) - PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAlias(httpAlias, portalId); - if (alias == null) - { - // no match between alias and portal id - var aliasArray = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); - 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"); - } - else - { - messages.Add("Portal Id " + portalId.ToString() + - " does not match http alias and no usable alias could be found"); - } - } - - return alias; - } - - internal static string GetCultureOfPath(string path) - { - string code = string.Empty; - MatchCollection matches = CodePatternRegex.Matches(path); - if (matches.Count > 0) - { - foreach (Match langMatch in matches) - { - if (langMatch.Success) - { - Group langGroup = langMatch.Groups["cc"]; - if (langGroup.Success) - { - code = langGroup.Value; - break; - } - } - } - } - - return code; - } - - private static string GetCultureOfSettings(PortalSettings portalSettings) - { - // note! should be replaced with compiled call to portalSettings.CultureCode property when base supported version is increased. - string cultureCode = string.Empty; - PropertyInfo cultureCodePi = portalSettings.GetType().GetProperty("CultureCode"); - if (cultureCodePi != null) - { - cultureCode = (string)cultureCodePi.GetValue(portalSettings, null); - } - - return cultureCode; - } - private static string GetFriendlyAlias( string path, ref string httpAlias, @@ -1430,39 +1464,5 @@ private static bool TransformStandardPath(ref string newPath, ref string newTabP return builtInUrl; } - - internal static string ForceLowerCaseIfAllowed(TabInfo tab, string url, FriendlyUrlSettings settings) - { - // 606 : include regex to stop lower case in certain circumstances - // 840 : change to re-introduce lower case restrictions on admin / host tabs - if (tab != null) - { - if (!(tab.IsSuperTab || RewriteController.IsAdminTab(tab.PortalID, tab.TabPath, settings))) - { - bool forceLowerCase = settings.ForceLowerCase; - if (forceLowerCase) - { - if (!string.IsNullOrEmpty(settings.ForceLowerCaseRegex)) - { - var rx = RegexUtils.GetCachedRegex(settings.ForceLowerCaseRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - forceLowerCase = !rx.IsMatch(url); - } - } - - if (forceLowerCase) - { - // don't force lower case for Urls excluded from being 'friendly' - forceLowerCase = !RewriteController.IsExcludedFromFriendlyUrls(tab, settings, false); - } - - if (forceLowerCase) - { - url = url.ToLowerInvariant(); - } - } - } - - return url; - } } } diff --git a/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs b/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs index 88ec76e5d5d..b6db0fe9dcd 100644 --- a/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs +++ b/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs @@ -30,14 +30,130 @@ namespace DotNetNuke.Entities.Urls public class AdvancedUrlRewriter : UrlRewriterBase { + private const string _productName = "AdvancedUrlRewriter"; private static readonly Regex DefaultPageRegex = new Regex(@"(?.[^&]+)=$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex UrlSlashesRegex = new Regex("[\\\\/]\\.\\.[\\\\/]", RegexOptions.Compiled); private static readonly Regex AliasUrlRegex = new Regex(@"(?:^(?http[s]{0,1}://){0,1})(?:(?_ALIAS_)(?$|\?[\w]*|/[\w]*))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - private const string _productName = "AdvancedUrlRewriter"; private FriendlyUrlSettings _settings; + public void ProcessTestRequestWithContext( + HttpContext context, + Uri requestUri, + bool useFriendlyUrls, + UrlAction result, + FriendlyUrlSettings settings) + { + Guid parentTraceId = Guid.Empty; + this._settings = settings; + this.ProcessRequest( + context, + requestUri, + useFriendlyUrls, + result, + settings, + false, + parentTraceId); + } + + internal static void RewriteAsChildAliasRoot( + HttpContext context, + UrlAction result, + string aliasQueryString, + FriendlyUrlSettings settings) + { + string culture = null; + + // look for specific alias to rewrite language parameter + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (result.PortalId > -1 && result.HttpAlias != null) + { + culture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); + } + + if (string.IsNullOrEmpty(culture)) + + // 732 : when no culture returned can be "" as well as null : no culture causes no rewrite, which results in redirect to parent alias + { + // set the default culture code here + // 735 : switch to custom method for getting portal + PortalInfo pi = CacheController.GetPortal(result.PortalId, false); + if (pi != null) + { + culture = pi.DefaultLanguage; + } + } + + if (!string.IsNullOrEmpty(culture)) // a culture was identified for the alias root + { + if (RewriteController.AddLanguageCodeToRewritePath(ref aliasQueryString, culture)) + { + result.CultureCode = culture; + } + + result.DoRewrite = true; + result.RewritePath = "~/" + Globals.glbDefaultPage + aliasQueryString; + + // the expected /default.aspx path (defaultPageUrl) matches the requested Url (/default.aspx) + if (context != null) + { + // only do if not testing + RewriterUtils.RewriteUrl(context, result.RewritePath); + } + } + } + + internal static bool CheckForChildPortalRootUrl(string requestUrl, UrlAction result, out string aliasQueryString) + { + bool isChildPortalRootUrl = false; + + // what we are going to test for here is that if this is a child portal request, for the /default.aspx of the child portal + // then we are going to avoid the core 302 redirect to ?alias=portalALias by rewriting to the /default.aspx of the site root + // 684 : don't convert querystring items to lower case + // do the check by constructing what a child alias url would look like and compare it with the requested urls + // 912 : when requested without a valid portal alias, portalALias is null. Refuse and return false. + aliasQueryString = null; + if (result.PortalAlias != null && result.PortalAlias.HTTPAlias != null) + { + string defaultPageUrl = result.Scheme + result.PortalAlias.HTTPAlias + "/" + + Globals.glbDefaultPage.ToLowerInvariant(); // child alias Url with /default.aspx + + // 660 : look for a querystring on the site root for a child portal, and handle it if so + if (string.CompareOrdinal(requestUrl.ToLowerInvariant(), defaultPageUrl) == 0) + { + // exact match : that's the alias root + isChildPortalRootUrl = true; + aliasQueryString = string.Empty; + } + + if (!isChildPortalRootUrl && requestUrl.Contains("?")) + { + // is we didn't get an exact match but there is a querystring, then investigate + string[] requestUrlParts = requestUrl.Split('?'); + if (requestUrlParts.GetUpperBound(0) > 0) + { + string rootPart = requestUrlParts[0]; + string queryString = requestUrlParts[1]; + if (string.Compare(rootPart, defaultPageUrl, StringComparison.OrdinalIgnoreCase) == 0) + { + // rewrite, but put in the querystring on the rewrite path + isChildPortalRootUrl = true; + aliasQueryString = "?" + queryString; + + // 674: check for 301 if this value is a tabid/xx - otherwise the url will just evaluate as is + if (queryString.ToLowerInvariant().StartsWith("tabid=")) + { + result.Action = ActionType.CheckFor301; + } + } + } + } + } + + return isChildPortalRootUrl; + } + internal override void RewriteUrl(object sender, EventArgs e) { Guid parentTraceId = Guid.Empty; @@ -81,11 +197,11 @@ internal override void RewriteUrl(object sender, EventArgs e) // 829 : change constructor to stop using physical path var result = new UrlAction(request) - { - IsSecureConnection = request.IsSecureConnection, - IsSSLOffloaded = UrlUtils.IsSslOffloadEnabled(request), - RawUrl = request.RawUrl, - }; + { + IsSecureConnection = request.IsSecureConnection, + IsSSLOffloaded = UrlUtils.IsSslOffloadEnabled(request), + RawUrl = request.RawUrl, + }; this.ProcessRequest( app.Context, app.Context.Request.Url, @@ -97,1235 +213,1335 @@ internal override void RewriteUrl(object sender, EventArgs e) } } - public void ProcessTestRequestWithContext( + protected bool IsPortalAliasIncorrect( HttpContext context, + HttpRequest request, Uri requestUri, - bool useFriendlyUrls, UrlAction result, - FriendlyUrlSettings settings) + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + Guid parentTraceId, + out string httpAlias) { - Guid parentTraceId = Guid.Empty; - this._settings = settings; - this.ProcessRequest( - context, - requestUri, - useFriendlyUrls, - result, - settings, - false, - parentTraceId); - } + // now check to make sure it's the primary portal alias for this portal/language/browser + bool incorrectAlias = false; + httpAlias = null; - private PortalAliasInfo GetPortalAlias(FriendlyUrlSettings settings, string requestUrl, out bool redirectAlias, out bool isPrimaryAlias, out string wrongAlias) - { - PortalAliasInfo aliasInfo = null; - redirectAlias = false; - wrongAlias = null; - isPrimaryAlias = false; - OrderedDictionary portalAliases = TabIndexController.GetPortalAliases(settings); - foreach (string alias in portalAliases.Keys) + // if (result.RedirectAllowed && result.PortalId > -1) + if (result.PortalId > -1) // portal has been identified { - var urlToMatch = requestUrl; + var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - // in fact, requested url should contain alias - // for better performance, need to check whether we want to proceed with a whole url matching or not - // if alias is not a part of url -> let's proceed to the next iteration - var aliasIndex = urlToMatch.IndexOf(alias, StringComparison.InvariantCultureIgnoreCase); - if (aliasIndex < 0) - { - continue; - } - else + if (queryStringCol != null && queryStringCol["forceAlias"] != "true") { - // we do not accept URL if the first occurence of alias is presented somewhere in the query string - var queryIndex = urlToMatch.IndexOf("?", StringComparison.InvariantCultureIgnoreCase); - if (queryIndex >= 0 && queryIndex < aliasIndex) + if (portalAliases.Count > 0) { - // alias is in the query string, go to the next alias - continue; - } + string checkAlias = result.HttpAlias; + bool continueLoop = true; + bool triedWWW = false; + while (httpAlias == null && continueLoop) + { + if (portalAliases.ContainsAlias(result.PortalId, checkAlias)) + { + if (portalAliases.Count > 0) + { + // var cpa = portalAliases.GetAliasByPortalIdAndSettings(result); + string url = requestUri.ToString(); + RewriteController.CheckLanguageMatch(ref url, result); + var cpa = portalAliases + .Where(a => a.IsPrimary || result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect) + .GetAliasByPortalIdAndSettings(result.PortalId, result, result.CultureCode, result.BrowserType); - // we are fine here, lets prepare URL to be validated in regex - urlToMatch = urlToMatch.ReplaceIgnoreCase(alias, "_ALIAS_"); - } + if (cpa != null) + { + httpAlias = cpa.HTTPAlias; + continueLoop = false; + } - // check whether requested URL has the right URL format containing existing alias - // i.e. url is http://dnndev.me/site1/query?string=test, alias is dnndev.me/site1 - // in the below expression we will validate following value http://_ALIAS_/query?string=test - var aliasMatch = AliasUrlRegex.Match(urlToMatch); - if (aliasMatch.Success) - { - // check for mobile browser and matching - var aliasEx = (PortalAliasInfo)portalAliases[alias]; - redirectAlias = aliasEx.Redirect; - if (redirectAlias) - { - wrongAlias = alias; - } + if (string.IsNullOrEmpty(result.CultureCode) && cpa == null) + { + // if there is a specific culture for this portal alias, then check that + string culture = portalAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); - isPrimaryAlias = aliasEx.IsPrimary; - aliasInfo = aliasEx; - break; - } - } + // if this matches the alias of the request, then we know we have the correct alias because it is a specific culture + if (!string.IsNullOrEmpty(culture)) + { + continueLoop = false; + } + } + } + } - return aliasInfo; - } + // check whether to still go on or not + if (continueLoop) + { + // this alias doesn't exist in the list + // check if it has a www on it - if not, try adding, if it does, try removing + if (!triedWWW) + { + triedWWW = true; // now tried adding/removing www + if (checkAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) + { + checkAlias = checkAlias.Substring(4); + } + else + { + checkAlias = "www." + checkAlias; + } + } + else + { + // last thing to try, get the default language and see if there is a portal alias for that + // thus, any aliases not identified as belonging to a language are redirected back to the + // alias named for the default language + continueLoop = false; - private void ProcessRequest( - HttpContext context, - Uri requestUri, - bool useFriendlyUrls, - UrlAction result, - FriendlyUrlSettings settings, - bool allowSettingsChange, - Guid parentTraceId) - { - bool finished = false; - bool showDebug = false; - bool postRequest = false; + // 735 : switch to custom method for getting portal + PortalInfo pi = CacheController.GetPortal(result.PortalId, false); + if (pi != null) + { + string cultureCode = pi.DefaultLanguage; + if (!string.IsNullOrEmpty(cultureCode)) + { + var primaryPortalAlias = portalAliases.GetAliasByPortalIdAndSettings(result.PortalId, result, cultureCode, settings); + if (primaryPortalAlias != null) + { + httpAlias = primaryPortalAlias.HTTPAlias; + } + } + } + } + } + } + } - HttpRequest request = context.Request; - HttpResponse response = context.Response; - string requestType = request.RequestType; - NameValueCollection queryStringCol = request.QueryString; + // check to see if it is a custom tab alais - in that case, it is allowed to be requested for the tab + if (CheckIfAliasIsCustomTabAlias(ref result, httpAlias, settings)) + { + // change the primary alias to the custom tab alias that has been requested. + result.PrimaryAlias = result.PortalAlias; + } + else + if (httpAlias != null && string.Compare(httpAlias, result.HttpAlias, StringComparison.OrdinalIgnoreCase) != 0) + { + incorrectAlias = true; + } + } + } - try - { - string fullUrl, querystring; + return incorrectAlias; + } - // 699: get the full url based on the request and the quersytring, rather than the requestUri.ToString() - // there is a difference in encoding, which can corrupt results when an encoded value is in the querystring - RewriteController.GetUrlWithQuerystring(request, requestUri, out fullUrl, out querystring); + private static void ShowDebugData(HttpContext context, string requestUri, UrlAction result, Exception ex) + { + if (context != null) + { + HttpResponse response = context.Response; - showDebug = CheckForDebug(request, queryStringCol, settings.AllowDebugCode); - string ignoreRegex = settings.IgnoreRegex; - bool ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); - bool redirectAlias = false; - if (!ignoreRequest) + // handle null responses wherever they might be found - this routine must be tolerant to all kinds of invalid inputs + if (requestUri == null) { - // set original path - context.Items["UrlRewrite:OriginalUrl"] = requestUri.AbsoluteUri; - - // set the path of the result object, and determine if a redirect is allowed on this request - result.SetOriginalPath(requestUri.ToString(), settings); - - // 737 : set the mobile browser - result.SetBrowserType(request, response, settings); + requestUri = "null Uri"; + } - // add to context - context.Items["UrlRewrite:BrowserType"] = result.BrowserType.ToString(); + string finalUrl = "null final Url"; + string rewritePath = "null rewrite path"; + string action = "null action"; + if (result != null) + { + finalUrl = result.FinalUrl; + action = result.Action.ToString(); + rewritePath = result.RewritePath; + } - // 839 : split out this check - result.SetRedirectAllowed(result.OriginalPath, settings); + // format up the error message to show + const string debugMsg = "{0}, {1}, {2}, {3}, {4}, {5}, {6}"; + string productVer = DotNetNukeContext.Current.Application.Version.ToString(); + string portalSettings = string.Empty; + string browser = "Unknown"; - // find the portal alias first - string wrongAlias; - bool isPrimaryAlias; - var requestedAlias = this.GetPortalAlias(settings, fullUrl, out redirectAlias, out isPrimaryAlias, out wrongAlias); + // 949 : don't rely on 'result' being non-null + if (result != null) + { + browser = result.BrowserType.ToString(); + } - if (requestedAlias != null) + if (context.Items.Contains("PortalSettings")) + { + var ps = (PortalSettings)context.Items["PortalSettings"]; + if (ps != null) { - // 827 : now get the correct settings for this portal (if not a test request) - // 839 : separate out redirect check as well and move above first redirect test (ConfigurePortalAliasRedirect) - if (allowSettingsChange) - { - settings = new FriendlyUrlSettings(requestedAlias.PortalID); - result.SetRedirectAllowed(result.OriginalPath, settings); - } - - result.PortalAlias = requestedAlias; - result.PrimaryAlias = requestedAlias; // this is the primary alias - result.PortalId = requestedAlias.PortalID; - result.CultureCode = requestedAlias.CultureCode; - - // get the portal alias mapping for this portal - result.PortalAliasMapping = PortalSettingsController.Instance().GetPortalAliasMappingMode(requestedAlias.PortalID); - - // if requested alias wasn't the primary, we have a replacement, redirects are allowed and the portal alias mapping mode is redirect - // then do a redirect based on the wrong portal - if ((redirectAlias && wrongAlias != null) && result.RedirectAllowed && result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect) - { - // this is the alias, we are going to enforce it as the primary alias - result.PortalAlias = requestedAlias; - result.PrimaryAlias = requestedAlias; - - // going to redirect this alias because it is incorrect - // or do we just want to mark as 'check for 301??' - redirectAlias = ConfigurePortalAliasRedirect( - ref result, - wrongAlias, - requestedAlias.HTTPAlias, - false, - settings.InternalAliasList, - settings); - } - else + portalSettings = ps.PortalId.ToString(); + if (ps.PortalAlias != null) { - // do not redirect the wrong alias, but set the primary alias value - if (wrongAlias != null) - { - // get the portal alias info for the requested alias (which is the wrong one) - // and set that as the alias, but also set the found alias as the primary - PortalAliasInfo wrongAliasInfo = PortalAliasController.Instance.GetPortalAlias(wrongAlias); - if (wrongAliasInfo != null) - { - result.PortalAlias = wrongAliasInfo; - result.PrimaryAlias = requestedAlias; - } - } + portalSettings += ":" + ps.PortalAlias.HTTPAlias; } } } - ignoreRegex = settings.IgnoreRegex; - ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); - if (!ignoreRequest) + response.AppendHeader( + "X-" + _productName + "-Debug", + string.Format(debugMsg, requestUri, finalUrl, rewritePath, action, productVer, + portalSettings, browser)); + int msgNum = 1; + if (result != null) { - // check to see if a post request - if (request.RequestType == "POST") + foreach (string msg in result.DebugMessages) { - postRequest = true; + response.AppendHeader("X-" + _productName + "-Debug-" + msgNum.ToString("00"), msg); + msgNum++; } + } - // check the portal alias again. This time, in more depth now that the portal Id is known - // this check handles browser types/language specific aliases & mobile aliases - string primaryHttpAlias; - if (!redirectAlias && this.IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryHttpAlias)) - { - // it was an incorrect alias - PortalAliasInfo primaryAlias = PortalAliasController.Instance.GetPortalAlias(primaryHttpAlias); - if (primaryAlias != null) - { - result.PrimaryAlias = primaryAlias; - } + if (ex != null) + { + response.AppendHeader("X-" + _productName + "-Ex", ex.Message); + } + } + } - // try and redirect the alias if the settings allow it - redirectAlias = RedirectPortalAlias(primaryHttpAlias, ref result, settings); + private static void Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, bool transfer, bool showDebug) + { + // handle Auto-Add Alias + if (result.Action == ActionType.Output404 && CanAutoAddPortalAlias()) + { + // Need to determine if this is a real 404 or a possible new alias. + var portalId = Host.HostPortalID; + if (portalId > Null.NullInteger) + { + if (string.IsNullOrEmpty(result.DomainName)) + { + result.DomainName = Globals.GetDomainName(context.Request); // parse the domain name out of the request } - if (redirectAlias) + // Get all the existing aliases + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); + + bool autoaddAlias; + bool isPrimary = false; + if (!aliases.Any()) { - // not correct alias for portal : will be redirected - // perform a 301 redirect if one has already been found - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl, false); - finished = true; + autoaddAlias = true; + isPrimary = true; } - - if (!finished) + else { - // Check to see if this to be rewritten into default.aspx?tabId=nn format - // this call is the main rewriting matching call. It makes the decision on whether it is a - // physical file, whether it is toe be rewritten or redirected by way of a stored rule - - // Check if we have a standard url - var uri = new Uri(fullUrl); - if (uri.PathAndQuery.StartsWith("/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - result.DoRewrite = true; - result.Action = ActionType.CheckFor301; - result.RewritePath = Globals.glbDefaultPage + uri.Query; - } - else + autoaddAlias = true; + foreach (var alias in aliases) { - bool isPhysicalResource; - CheckForRewrite(fullUrl, querystring, result, useFriendlyUrls, queryStringCol, settings, out isPhysicalResource, parentTraceId); + if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0 + && result.DomainName.Length >= alias.HTTPAlias.Length) + { + autoaddAlias = false; + break; + } } + } - // return 404 if there is no portal alias for a rewritten request - if (result.DoRewrite && result.PortalAlias == null) + if (autoaddAlias) + { + var portalAliasInfo = new PortalAliasInfo { - // 882 : move this logic in from where it was before to here - // so that non-rewritten requests don't trip over it - // no portal alias found for the request : that's a 404 error - result.Action = ActionType.Output404; - result.Reason = RedirectReason.No_Portal_Alias; + PortalID = portalId, + HTTPAlias = result.DomainName, + IsPrimary = isPrimary, + }; + PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); - Handle404OrException(settings, context, null, result, false, showDebug); - finished = true; // cannot fulfil request unless correct portal alias specified - } + context.Response.Redirect(context.Request.Url.ToString(), true); } + } + } - if (!finished && result.DoRewrite) - { - // check the identified portal alias details for any extra rewrite information required - // this includes the culture and the skin, which can be placed into the rewrite path - // This logic is here because it will catch any Urls which are excluded from rewriting - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (context != null) + { + HttpRequest request = context.Request; + HttpResponse response = context.Response; + HttpServerUtility server = context.Server; - if (result.PortalId > -1 && result.HttpAlias != null) - { - string culture; - string skin; - BrowserTypes browserType; - primaryAliases.GetSettingsByPortalIdAndAlias(result.PortalId, result.HttpAlias, - out culture, - out browserType, - out skin); + const string errorPageHtmlHeader = @"{0}"; + const string errorPageHtmlFooter = @""; + var errorPageHtml = new StringWriter(); + CustomErrorsSection ceSection = null; - // add language code to path if it exists (not null) and if it's not already there - string rewritePath = result.RewritePath; - if (RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, culture)) - { - result.CultureCode = culture; - } + // 876 : security catch for custom error reading + try + { + ceSection = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"); + } - // 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); - result.RewritePath = rewritePath; // reset back from ref temp var - if (debugMessage != null) - { - result.DebugMessages.Add(debugMessage); - } - } + // ReSharper disable EmptyGeneralCatchClause + catch (Exception) + + // ReSharper restore EmptyGeneralCatchClause + { + // on some medium trust environments, this will throw an exception for trying to read the custom Errors + // do nothing + } + + /* 454 new 404/500 error handling routine */ + bool useDNNTab = false; + int errTabId = -1; + string errUrl = null; + string status = string.Empty; + bool isPostback = false; + if (settings != null) + { + if (request.RequestType == "POST") + { + isPostback = true; } - if (!finished && result.DoRewrite) + if (result != null && ex != null) { - // if so, do the rewrite - if (result.RewritePath.StartsWith(result.Scheme) || result.RewritePath.StartsWith(Globals.glbDefaultPage) == false) + result.DebugMessages.Add("Exception: " + ex.Message); + result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); + if (ex.InnerException != null) { - if (result.RewritePath.Contains(Globals.glbDefaultPage) == false) - { - RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); - } - else - { - // if there is no TabId and we have the domain - if (!result.RewritePath.ToLowerInvariant().Contains("tabId=")) - { - RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); - } - else - { - RewriterUtils.RewriteUrl(context, result.RewritePath); - } - } + result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message); + result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace); } else { - RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); + result.DebugMessages.Add("Inner Ex : null"); + } + } + + string errRH; + string errRV; + int statusCode; + if (result != null && result.Action != ActionType.Output404) + { + // output everything but 404 (usually 500) + if (settings.TabId500 > -1) // tabid specified for 500 error page, use that + { + useDNNTab = true; + errTabId = settings.TabId500; } + + errUrl = settings.Url500; + errRH = "X-UrlRewriter-500"; + errRV = "500 Rewritten to {0} : {1}"; + statusCode = 500; + status = "500 Internal Server Error"; } - - // confirm which portal the request is for - if (!finished) + else // output 404 error { - this.IdentifyPortalAlias(context, request, requestUri, result, queryStringCol, settings, parentTraceId); - if (result.Action == ActionType.Redirect302Now) + if (settings.TabId404 > -1) // if the tabid is specified for a 404 page, then use that { - // performs a 302 redirect if requested - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.Redirect(result.FinalUrl, false); - finished = true; + useDNNTab = true; + errTabId = settings.TabId404; } - else + + if (!string.IsNullOrEmpty(settings.Regex404)) + + // with 404 errors, there's an option to catch certain urls and use an external url for extra processing. { - if (result.Action == ActionType.Redirect301 && !string.IsNullOrEmpty(result.FinalUrl)) + try { - finished = true; + // 944 : check the original Url in case the requested Url has been rewritten before discovering it's a 404 error + string requestedUrl = request.Url.ToString(); + if (result != null && !string.IsNullOrEmpty(result.OriginalPath)) + { + requestedUrl = result.OriginalPath; + } - // perform a 301 redirect if one has already been found - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl, false); + if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + { + useDNNTab = false; + + // if we have a match in the 404 regex value, then don't use the tabid + } + } + catch (Exception regexEx) + { + // .some type of exception : output in response header, and go back to using the tabid + response.AppendHeader("X-UrlRewriter-404Exception", regexEx.Message); } } - } - if (!finished) - { - // check to see if this tab has an external url that should be forwared or not - finished = CheckForTabExternalForwardOrRedirect(context, ref result, response, settings, parentTraceId); + errUrl = settings.Url404; + errRH = "X-UrlRewriter-404"; + errRV = "404 Rewritten to {0} : {1} : Reason {2}"; + status = "404 Not Found"; + statusCode = 404; } - // check for a parameter redirect (we had to do all the previous processing to know we are on the right portal and identify the tabid) - // if the CustomParmRewrite flag is set, it means we already rewrote these parameters, so they have to be correct, and aren't subject to - // redirection. The only reason to do a custom parm rewrite is to interpret already-friendly parameters - if (!finished - && !postRequest /* either request is null, or it's not a post - 551 */ - && result.HttpAlias != null /* must have a http alias */ - && !result.CustomParmRewrite && /* not custom rewritten parms */ - ((settings.EnableCustomProviders && - RedirectController.CheckForModuleProviderRedirect(requestUri, ref result, queryStringCol, settings, parentTraceId)) - - // 894 : allow disable of all custom providers - || - RedirectController.CheckForParameterRedirect(requestUri, ref result, queryStringCol, settings))) + // check for 404 logging + if (result == null || result.Action == ActionType.Output404) { - // 301 redirect to new location based on parameter match - if (response != null) - { - switch (result.Action) - { - case ActionType.Redirect301: - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl); - break; - case ActionType.Redirect302: - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.Redirect(result.FinalUrl); - break; - case ActionType.Output404: - response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); - Handle404OrException(settings, context, null, result, true, showDebug); - break; - } - } - - finished = true; + // Log 404 errors to Event Log + UrlRewriterUtils.Log404(request, settings, result); } - // shifted until after the 301 redirect code to allow redirects to be checked for pages which have no rewrite value - // look for a 404 result from the rewrite, because of a deleted page or rule - if (!finished && result.Action == ActionType.Output404) + // 912 : use unhandled 404 switch + string reason404 = null; + bool unhandled404 = true; + if (useDNNTab && errTabId > -1) { - if (result.OriginalPath.Equals(result.HttpAlias, StringComparison.InvariantCultureIgnoreCase) - && result.PortalAlias != null - && result.Reason != RedirectReason.Deleted_Page - && result.Reason != RedirectReason.Disabled_Page) - { - // Request for domain with no page identified (and no home page set in Site Settings) - result.Action = ActionType.Continue; - } - else + unhandled404 = false; // we're handling it here + TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true); + if (errTab != null) { - finished = true; - response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); + bool redirect = false; - if (showDebug) + // ok, valid tabid. what we're going to do is to load up this tab via a rewrite of the url, and then change the output status + string reason = "Not Found"; + if (result != null) { - ShowDebugData(context, requestUri.AbsoluteUri, result, null); + reason = result.Reason.ToString(); } - // show the 404 page if configured - result.Reason = RedirectReason.Requested_404; - Handle404OrException(settings, context, null, result, true, showDebug); - } - } + response.AppendHeader(errRH, string.Format(errRV, "DNN Tab", + errTab.TabName + "(Tabid:" + errTabId.ToString() + ")", + reason)); - if (!finished) - { - // add the portal settings to the app context if the portal alias has been found and is correct - if (result.PortalId != -1 && result.PortalAlias != null) - { - // for invalid tab id other than -1, show the 404 page - TabInfo tabInfo = TabController.Instance.GetTab(result.TabId, result.PortalId, false); - if (tabInfo == null && result.TabId > -1) + // show debug messages even if in debug mode + if (context != null && response != null && result != null && showDebug) { - finished = true; - - if (showDebug) - { - ShowDebugData(context, requestUri.AbsoluteUri, result, null); - } + ShowDebugData(context, result.OriginalPath, result, null); + } - // show the 404 page if configured - result.Action = ActionType.Output404; - result.Reason = RedirectReason.Requested_404; - response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); - Handle404OrException(settings, context, null, result, true, showDebug); + if (!isPostback) + { + response.ClearContent(); + response.StatusCode = statusCode; + response.Status = status; } else { - Globals.SetApplicationName(result.PortalId); - - // load the PortalSettings into current context - var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); + redirect = true; - // set the primary alias if one was specified - if (result.PrimaryAlias != null) - { - portalSettings.PrimaryAlias = result.PrimaryAlias; - } + // redirect postbacks as you can't postback successfully to a server.transfer + } - if (result.CultureCode != null && fullUrl.Contains(result.CultureCode) && - portalSettings.DefaultLanguage == result.CultureCode) - { - // when the request culture code is the same as the portal default, check for a 301 redirect, because we try and remove the language from the url where possible - result.Action = ActionType.CheckFor301; - } + errUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(errTab.TabID, string.Empty); - int portalHomeTabId = portalSettings.HomeTabId; - if (context != null && portalSettings != null && !context.Items.Contains("PortalSettings")) + // have to update the portal settings with the new tabid + PortalSettings ps = null; + if (context != null && context.Items != null) + { + if (context.Items.Contains("PortalSettings")) { - context.Items.Add("PortalSettings", portalSettings); - - // load PortalSettings and HostSettings dictionaries into current context - // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way - context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalSettings.PortalId)); - context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary()); + ps = (PortalSettings)context.Items["PortalSettings"]; + context.Items.Remove("PortalSettings"); // nix it from the context } + } - // check if a secure redirection is needed - // this would be done earlier in the piece, but need to know the portal settings, tabid etc before processing it - bool redirectSecure = this.CheckForSecureRedirect(portalSettings, requestUri, result, queryStringCol, settings); - if (redirectSecure) - { - if (response != null) - { - // 702 : don't check final url until checked for null reference first - if (result.FinalUrl != null) - { - if (result.FinalUrl.StartsWith("https://")) - { - if (showDebug) - { - /* - string debugMsg = "{0}, {1}, {2}, {3}, {4}"; - string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); - response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer)); - */ - ShowDebugData(context, fullUrl, result, null); - } - - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl); - finished = true; - } - else - { - if (settings.SSLClientRedirect) - { - // redirect back to http version, use client redirect - response.Clear(); - - // add a refresh header to the response - response.AddHeader("Refresh", "0;URL=" + result.FinalUrl); - - // add the clientside javascript redirection script - var finalUrl = HttpUtility.HtmlEncode(result.FinalUrl); - response.Write(""); - response.Write(@""); - response.Write(""); - if (showDebug) - { - /* - string debugMsg = "{0}, {1}, {2}, {3}, {4}"; - string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); - response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer)); - */ - ShowDebugData(context, fullUrl, result, null); - } - - // send the response - // 891 : reinstate the response.end to stop the entire page loading - response.End(); - finished = true; - } - else - { - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl); - finished = true; - } - } - } - } + if (ps != null && ps.PortalAlias != null) + { + ps = new PortalSettings(errTabId, ps.PortalAlias); + } + else + { + if (result.HttpAlias != null && result.PortalId > -1) + { + PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias, result.PortalId); + ps = new PortalSettings(errTabId, pa); } else { - // check for, and do a 301 redirect if required - if (CheckForRedirects(requestUri, fullUrl, queryStringCol, result, requestType, settings, portalHomeTabId)) + // 912 : handle 404 when no valid portal can be identified + // results when iis is configured to handle portal alias, but + // DNN isn't. This always returns 404 because a multi-portal site + // can't just show the 404 page of the host site. + ArrayList portals = PortalController.Instance.GetPortals(); + if (portals != null && portals.Count == 1) { - if (response != null) + // single portal install, load up portal settings for this portal + var singlePortal = (PortalInfo)portals[0]; + + // list of aliases from database + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(singlePortal.PortalID).ToList(); + + // list of aliases from Advanced Url settings + List chosen = aliases.GetAliasesForPortalId(singlePortal.PortalID); + PortalAliasInfo useFor404 = null; + + // go through all aliases and either get the first valid one, or the first + // as chosen in the advanced url management settings + foreach (var pa in aliases) { - if (result.Action == ActionType.Redirect301) + if (useFor404 == null) { - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl, false); - finished = true; + useFor404 = pa; // first one by default } - else if (result.Action == ActionType.Redirect302) + + // matching? + if (chosen != null && chosen.Count > 0) { - response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.Redirect(result.FinalUrl, false); - finished = true; + if (chosen.Contains(pa.HTTPAlias)) + { + useFor404 = pa; + } + } + else + { + break; // no further checking } } + + // now configure that as the portal settings + if (useFor404 != null) + { + // create portal settings context for identified portal alias in single portal install + ps = new PortalSettings(errTabId, useFor404); + } } else { - // 612 : Don't clear out a 302 redirect if set - if (result.Action != ActionType.Redirect302 && - result.Action != ActionType.Redirect302Now) - { - result.Reason = RedirectReason.Not_Redirected; - result.FinalUrl = null; - } + reason404 = "Requested domain name is not configured as valid website"; + unhandled404 = true; } } } - } - else - { - // alias does not exist in database - // and all attempts to find another have failed - // this should only happen if the HostPortal does not have any aliases - result.Action = ActionType.Output404; - if (response != null) + + if (ps != null) { - if (showDebug) + // re-add the context items portal settings back in + context.Items.Add("PortalSettings", ps); + } + + if (redirect) + { + errUrl = TestableGlobals.Instance.NavigateURL(); + response.Redirect(errUrl, true); // redirect and end response. + + // It will mean the user will have to postback again, but it will work the second time + } + else + { + if (transfer) { - ShowDebugData(context, fullUrl, result, null); - } + // execute a server transfer to the default.aspx?tabid=xx url + // 767 : object not set error on extensionless 404 errors + if (context.User == null) + { + context.User = GetCurrentPrincipal(context); + } - result.Reason = RedirectReason.Requested_404; + response.TrySkipIisCustomErrors = true; - // 912 : change 404 type to transfer to allow transfer to main portal in single-portal installs - Handle404OrException(settings, context, null, result, true, showDebug); - finished = true; + // 881 : spoof the basePage object so that the client dependency framework + // is satisfied it's working with a page-based handler + IHttpHandler spoofPage = new CDefault(); + context.Handler = spoofPage; + server.Transfer("~/" + errUrl, true); + } + else + { + context.RewritePath("~/Default.aspx", false); + response.TrySkipIisCustomErrors = true; + response.Status = "404 Not Found"; + response.StatusCode = 404; + } } } } - // 404 page ?? - if (settings.TabId404 > 0 && settings.TabId404 == result.TabId) + // 912 : change to new if statement to handle cases where the TabId404 couldn't be handled correctly + if (unhandled404) { - string status = queryStringCol["status"]; - if (status == "404") + // proces the error on the external Url by rewriting to the external url + if (!string.IsNullOrEmpty(errUrl)) { - // respond with a 404 error - result.Action = ActionType.Output404; - result.Reason = RedirectReason.Requested_404_In_Url; - Handle404OrException(settings, context, null, result, true, showDebug); + response.ClearContent(); + response.TrySkipIisCustomErrors = true; + string reason = "Not Found"; + if (result != null) + { + reason = result.Reason.ToString(); + } + + response.AppendHeader(errRH, string.Format(errRV, "Url", errUrl, reason)); + if (reason404 != null) + { + response.AppendHeader("X-Url-Master-404-Data", reason404); + } + + response.StatusCode = statusCode; + response.Status = status; + server.Transfer("~/" + errUrl, true); } - } - else - { - if (result.DoRewrite == false && result.CanRewrite != StateBoolean.False && !finished && - result.Action == ActionType.Continue) + else { - // 739 : catch no-extension 404 errors - string pathWithNoQs = result.OriginalPath; - if (pathWithNoQs.Contains("?")) + errorPageHtml.Write(status + "
The requested Url does not return any valid content."); + if (reason404 != null) { - pathWithNoQs = pathWithNoQs.Substring(0, pathWithNoQs.IndexOf("?", StringComparison.Ordinal)); + errorPageHtml.Write(status + "
" + reason404); } - if (!pathWithNoQs.Substring(pathWithNoQs.Length - 5, 5).Contains(".")) + errorPageHtml.Write("
Administrators
"); + errorPageHtml.Write("
Change this message by configuring a specific 404 Error Page or Url for this website.
"); + + // output a reason for the 404 + string reason = string.Empty; + if (result != null) { - // 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)) - { - // do nothing : it's a request for a valid physical path, maybe including a default document - result.VirtualPath = StateBoolean.False; - } - else - { - if (!Globals.ServicesFrameworkRegex.IsMatch(context.Request.RawUrl)) - { - // no physical path, intercept the request and hand out a 404 error - result.Action = ActionType.Output404; - result.Reason = RedirectReason.Page_404; - result.VirtualPath = StateBoolean.True; + reason = result.Reason.ToString(); + } - // add in a message to explain this 404, becaue it can be cryptic - result.DebugMessages.Add("404 Reason : Not found and no extension"); - Handle404OrException(settings, context, null, result, true, showDebug); - } - } + if (!string.IsNullOrEmpty(errRH) && !string.IsNullOrEmpty(reason)) + { + response.AppendHeader(errRH, reason); } + + response.StatusCode = statusCode; + response.Status = status; + } + } + } + else + { + // fallback output if not valid settings + if (result != null && result.Action == ActionType.Output404) + { + // don't restate the requested Url to prevent cross site scripting + errorPageHtml.Write("404 Not Found
The requested Url does not return any valid content."); + response.StatusCode = 404; + response.Status = "404 Not Found"; + } + else + { + // error, especially if invalid result object + errorPageHtml.Write("500 Server Error
An error occured during processing : if possible, check the event log of the server
"); + response.StatusCode = 500; + response.Status = "500 Internal Server Error"; + if (result != null) + { + result.Action = ActionType.Output500; } } + } - // show debug messages after extensionless-url special 404 handling - if (showDebug) + if (ex != null) + { + if (context != null) { - ShowDebugData(context, fullUrl, result, null); + if (context.Items.Contains("UrlRewrite:Exception") == false) + { + context.Items.Add("UrlRewrite:Exception", ex.Message); + context.Items.Add("UrlRewrite:StackTrace", ex.StackTrace); + } + } + + if (ceSection != null && ceSection.Mode == CustomErrorsMode.Off) + { + errorPageHtml.Write(errorPageHtmlHeader); + 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("~")) + { + errUrl = VirtualPathUtility.ToAbsolute(errUrl); + } + } + finally + { + if (errUrl != null) + { + errorPageHtml.Write("
The error handling would have shown this page : " + errUrl + "
"); + } + else + { + errorPageHtml.Write("
The error handling could not determine the correct page to show.
"); + } + } } } - } - catch (ThreadAbortException) - { - // do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest - // level try/catch block, so we handle it here. - Thread.ResetAbort(); - } - catch (Exception ex) - { - if (showDebug) + + string errorPageHtmlBody = errorPageHtml.ToString(); + if (errorPageHtmlBody.Length > 0) { - Services.Exceptions.Exceptions.LogException(ex); + response.Write(errorPageHtmlHeader); + response.Write(errorPageHtmlBody); + response.Write(errorPageHtmlFooter); } - if (response != null) + if (ex != null) { - if (showDebug) - { - ShowDebugData(context, requestUri.AbsoluteUri, result, ex); - } + UrlRewriterUtils.LogExceptionInRequest(ex, status, result); + } + } + } - if (result != null) - { - result.Ex = ex; - result.Reason = RedirectReason.Exception; - } + private PortalAliasInfo GetPortalAlias(FriendlyUrlSettings settings, string requestUrl, out bool redirectAlias, out bool isPrimaryAlias, out string wrongAlias) + { + PortalAliasInfo aliasInfo = null; + redirectAlias = false; + wrongAlias = null; + isPrimaryAlias = false; + OrderedDictionary portalAliases = TabIndexController.GetPortalAliases(settings); + foreach (string alias in portalAliases.Keys) + { + var urlToMatch = requestUrl; - Handle404OrException(settings, context, ex, result, false, showDebug); + // in fact, requested url should contain alias + // for better performance, need to check whether we want to proceed with a whole url matching or not + // if alias is not a part of url -> let's proceed to the next iteration + var aliasIndex = urlToMatch.IndexOf(alias, StringComparison.InvariantCultureIgnoreCase); + if (aliasIndex < 0) + { + continue; } else { - if (result != null && result.DebugMessages != null) + // we do not accept URL if the first occurence of alias is presented somewhere in the query string + var queryIndex = urlToMatch.IndexOf("?", StringComparison.InvariantCultureIgnoreCase); + if (queryIndex >= 0 && queryIndex < aliasIndex) { - result.DebugMessages.Add("Exception: " + ex.Message); - result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); + // alias is in the query string, go to the next alias + continue; } - throw; + // we are fine here, lets prepare URL to be validated in regex + urlToMatch = urlToMatch.ReplaceIgnoreCase(alias, "_ALIAS_"); } - } - finally - { - // 809 : add in new code copied from urlRewrite class in standard Url Rewrite module - if (context != null && context.Items["FirstRequest"] != null) + + // check whether requested URL has the right URL format containing existing alias + // i.e. url is http://dnndev.me/site1/query?string=test, alias is dnndev.me/site1 + // in the below expression we will validate following value http://_ALIAS_/query?string=test + var aliasMatch = AliasUrlRegex.Match(urlToMatch); + if (aliasMatch.Success) { - context.Items.Remove("FirstRequest"); + // check for mobile browser and matching + var aliasEx = (PortalAliasInfo)portalAliases[alias]; + redirectAlias = aliasEx.Redirect; + if (redirectAlias) + { + wrongAlias = alias; + } - // process any messages in the eventQueue for the Application_Start_FIrstRequest event - EventQueueController.ProcessMessages("Application_Start_FirstRequest"); + isPrimaryAlias = aliasEx.IsPrimary; + aliasInfo = aliasEx; + break; } } + + return aliasInfo; } - private static void ShowDebugData(HttpContext context, string requestUri, UrlAction result, Exception ex) + private void ProcessRequest( + HttpContext context, + Uri requestUri, + bool useFriendlyUrls, + UrlAction result, + FriendlyUrlSettings settings, + bool allowSettingsChange, + Guid parentTraceId) { - if (context != null) + bool finished = false; + bool showDebug = false; + bool postRequest = false; + + HttpRequest request = context.Request; + HttpResponse response = context.Response; + string requestType = request.RequestType; + NameValueCollection queryStringCol = request.QueryString; + + try { - HttpResponse response = context.Response; + string fullUrl, querystring; - // handle null responses wherever they might be found - this routine must be tolerant to all kinds of invalid inputs - if (requestUri == null) - { - requestUri = "null Uri"; - } + // 699: get the full url based on the request and the quersytring, rather than the requestUri.ToString() + // there is a difference in encoding, which can corrupt results when an encoded value is in the querystring + RewriteController.GetUrlWithQuerystring(request, requestUri, out fullUrl, out querystring); - string finalUrl = "null final Url"; - string rewritePath = "null rewrite path"; - string action = "null action"; - if (result != null) + showDebug = CheckForDebug(request, queryStringCol, settings.AllowDebugCode); + string ignoreRegex = settings.IgnoreRegex; + bool ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); + bool redirectAlias = false; + if (!ignoreRequest) { - finalUrl = result.FinalUrl; - action = result.Action.ToString(); - rewritePath = result.RewritePath; - } + // set original path + context.Items["UrlRewrite:OriginalUrl"] = requestUri.AbsoluteUri; - // format up the error message to show - const string debugMsg = "{0}, {1}, {2}, {3}, {4}, {5}, {6}"; - string productVer = DotNetNukeContext.Current.Application.Version.ToString(); - string portalSettings = string.Empty; - string browser = "Unknown"; + // set the path of the result object, and determine if a redirect is allowed on this request + result.SetOriginalPath(requestUri.ToString(), settings); - // 949 : don't rely on 'result' being non-null - if (result != null) - { - browser = result.BrowserType.ToString(); - } + // 737 : set the mobile browser + result.SetBrowserType(request, response, settings); - if (context.Items.Contains("PortalSettings")) - { - var ps = (PortalSettings)context.Items["PortalSettings"]; - if (ps != null) + // add to context + context.Items["UrlRewrite:BrowserType"] = result.BrowserType.ToString(); + + // 839 : split out this check + result.SetRedirectAllowed(result.OriginalPath, settings); + + // find the portal alias first + string wrongAlias; + bool isPrimaryAlias; + var requestedAlias = this.GetPortalAlias(settings, fullUrl, out redirectAlias, out isPrimaryAlias, out wrongAlias); + + if (requestedAlias != null) { - portalSettings = ps.PortalId.ToString(); - if (ps.PortalAlias != null) + // 827 : now get the correct settings for this portal (if not a test request) + // 839 : separate out redirect check as well and move above first redirect test (ConfigurePortalAliasRedirect) + if (allowSettingsChange) { - portalSettings += ":" + ps.PortalAlias.HTTPAlias; + settings = new FriendlyUrlSettings(requestedAlias.PortalID); + result.SetRedirectAllowed(result.OriginalPath, settings); } - } - } - - response.AppendHeader( - "X-" + _productName + "-Debug", - string.Format(debugMsg, requestUri, finalUrl, rewritePath, action, productVer, - portalSettings, browser)); - int msgNum = 1; - if (result != null) - { - foreach (string msg in result.DebugMessages) - { - response.AppendHeader("X-" + _productName + "-Debug-" + msgNum.ToString("00"), msg); - msgNum++; - } - } - if (ex != null) - { - response.AppendHeader("X-" + _productName + "-Ex", ex.Message); - } - } - } + result.PortalAlias = requestedAlias; + result.PrimaryAlias = requestedAlias; // this is the primary alias + result.PortalId = requestedAlias.PortalID; + result.CultureCode = requestedAlias.CultureCode; - private static void Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, bool transfer, bool showDebug) - { - // handle Auto-Add Alias - if (result.Action == ActionType.Output404 && CanAutoAddPortalAlias()) - { - // Need to determine if this is a real 404 or a possible new alias. - var portalId = Host.HostPortalID; - if (portalId > Null.NullInteger) - { - if (string.IsNullOrEmpty(result.DomainName)) - { - result.DomainName = Globals.GetDomainName(context.Request); // parse the domain name out of the request - } + // get the portal alias mapping for this portal + result.PortalAliasMapping = PortalSettingsController.Instance().GetPortalAliasMappingMode(requestedAlias.PortalID); - // Get all the existing aliases - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); + // if requested alias wasn't the primary, we have a replacement, redirects are allowed and the portal alias mapping mode is redirect + // then do a redirect based on the wrong portal + if ((redirectAlias && wrongAlias != null) && result.RedirectAllowed && result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect) + { + // this is the alias, we are going to enforce it as the primary alias + result.PortalAlias = requestedAlias; + result.PrimaryAlias = requestedAlias; - bool autoaddAlias; - bool isPrimary = false; - if (!aliases.Any()) - { - autoaddAlias = true; - isPrimary = true; - } - else - { - autoaddAlias = true; - foreach (var alias in aliases) + // going to redirect this alias because it is incorrect + // or do we just want to mark as 'check for 301??' + redirectAlias = ConfigurePortalAliasRedirect( + ref result, + wrongAlias, + requestedAlias.HTTPAlias, + false, + settings.InternalAliasList, + settings); + } + else { - if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0 - && result.DomainName.Length >= alias.HTTPAlias.Length) + // do not redirect the wrong alias, but set the primary alias value + if (wrongAlias != null) { - autoaddAlias = false; - break; + // get the portal alias info for the requested alias (which is the wrong one) + // and set that as the alias, but also set the found alias as the primary + PortalAliasInfo wrongAliasInfo = PortalAliasController.Instance.GetPortalAlias(wrongAlias); + if (wrongAliasInfo != null) + { + result.PortalAlias = wrongAliasInfo; + result.PrimaryAlias = requestedAlias; + } } } } - - if (autoaddAlias) - { - var portalAliasInfo = new PortalAliasInfo - { - PortalID = portalId, - HTTPAlias = result.DomainName, - IsPrimary = isPrimary, - }; - PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); - - context.Response.Redirect(context.Request.Url.ToString(), true); - } } - } - - if (context != null) - { - HttpRequest request = context.Request; - HttpResponse response = context.Response; - HttpServerUtility server = context.Server; - - const string errorPageHtmlHeader = @"{0}"; - const string errorPageHtmlFooter = @""; - var errorPageHtml = new StringWriter(); - CustomErrorsSection ceSection = null; - // 876 : security catch for custom error reading - try + ignoreRegex = settings.IgnoreRegex; + ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); + if (!ignoreRequest) { - ceSection = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"); - } + // check to see if a post request + if (request.RequestType == "POST") + { + postRequest = true; + } -// ReSharper disable EmptyGeneralCatchClause - catch (Exception) + // check the portal alias again. This time, in more depth now that the portal Id is known + // this check handles browser types/language specific aliases & mobile aliases + string primaryHttpAlias; + if (!redirectAlias && this.IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryHttpAlias)) + { + // it was an incorrect alias + PortalAliasInfo primaryAlias = PortalAliasController.Instance.GetPortalAlias(primaryHttpAlias); + if (primaryAlias != null) + { + result.PrimaryAlias = primaryAlias; + } -// ReSharper restore EmptyGeneralCatchClause - { - // on some medium trust environments, this will throw an exception for trying to read the custom Errors - // do nothing - } + // try and redirect the alias if the settings allow it + redirectAlias = RedirectPortalAlias(primaryHttpAlias, ref result, settings); + } - /* 454 new 404/500 error handling routine */ - bool useDNNTab = false; - int errTabId = -1; - string errUrl = null; - string status = string.Empty; - bool isPostback = false; - if (settings != null) - { - if (request.RequestType == "POST") + if (redirectAlias) { - isPostback = true; + // not correct alias for portal : will be redirected + // perform a 301 redirect if one has already been found + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl, false); + finished = true; } - if (result != null && ex != null) + if (!finished) { - result.DebugMessages.Add("Exception: " + ex.Message); - result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); - if (ex.InnerException != null) + // Check to see if this to be rewritten into default.aspx?tabId=nn format + // this call is the main rewriting matching call. It makes the decision on whether it is a + // physical file, whether it is toe be rewritten or redirected by way of a stored rule + + // Check if we have a standard url + var uri = new Uri(fullUrl); + if (uri.PathAndQuery.StartsWith("/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) { - result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message); - result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace); + result.DoRewrite = true; + result.Action = ActionType.CheckFor301; + result.RewritePath = Globals.glbDefaultPage + uri.Query; } else { - result.DebugMessages.Add("Inner Ex : null"); + bool isPhysicalResource; + CheckForRewrite(fullUrl, querystring, result, useFriendlyUrls, queryStringCol, settings, out isPhysicalResource, parentTraceId); } - } - string errRH; - string errRV; - int statusCode; - if (result != null && result.Action != ActionType.Output404) - { - // output everything but 404 (usually 500) - if (settings.TabId500 > -1) // tabid specified for 500 error page, use that + // return 404 if there is no portal alias for a rewritten request + if (result.DoRewrite && result.PortalAlias == null) { - useDNNTab = true; - errTabId = settings.TabId500; - } + // 882 : move this logic in from where it was before to here + // so that non-rewritten requests don't trip over it + // no portal alias found for the request : that's a 404 error + result.Action = ActionType.Output404; + result.Reason = RedirectReason.No_Portal_Alias; - errUrl = settings.Url500; - errRH = "X-UrlRewriter-500"; - errRV = "500 Rewritten to {0} : {1}"; - statusCode = 500; - status = "500 Internal Server Error"; + Handle404OrException(settings, context, null, result, false, showDebug); + finished = true; // cannot fulfil request unless correct portal alias specified + } } - else // output 404 error + + if (!finished && result.DoRewrite) { - if (settings.TabId404 > -1) // if the tabid is specified for a 404 page, then use that + // check the identified portal alias details for any extra rewrite information required + // this includes the culture and the skin, which can be placed into the rewrite path + // This logic is here because it will catch any Urls which are excluded from rewriting + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + + if (result.PortalId > -1 && result.HttpAlias != null) { - useDNNTab = true; - errTabId = settings.TabId404; - } + string culture; + string skin; + BrowserTypes browserType; + primaryAliases.GetSettingsByPortalIdAndAlias(result.PortalId, result.HttpAlias, + out culture, + out browserType, + out skin); - if (!string.IsNullOrEmpty(settings.Regex404)) + // add language code to path if it exists (not null) and if it's not already there + string rewritePath = result.RewritePath; + if (RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, culture)) + { + result.CultureCode = culture; + } + + // 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); + result.RewritePath = rewritePath; // reset back from ref temp var + if (debugMessage != null) + { + result.DebugMessages.Add(debugMessage); + } + } + } - // with 404 errors, there's an option to catch certain urls and use an external url for extra processing. + if (!finished && result.DoRewrite) + { + // if so, do the rewrite + if (result.RewritePath.StartsWith(result.Scheme) || result.RewritePath.StartsWith(Globals.glbDefaultPage) == false) { - try + if (result.RewritePath.Contains(Globals.glbDefaultPage) == false) { - // 944 : check the original Url in case the requested Url has been rewritten before discovering it's a 404 error - string requestedUrl = request.Url.ToString(); - if (result != null && !string.IsNullOrEmpty(result.OriginalPath)) + RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); + } + else + { + // if there is no TabId and we have the domain + if (!result.RewritePath.ToLowerInvariant().Contains("tabId=")) { - requestedUrl = result.OriginalPath; + RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); } - - if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + else { - useDNNTab = false; - - // if we have a match in the 404 regex value, then don't use the tabid + RewriterUtils.RewriteUrl(context, result.RewritePath); } } - catch (Exception regexEx) + } + else + { + RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); + } + } + + // confirm which portal the request is for + if (!finished) + { + this.IdentifyPortalAlias(context, request, requestUri, result, queryStringCol, settings, parentTraceId); + if (result.Action == ActionType.Redirect302Now) + { + // performs a 302 redirect if requested + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl, false); + finished = true; + } + else + { + if (result.Action == ActionType.Redirect301 && !string.IsNullOrEmpty(result.FinalUrl)) { - // .some type of exception : output in response header, and go back to using the tabid - response.AppendHeader("X-UrlRewriter-404Exception", regexEx.Message); + finished = true; + + // perform a 301 redirect if one has already been found + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl, false); } } + } - errUrl = settings.Url404; - errRH = "X-UrlRewriter-404"; - errRV = "404 Rewritten to {0} : {1} : Reason {2}"; - status = "404 Not Found"; - statusCode = 404; + if (!finished) + { + // check to see if this tab has an external url that should be forwared or not + finished = CheckForTabExternalForwardOrRedirect(context, ref result, response, settings, parentTraceId); } - // check for 404 logging - if (result == null || result.Action == ActionType.Output404) + // check for a parameter redirect (we had to do all the previous processing to know we are on the right portal and identify the tabid) + // if the CustomParmRewrite flag is set, it means we already rewrote these parameters, so they have to be correct, and aren't subject to + // redirection. The only reason to do a custom parm rewrite is to interpret already-friendly parameters + if (!finished + && !postRequest /* either request is null, or it's not a post - 551 */ + && result.HttpAlias != null /* must have a http alias */ + && !result.CustomParmRewrite && /* not custom rewritten parms */ + ((settings.EnableCustomProviders && + RedirectController.CheckForModuleProviderRedirect(requestUri, ref result, queryStringCol, settings, parentTraceId)) + + // 894 : allow disable of all custom providers + || + RedirectController.CheckForParameterRedirect(requestUri, ref result, queryStringCol, settings))) { - // Log 404 errors to Event Log - UrlRewriterUtils.Log404(request, settings, result); + // 301 redirect to new location based on parameter match + if (response != null) + { + switch (result.Action) + { + case ActionType.Redirect301: + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl); + break; + case ActionType.Redirect302: + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl); + break; + case ActionType.Output404: + response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); + Handle404OrException(settings, context, null, result, true, showDebug); + break; + } + } + + finished = true; } - // 912 : use unhandled 404 switch - string reason404 = null; - bool unhandled404 = true; - if (useDNNTab && errTabId > -1) + // shifted until after the 301 redirect code to allow redirects to be checked for pages which have no rewrite value + // look for a 404 result from the rewrite, because of a deleted page or rule + if (!finished && result.Action == ActionType.Output404) { - unhandled404 = false; // we're handling it here - TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true); - if (errTab != null) + if (result.OriginalPath.Equals(result.HttpAlias, StringComparison.InvariantCultureIgnoreCase) + && result.PortalAlias != null + && result.Reason != RedirectReason.Deleted_Page + && result.Reason != RedirectReason.Disabled_Page) { - bool redirect = false; + // Request for domain with no page identified (and no home page set in Site Settings) + result.Action = ActionType.Continue; + } + else + { + finished = true; + response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); - // ok, valid tabid. what we're going to do is to load up this tab via a rewrite of the url, and then change the output status - string reason = "Not Found"; - if (result != null) + if (showDebug) { - reason = result.Reason.ToString(); + ShowDebugData(context, requestUri.AbsoluteUri, result, null); } - response.AppendHeader(errRH, string.Format(errRV, "DNN Tab", - errTab.TabName + "(Tabid:" + errTabId.ToString() + ")", - reason)); + // show the 404 page if configured + result.Reason = RedirectReason.Requested_404; + Handle404OrException(settings, context, null, result, true, showDebug); + } + } - // show debug messages even if in debug mode - if (context != null && response != null && result != null && showDebug) + if (!finished) + { + // add the portal settings to the app context if the portal alias has been found and is correct + if (result.PortalId != -1 && result.PortalAlias != null) + { + // for invalid tab id other than -1, show the 404 page + TabInfo tabInfo = TabController.Instance.GetTab(result.TabId, result.PortalId, false); + if (tabInfo == null && result.TabId > -1) { - ShowDebugData(context, result.OriginalPath, result, null); - } + finished = true; - if (!isPostback) - { - response.ClearContent(); - response.StatusCode = statusCode; - response.Status = status; + if (showDebug) + { + ShowDebugData(context, requestUri.AbsoluteUri, result, null); + } + + // show the 404 page if configured + result.Action = ActionType.Output404; + result.Reason = RedirectReason.Requested_404; + response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); + Handle404OrException(settings, context, null, result, true, showDebug); } else { - redirect = true; - - // redirect postbacks as you can't postback successfully to a server.transfer - } + Globals.SetApplicationName(result.PortalId); - errUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(errTab.TabID, string.Empty); + // load the PortalSettings into current context + var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); - // have to update the portal settings with the new tabid - PortalSettings ps = null; - if (context != null && context.Items != null) - { - if (context.Items.Contains("PortalSettings")) + // set the primary alias if one was specified + if (result.PrimaryAlias != null) { - ps = (PortalSettings)context.Items["PortalSettings"]; - context.Items.Remove("PortalSettings"); // nix it from the context + portalSettings.PrimaryAlias = result.PrimaryAlias; } - } - if (ps != null && ps.PortalAlias != null) - { - ps = new PortalSettings(errTabId, ps.PortalAlias); - } - else - { - if (result.HttpAlias != null && result.PortalId > -1) + if (result.CultureCode != null && fullUrl.Contains(result.CultureCode) && + portalSettings.DefaultLanguage == result.CultureCode) { - PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias, result.PortalId); - ps = new PortalSettings(errTabId, pa); + // when the request culture code is the same as the portal default, check for a 301 redirect, because we try and remove the language from the url where possible + result.Action = ActionType.CheckFor301; } - else - { - // 912 : handle 404 when no valid portal can be identified - // results when iis is configured to handle portal alias, but - // DNN isn't. This always returns 404 because a multi-portal site - // can't just show the 404 page of the host site. - ArrayList portals = PortalController.Instance.GetPortals(); - if (portals != null && portals.Count == 1) - { - // single portal install, load up portal settings for this portal - var singlePortal = (PortalInfo)portals[0]; - // list of aliases from database - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(singlePortal.PortalID).ToList(); + int portalHomeTabId = portalSettings.HomeTabId; + if (context != null && portalSettings != null && !context.Items.Contains("PortalSettings")) + { + context.Items.Add("PortalSettings", portalSettings); - // list of aliases from Advanced Url settings - List chosen = aliases.GetAliasesForPortalId(singlePortal.PortalID); - PortalAliasInfo useFor404 = null; + // load PortalSettings and HostSettings dictionaries into current context + // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way + context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalSettings.PortalId)); + context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary()); + } - // go through all aliases and either get the first valid one, or the first - // as chosen in the advanced url management settings - foreach (var pa in aliases) + // check if a secure redirection is needed + // this would be done earlier in the piece, but need to know the portal settings, tabid etc before processing it + bool redirectSecure = this.CheckForSecureRedirect(portalSettings, requestUri, result, queryStringCol, settings); + if (redirectSecure) + { + if (response != null) + { + // 702 : don't check final url until checked for null reference first + if (result.FinalUrl != null) { - if (useFor404 == null) - { - useFor404 = pa; // first one by default - } - - // matching? - if (chosen != null && chosen.Count > 0) + if (result.FinalUrl.StartsWith("https://")) { - if (chosen.Contains(pa.HTTPAlias)) + if (showDebug) { - useFor404 = pa; + /* + string debugMsg = "{0}, {1}, {2}, {3}, {4}"; + string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); + response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer)); + */ + ShowDebugData(context, fullUrl, result, null); } + + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl); + finished = true; } else { - break; // no further checking - } - } - - // now configure that as the portal settings - if (useFor404 != null) - { - // create portal settings context for identified portal alias in single portal install - ps = new PortalSettings(errTabId, useFor404); - } - } - else - { - reason404 = "Requested domain name is not configured as valid website"; - unhandled404 = true; - } - } - } + if (settings.SSLClientRedirect) + { + // redirect back to http version, use client redirect + response.Clear(); - if (ps != null) - { - // re-add the context items portal settings back in - context.Items.Add("PortalSettings", ps); - } + // add a refresh header to the response + response.AddHeader("Refresh", "0;URL=" + result.FinalUrl); - if (redirect) - { - errUrl = TestableGlobals.Instance.NavigateURL(); - response.Redirect(errUrl, true); // redirect and end response. + // add the clientside javascript redirection script + var finalUrl = HttpUtility.HtmlEncode(result.FinalUrl); + response.Write(""); + response.Write(@""); + response.Write(""); + if (showDebug) + { + /* + string debugMsg = "{0}, {1}, {2}, {3}, {4}"; + string productVer = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).Version.ToString(); + response.AppendHeader("X-" + prodName + "-Debug", string.Format(debugMsg, requestUri.AbsoluteUri, result.FinalUrl, result.RewritePath, result.Action, productVer)); + */ + ShowDebugData(context, fullUrl, result, null); + } - // It will mean the user will have to postback again, but it will work the second time - } - else - { - if (transfer) - { - // execute a server transfer to the default.aspx?tabid=xx url - // 767 : object not set error on extensionless 404 errors - if (context.User == null) - { - context.User = GetCurrentPrincipal(context); + // send the response + // 891 : reinstate the response.end to stop the entire page loading + response.End(); + finished = true; + } + else + { + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl); + finished = true; + } + } + } } - - response.TrySkipIisCustomErrors = true; - - // 881 : spoof the basePage object so that the client dependency framework - // is satisfied it's working with a page-based handler - IHttpHandler spoofPage = new CDefault(); - context.Handler = spoofPage; - server.Transfer("~/" + errUrl, true); } else { - context.RewritePath("~/Default.aspx", false); - response.TrySkipIisCustomErrors = true; - response.Status = "404 Not Found"; - response.StatusCode = 404; + // check for, and do a 301 redirect if required + if (CheckForRedirects(requestUri, fullUrl, queryStringCol, result, requestType, settings, portalHomeTabId)) + { + if (response != null) + { + if (result.Action == ActionType.Redirect301) + { + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.RedirectPermanent(result.FinalUrl, false); + finished = true; + } + else if (result.Action == ActionType.Redirect302) + { + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl, false); + finished = true; + } + } + } + else + { + // 612 : Don't clear out a 302 redirect if set + if (result.Action != ActionType.Redirect302 && + result.Action != ActionType.Redirect302Now) + { + result.Reason = RedirectReason.Not_Redirected; + result.FinalUrl = null; + } + } } } } - } - - // 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 - if (!string.IsNullOrEmpty(errUrl)) + else { - response.ClearContent(); - response.TrySkipIisCustomErrors = true; - string reason = "Not Found"; - if (result != null) + // alias does not exist in database + // and all attempts to find another have failed + // this should only happen if the HostPortal does not have any aliases + result.Action = ActionType.Output404; + if (response != null) { - reason = result.Reason.ToString(); - } + if (showDebug) + { + ShowDebugData(context, fullUrl, result, null); + } - response.AppendHeader(errRH, string.Format(errRV, "Url", errUrl, reason)); - if (reason404 != null) - { - response.AppendHeader("X-Url-Master-404-Data", reason404); + result.Reason = RedirectReason.Requested_404; + + // 912 : change 404 type to transfer to allow transfer to main portal in single-portal installs + Handle404OrException(settings, context, null, result, true, showDebug); + finished = true; } + } + } - response.StatusCode = statusCode; - response.Status = status; - server.Transfer("~/" + errUrl, true); + // 404 page ?? + if (settings.TabId404 > 0 && settings.TabId404 == result.TabId) + { + string status = queryStringCol["status"]; + if (status == "404") + { + // respond with a 404 error + result.Action = ActionType.Output404; + result.Reason = RedirectReason.Requested_404_In_Url; + Handle404OrException(settings, context, null, result, true, showDebug); } - else + } + else + { + if (result.DoRewrite == false && result.CanRewrite != StateBoolean.False && !finished && + result.Action == ActionType.Continue) { - errorPageHtml.Write(status + "
The requested Url does not return any valid content."); - if (reason404 != null) + // 739 : catch no-extension 404 errors + string pathWithNoQs = result.OriginalPath; + if (pathWithNoQs.Contains("?")) { - errorPageHtml.Write(status + "
" + reason404); + pathWithNoQs = pathWithNoQs.Substring(0, pathWithNoQs.IndexOf("?", StringComparison.Ordinal)); } - errorPageHtml.Write("
Administrators
"); - errorPageHtml.Write("
Change this message by configuring a specific 404 Error Page or Url for this website.
"); - - // output a reason for the 404 - string reason = string.Empty; - if (result != null) + if (!pathWithNoQs.Substring(pathWithNoQs.Length - 5, 5).Contains(".")) { - reason = result.Reason.ToString(); - } + // 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)) + { + // do nothing : it's a request for a valid physical path, maybe including a default document + result.VirtualPath = StateBoolean.False; + } + else + { + if (!Globals.ServicesFrameworkRegex.IsMatch(context.Request.RawUrl)) + { + // no physical path, intercept the request and hand out a 404 error + result.Action = ActionType.Output404; + result.Reason = RedirectReason.Page_404; + result.VirtualPath = StateBoolean.True; - if (!string.IsNullOrEmpty(errRH) && !string.IsNullOrEmpty(reason)) - { - response.AppendHeader(errRH, reason); + // add in a message to explain this 404, becaue it can be cryptic + result.DebugMessages.Add("404 Reason : Not found and no extension"); + Handle404OrException(settings, context, null, result, true, showDebug); + } + } } - - response.StatusCode = statusCode; - response.Status = status; } } - } - else - { - // fallback output if not valid settings - if (result != null && result.Action == ActionType.Output404) - { - // don't restate the requested Url to prevent cross site scripting - errorPageHtml.Write("404 Not Found
The requested Url does not return any valid content."); - response.StatusCode = 404; - response.Status = "404 Not Found"; - } - else + + // show debug messages after extensionless-url special 404 handling + if (showDebug) { - // error, especially if invalid result object - errorPageHtml.Write("500 Server Error
An error occured during processing : if possible, check the event log of the server
"); - response.StatusCode = 500; - response.Status = "500 Internal Server Error"; - if (result != null) - { - result.Action = ActionType.Output500; - } + ShowDebugData(context, fullUrl, result, null); } } + } + catch (ThreadAbortException) + { + // do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest + // level try/catch block, so we handle it here. + Thread.ResetAbort(); + } + catch (Exception ex) + { + if (showDebug) + { + Services.Exceptions.Exceptions.LogException(ex); + } - if (ex != null) + if (response != null) { - if (context != null) + if (showDebug) { - if (context.Items.Contains("UrlRewrite:Exception") == false) - { - context.Items.Add("UrlRewrite:Exception", ex.Message); - context.Items.Add("UrlRewrite:StackTrace", ex.StackTrace); - } + ShowDebugData(context, requestUri.AbsoluteUri, result, ex); } - if (ceSection != null && ceSection.Mode == CustomErrorsMode.Off) + if (result != null) { - errorPageHtml.Write(errorPageHtmlHeader); - 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("~")) - { - errUrl = VirtualPathUtility.ToAbsolute(errUrl); - } - } - finally - { - if (errUrl != null) - { - errorPageHtml.Write("
The error handling would have shown this page : " + errUrl + "
"); - } - else - { - errorPageHtml.Write("
The error handling could not determine the correct page to show.
"); - } - } + result.Ex = ex; + result.Reason = RedirectReason.Exception; } - } - string errorPageHtmlBody = errorPageHtml.ToString(); - if (errorPageHtmlBody.Length > 0) - { - response.Write(errorPageHtmlHeader); - response.Write(errorPageHtmlBody); - response.Write(errorPageHtmlFooter); + Handle404OrException(settings, context, ex, result, false, showDebug); } + else + { + if (result != null && result.DebugMessages != null) + { + result.DebugMessages.Add("Exception: " + ex.Message); + result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); + } - if (ex != null) + throw; + } + } + finally + { + // 809 : add in new code copied from urlRewrite class in standard Url Rewrite module + if (context != null && context.Items["FirstRequest"] != null) { - UrlRewriterUtils.LogExceptionInRequest(ex, status, result); + context.Items.Remove("FirstRequest"); + + // process any messages in the eventQueue for the Application_Start_FIrstRequest event + EventQueueController.ProcessMessages("Application_Start_FirstRequest"); } } } @@ -1351,7 +1567,7 @@ private static IPrincipal GetCurrentPrincipal(HttpContext context) } catch (Exception) { - // do nothing here. + // do nothing here. } return currentPrincipal; @@ -1409,173 +1625,160 @@ private static bool CheckForTabExternalForwardOrRedirect( try { - // check for external forwarding or a permanent redirect request - // 592 : check for permanent redirect (823 : moved location from 'checkForRedirects') - if (result.TabId > -1 && result.PortalId > -1 && - (settings.ForwardExternalUrlsType != DNNPageForwardType.NoForward || - result.Reason == RedirectReason.Tab_Permanent_Redirect)) - { - bool allowRedirect = !(result.RewritePath != null && result.RewritePath.ToLowerInvariant().Contains("&ctl=tab")); - - // 594 : do not redirect settings pages for external urls - if (allowRedirect) + // check for external forwarding or a permanent redirect request + // 592 : check for permanent redirect (823 : moved location from 'checkForRedirects') + if (result.TabId > -1 && result.PortalId > -1 && + (settings.ForwardExternalUrlsType != DNNPageForwardType.NoForward || + result.Reason == RedirectReason.Tab_Permanent_Redirect)) { - TabInfo tab; - allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, false, out tab, settings); + bool allowRedirect = !(result.RewritePath != null && result.RewritePath.ToLowerInvariant().Contains("&ctl=tab")); + + // 594 : do not redirect settings pages for external urls if (allowRedirect) { - // 772 : not redirecting file type Urls when requested. - bool permanentRedirect = false; - string redirectUrl = null; - string cleanPath = null; - bool doRedirect = false; - switch (tab.TabType) + TabInfo tab; + allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, false, out tab, settings); + if (allowRedirect) { - case TabType.File: - // have to fudge in a portal settings object for this to work - shortcoming of LinkClick URl generation - var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); - if (context != null) - { - context.Items.Add("PortalSettings", portalSettings); - result.Reason = RedirectReason.File_Url; - string fileUrl = Globals.LinkClick(tab.Url, tab.TabID, -1); - context.Items.Remove("PortalSettings"); - - // take back out again, because it will be done further downstream - // do a check to make sure we're not repeating the Url again, because the tabid is set but we don't want to touch - // a linkclick url - if (!result.OriginalPathNoAlias.EndsWith(HttpUtility.UrlDecode(fileUrl), true, CultureInfo.InvariantCulture)) + // 772 : not redirecting file type Urls when requested. + bool permanentRedirect = false; + string redirectUrl = null; + string cleanPath = null; + bool doRedirect = false; + switch (tab.TabType) + { + case TabType.File: + // have to fudge in a portal settings object for this to work - shortcoming of LinkClick URl generation + var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); + if (context != null) { - redirectUrl = fileUrl; + context.Items.Add("PortalSettings", portalSettings); + result.Reason = RedirectReason.File_Url; + string fileUrl = Globals.LinkClick(tab.Url, tab.TabID, -1); + context.Items.Remove("PortalSettings"); + + // take back out again, because it will be done further downstream + // do a check to make sure we're not repeating the Url again, because the tabid is set but we don't want to touch + // a linkclick url + if (!result.OriginalPathNoAlias.EndsWith(HttpUtility.UrlDecode(fileUrl), true, CultureInfo.InvariantCulture)) + { + redirectUrl = fileUrl; + } } - } - if (redirectUrl != null) - { - doRedirect = true; - } - - break; - case TabType.Url: - result.Reason = RedirectReason.Tab_External_Url; - redirectUrl = tab.Url; - if (redirectUrl != null) - { - doRedirect = true; - if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) + if (redirectUrl != null) { - result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Tab_External_Url; + doRedirect = true; } - else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) + + break; + case TabType.Url: + result.Reason = RedirectReason.Tab_External_Url; + redirectUrl = tab.Url; + if (redirectUrl != null) { - result.Action = ActionType.Redirect302; - result.Reason = RedirectReason.Tab_External_Url; + doRedirect = true; + if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) + { + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Tab_External_Url; + } + else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) + { + result.Action = ActionType.Redirect302; + result.Reason = RedirectReason.Tab_External_Url; + } } - } - - break; - case TabType.Tab: - // if a tabType.tab is specified, it's either an external url or a permanent redirect - // get the redirect path of the specific tab, as long as we have a valid request to work from - if (request != null) - { - // get the rewrite or requested path in a clean format, suitable for input to the friendly url provider - cleanPath = RewriteController.GetRewriteOrRequestedPath(result, request.Url); + break; + case TabType.Tab: + // if a tabType.tab is specified, it's either an external url or a permanent redirect - // 727 prevent redirectLoop with do301 in querystring - if (result.Action == ActionType.Redirect301 || - result.Action == ActionType.Redirect302) + // get the redirect path of the specific tab, as long as we have a valid request to work from + if (request != null) { - cleanPath = RedirectTokens.RemoveAnyRedirectTokens( - cleanPath, - request.QueryString); - } + // get the rewrite or requested path in a clean format, suitable for input to the friendly url provider + cleanPath = RewriteController.GetRewriteOrRequestedPath(result, request.Url); - // get the redirect Url from the friendly url provider using the tab, path and settings - redirectUrl = RedirectController.GetTabRedirectUrl(tab, settings, cleanPath, result, - out permanentRedirect, - parentTraceId); - } + // 727 prevent redirectLoop with do301 in querystring + if (result.Action == ActionType.Redirect301 || + result.Action == ActionType.Redirect302) + { + cleanPath = RedirectTokens.RemoveAnyRedirectTokens( + cleanPath, + request.QueryString); + } - // check to make sure there isn't a blank redirect Url - if (redirectUrl == null) - { - // problem : no redirect Url to redirect to - // solution : cancel the redirect - string message = "Permanent Redirect chosen for Tab " + - tab.TabPath.Replace("//", "/") + - " but forwarding Url was not valid"; - RedirectController.CancelRedirect(ref result, context, settings, message); - } - else - { - // if there was a redirect Url, set the redirect action and set the type of redirect going to use - doRedirect = true; - if (permanentRedirect) - { - result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Tab_Permanent_Redirect; + // get the redirect Url from the friendly url provider using the tab, path and settings + redirectUrl = RedirectController.GetTabRedirectUrl(tab, settings, cleanPath, result, + out permanentRedirect, + parentTraceId); + } - // should be already set, anyway - result.RewritePath = cleanPath; + // check to make sure there isn't a blank redirect Url + if (redirectUrl == null) + { + // problem : no redirect Url to redirect to + // solution : cancel the redirect + string message = "Permanent Redirect chosen for Tab " + + tab.TabPath.Replace("//", "/") + + " but forwarding Url was not valid"; + RedirectController.CancelRedirect(ref result, context, settings, message); } else { - // not a permanent redirect, check if the page forwarding is set - if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) + // if there was a redirect Url, set the redirect action and set the type of redirect going to use + doRedirect = true; + if (permanentRedirect) { result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Tab_External_Url; + result.Reason = RedirectReason.Tab_Permanent_Redirect; + + // should be already set, anyway + result.RewritePath = cleanPath; } - else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) + else { - result.Action = ActionType.Redirect302; - result.Reason = RedirectReason.Tab_External_Url; + // not a permanent redirect, check if the page forwarding is set + if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) + { + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Tab_External_Url; + } + else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) + { + result.Action = ActionType.Redirect302; + result.Reason = RedirectReason.Tab_External_Url; + } } } - } - break; - default: - // only concern here is if permanent redirect is requested, but there is no external url specified - if (result.Reason == RedirectReason.Tab_Permanent_Redirect) - { - bool permRedirect = tab.PermanentRedirect; - if (permRedirect) + break; + default: + // only concern here is if permanent redirect is requested, but there is no external url specified + if (result.Reason == RedirectReason.Tab_Permanent_Redirect) { - // problem : permanent redirect marked, but no forwarding url supplied - // solution : cancel redirect - string message = "Permanent Redirect chosen for Tab " + - tab.TabPath.Replace("//", "/") + - " but no forwarding Url Supplied"; - RedirectController.CancelRedirect(ref result, context, settings, message); + bool permRedirect = tab.PermanentRedirect; + if (permRedirect) + { + // problem : permanent redirect marked, but no forwarding url supplied + // solution : cancel redirect + string message = "Permanent Redirect chosen for Tab " + + tab.TabPath.Replace("//", "/") + + " but no forwarding Url Supplied"; + RedirectController.CancelRedirect(ref result, context, settings, message); + } } - } - break; - } - - // do the redirect we have specified - if (doRedirect && - (result.Action == ActionType.Redirect301 || result.Action == ActionType.Redirect302)) - { - result.FinalUrl = redirectUrl; - if (result.Action == ActionType.Redirect301) - { - if (response != null) - { - // perform a 301 redirect to the external url of the tab - response.AppendHeader( - "X-Redirect-Reason", - result.Reason.ToString().Replace("_", " ") + " Requested"); - response.RedirectPermanent(result.FinalUrl); - } + break; } - else + + // do the redirect we have specified + if (doRedirect && + (result.Action == ActionType.Redirect301 || result.Action == ActionType.Redirect302)) { - if (result.Action == ActionType.Redirect302) + result.FinalUrl = redirectUrl; + if (result.Action == ActionType.Redirect301) { if (response != null) { @@ -1583,17 +1786,30 @@ private static bool CheckForTabExternalForwardOrRedirect( response.AppendHeader( "X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); - response.Redirect(result.FinalUrl); + response.RedirectPermanent(result.FinalUrl); + } + } + else + { + if (result.Action == ActionType.Redirect302) + { + if (response != null) + { + // perform a 301 redirect to the external url of the tab + response.AppendHeader( + "X-Redirect-Reason", + result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl); + } } } - } - finished = true; + finished = true; + } } } } } - } catch (ThreadAbortException) { // do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest @@ -1603,6 +1819,34 @@ private static bool CheckForTabExternalForwardOrRedirect( return finished; } + /// + /// Redirects an alias if that is allowed by the settings. + /// + /// + /// + /// + /// + private static bool RedirectPortalAlias(string httpAlias, ref UrlAction result, FriendlyUrlSettings settings) + { + bool redirected = false; + + // redirect to primary alias + if (result.PortalAliasMapping == PortalSettings.PortalAliasMapping.Redirect && result.RedirectAllowed) + { + if (result.Reason == RedirectReason.Wrong_Portal_Alias_For_Browser_Type || result.Reason == RedirectReason.Wrong_Portal_Alias_For_Culture || + result.Reason == RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser) + { + redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, result.Reason, settings.InternalAliasList, settings); + } + else + { + redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, settings.InternalAliasList, settings); + } + } + + return redirected; + } + private bool CheckForSecureRedirect( PortalSettings portalSettings, Uri requestUri, @@ -1616,7 +1860,7 @@ private bool CheckForSecureRedirect( // 889 : don't run secure redirect code for physical resources or requests that aren't a rewritten Url if (result.IsPhysicalResource == false && result.TabId >= 0) - // no secure redirection for physical resources, only tab-specific requests can be redirected for ssl connections + // no secure redirection for physical resources, only tab-specific requests can be redirected for ssl connections { if (portalSettings.ActiveTab != null) { @@ -1636,241 +1880,94 @@ private bool CheckForSecureRedirect( string sslUrl = portalSettings.SSLURL; if (string.IsNullOrEmpty(result.HttpAlias) == false) { - stdUrl = result.HttpAlias; - } - - url = url.Replace("http://", "https://"); - url = this.ReplaceDomainName(url, stdUrl, sslUrl); - } - } - - // check ssl enforced - if (portalSettings.SSLEnforced) - { - // Prevent browser's mixed-content error in case we open a secure PopUp or a secure iframe - // from an unsecure page - if (!portalSettings.ActiveTab.IsSecure && - result.IsSecureConnection && - !UrlUtils.IsPopUp(url)) - { - // has connection already been forced to secure? - if (queryStringCol["ssl"] == null) - { - // no? well this page shouldn't be secure - string stdUrl = portalSettings.STDURL; - string sslUrl = portalSettings.SSLURL; - url = url.Replace("https://", "http://"); - url = this.ReplaceDomainName(url, sslUrl, stdUrl); - redirectSecure = true; - } - } - } - } - - if (redirectSecure) - { - // now check to see if excluded. Why now? because less requests are made to redirect secure, - // so we don't have to check the exclusion as often. - bool exclude = false; - string doNotRedirectSecureRegex = settings.DoNotRedirectSecureRegex; - if (!string.IsNullOrEmpty(doNotRedirectSecureRegex)) - { - // match the raw url - exclude = Regex.IsMatch(result.RawUrl, doNotRedirectSecureRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - - if (!exclude) - { - result.Action = ActionType.Redirect302Now; - result.Reason = RedirectReason.Secure_Page_Requested; - - // 760 : get the culture specific home page tabid for a redirect comparison - int homePageTabId = portalSettings.HomeTabId; - homePageTabId = TabPathHelper.GetHomePageTabIdForCulture( - portalSettings.DefaultLanguage, - portalSettings.PortalId, - result.CultureCode, homePageTabId); - if (result.TabId == homePageTabId) - { - // replace the /default.aspx in the Url if it was found - url = DefaultPageRegex.Replace(url, "/"); - } - - result.FinalUrl = url; - } - else - { - // 702 : change return value if exclusion has occured - redirectSecure = false; - } - } - } - - return redirectSecure; - } - - private string ReplaceDomainName(string url, string replaceDomain, string withDomain) - { - if (replaceDomain != string.Empty && withDomain != string.Empty) - { - // 951 : change find/replace routine to regex for more accurate replacement - // (previous method gives false positives if the SSL Url is contained within the STD url) - string find = @"(?<=https?://)" + Regex.Escape(withDomain); - if (Regex.IsMatch(url, find, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) == false) - { - string replaceFind = @"(?<=https?://)" + Regex.Escape(replaceDomain); - url = Regex.Replace(url, replaceFind, withDomain, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - } - - return url; - } - - protected bool IsPortalAliasIncorrect( - HttpContext context, - HttpRequest request, - Uri requestUri, - UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - Guid parentTraceId, - out string httpAlias) - { - // now check to make sure it's the primary portal alias for this portal/language/browser - bool incorrectAlias = false; - httpAlias = null; - - // if (result.RedirectAllowed && result.PortalId > -1) - if (result.PortalId > -1) // portal has been identified - { - var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - - if (queryStringCol != null && queryStringCol["forceAlias"] != "true") - { - if (portalAliases.Count > 0) - { - string checkAlias = result.HttpAlias; - bool continueLoop = true; - bool triedWWW = false; - while (httpAlias == null && continueLoop) - { - if (portalAliases.ContainsAlias(result.PortalId, checkAlias)) - { - if (portalAliases.Count > 0) - { - // var cpa = portalAliases.GetAliasByPortalIdAndSettings(result); - string url = requestUri.ToString(); - RewriteController.CheckLanguageMatch(ref url, result); - var cpa = portalAliases - .Where(a => a.IsPrimary || result.PortalAliasMapping != PortalSettings.PortalAliasMapping.Redirect) - .GetAliasByPortalIdAndSettings(result.PortalId, result, result.CultureCode, result.BrowserType); - - if (cpa != null) - { - httpAlias = cpa.HTTPAlias; - continueLoop = false; - } - - if (string.IsNullOrEmpty(result.CultureCode) && cpa == null) - { - // if there is a specific culture for this portal alias, then check that - string culture = portalAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); - - // if this matches the alias of the request, then we know we have the correct alias because it is a specific culture - if (!string.IsNullOrEmpty(culture)) - { - continueLoop = false; - } - } - } - } - - // check whether to still go on or not - if (continueLoop) - { - // this alias doesn't exist in the list - // check if it has a www on it - if not, try adding, if it does, try removing - if (!triedWWW) - { - triedWWW = true; // now tried adding/removing www - if (checkAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) - { - checkAlias = checkAlias.Substring(4); - } - else - { - checkAlias = "www." + checkAlias; - } - } - else - { - // last thing to try, get the default language and see if there is a portal alias for that - // thus, any aliases not identified as belonging to a language are redirected back to the - // alias named for the default language - continueLoop = false; - - // 735 : switch to custom method for getting portal - PortalInfo pi = CacheController.GetPortal(result.PortalId, false); - if (pi != null) - { - string cultureCode = pi.DefaultLanguage; - if (!string.IsNullOrEmpty(cultureCode)) - { - var primaryPortalAlias = portalAliases.GetAliasByPortalIdAndSettings(result.PortalId, result, cultureCode, settings); - if (primaryPortalAlias != null) - { - httpAlias = primaryPortalAlias.HTTPAlias; - } - } - } - } + stdUrl = result.HttpAlias; } + + url = url.Replace("http://", "https://"); + url = this.ReplaceDomainName(url, stdUrl, sslUrl); } } - // check to see if it is a custom tab alais - in that case, it is allowed to be requested for the tab - if (CheckIfAliasIsCustomTabAlias(ref result, httpAlias, settings)) + // check ssl enforced + if (portalSettings.SSLEnforced) { - // change the primary alias to the custom tab alias that has been requested. - result.PrimaryAlias = result.PortalAlias; + // Prevent browser's mixed-content error in case we open a secure PopUp or a secure iframe + // from an unsecure page + if (!portalSettings.ActiveTab.IsSecure && + result.IsSecureConnection && + !UrlUtils.IsPopUp(url)) + { + // has connection already been forced to secure? + if (queryStringCol["ssl"] == null) + { + // no? well this page shouldn't be secure + string stdUrl = portalSettings.STDURL; + string sslUrl = portalSettings.SSLURL; + url = url.Replace("https://", "http://"); + url = this.ReplaceDomainName(url, sslUrl, stdUrl); + redirectSecure = true; + } + } } - else - if (httpAlias != null && string.Compare(httpAlias, result.HttpAlias, StringComparison.OrdinalIgnoreCase) != 0) + } + + if (redirectSecure) + { + // now check to see if excluded. Why now? because less requests are made to redirect secure, + // so we don't have to check the exclusion as often. + bool exclude = false; + string doNotRedirectSecureRegex = settings.DoNotRedirectSecureRegex; + if (!string.IsNullOrEmpty(doNotRedirectSecureRegex)) + { + // match the raw url + exclude = Regex.IsMatch(result.RawUrl, doNotRedirectSecureRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + + if (!exclude) + { + result.Action = ActionType.Redirect302Now; + result.Reason = RedirectReason.Secure_Page_Requested; + + // 760 : get the culture specific home page tabid for a redirect comparison + int homePageTabId = portalSettings.HomeTabId; + homePageTabId = TabPathHelper.GetHomePageTabIdForCulture( + portalSettings.DefaultLanguage, + portalSettings.PortalId, + result.CultureCode, homePageTabId); + if (result.TabId == homePageTabId) { - incorrectAlias = true; + // replace the /default.aspx in the Url if it was found + url = DefaultPageRegex.Replace(url, "/"); } + + result.FinalUrl = url; + } + else + { + // 702 : change return value if exclusion has occured + redirectSecure = false; + } } } - return incorrectAlias; + return redirectSecure; } - /// - /// Redirects an alias if that is allowed by the settings. - /// - /// - /// - /// - /// - private static bool RedirectPortalAlias(string httpAlias, ref UrlAction result, FriendlyUrlSettings settings) + private string ReplaceDomainName(string url, string replaceDomain, string withDomain) { - bool redirected = false; - - // redirect to primary alias - if (result.PortalAliasMapping == PortalSettings.PortalAliasMapping.Redirect && result.RedirectAllowed) + if (replaceDomain != string.Empty && withDomain != string.Empty) { - if (result.Reason == RedirectReason.Wrong_Portal_Alias_For_Browser_Type || result.Reason == RedirectReason.Wrong_Portal_Alias_For_Culture || - result.Reason == RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser) - { - redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, result.Reason, settings.InternalAliasList, settings); - } - else + // 951 : change find/replace routine to regex for more accurate replacement + // (previous method gives false positives if the SSL Url is contained within the STD url) + string find = @"(?<=https?://)" + Regex.Escape(withDomain); + if (Regex.IsMatch(url, find, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) == false) { - redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, settings.InternalAliasList, settings); + string replaceFind = @"(?<=https?://)" + Regex.Escape(replaceDomain); + url = Regex.Replace(url, replaceFind, withDomain, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } } - return redirected; + return url; } private static bool ConfigurePortalAliasRedirect( @@ -2326,101 +2423,26 @@ private void IdentifyPortalAlias( } } - internal static void RewriteAsChildAliasRoot( - HttpContext context, - UrlAction result, - string aliasQueryString, - FriendlyUrlSettings settings) - { - string culture = null; - - // look for specific alias to rewrite language parameter - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - if (result.PortalId > -1 && result.HttpAlias != null) - { - culture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); - } - - if (string.IsNullOrEmpty(culture)) - - // 732 : when no culture returned can be "" as well as null : no culture causes no rewrite, which results in redirect to parent alias - { - // set the default culture code here - // 735 : switch to custom method for getting portal - PortalInfo pi = CacheController.GetPortal(result.PortalId, false); - if (pi != null) - { - culture = pi.DefaultLanguage; - } - } - - if (!string.IsNullOrEmpty(culture)) // a culture was identified for the alias root - { - if (RewriteController.AddLanguageCodeToRewritePath(ref aliasQueryString, culture)) - { - result.CultureCode = culture; - } - - result.DoRewrite = true; - result.RewritePath = "~/" + Globals.glbDefaultPage + aliasQueryString; - - // the expected /default.aspx path (defaultPageUrl) matches the requested Url (/default.aspx) - if (context != null) - { - // only do if not testing - RewriterUtils.RewriteUrl(context, result.RewritePath); - } - } - } - - internal static bool CheckForChildPortalRootUrl(string requestUrl, UrlAction result, out string aliasQueryString) + /// + /// Make sure any redirect to the site root doesn't append the nasty /default.aspx on the end. + /// + /// + /// + /// + internal static string CheckForSiteRootRedirect(string alias, string destUrl) { - bool isChildPortalRootUrl = false; - - // what we are going to test for here is that if this is a child portal request, for the /default.aspx of the child portal - // then we are going to avoid the core 302 redirect to ?alias=portalALias by rewriting to the /default.aspx of the site root - // 684 : don't convert querystring items to lower case - // do the check by constructing what a child alias url would look like and compare it with the requested urls - // 912 : when requested without a valid portal alias, portalALias is null. Refuse and return false. - aliasQueryString = null; - if (result.PortalAlias != null && result.PortalAlias.HTTPAlias != null) + // 540 - don't append /default.aspx onto the end of a site root redirect. + if (destUrl.EndsWith(alias + "/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) { - string defaultPageUrl = result.Scheme + result.PortalAlias.HTTPAlias + "/" + - Globals.glbDefaultPage.ToLowerInvariant(); // child alias Url with /default.aspx - - // 660 : look for a querystring on the site root for a child portal, and handle it if so - if (string.CompareOrdinal(requestUrl.ToLowerInvariant(), defaultPageUrl) == 0) - { - // exact match : that's the alias root - isChildPortalRootUrl = true; - aliasQueryString = string.Empty; - } - - if (!isChildPortalRootUrl && requestUrl.Contains("?")) - { - // is we didn't get an exact match but there is a querystring, then investigate - string[] requestUrlParts = requestUrl.Split('?'); - if (requestUrlParts.GetUpperBound(0) > 0) - { - string rootPart = requestUrlParts[0]; - string queryString = requestUrlParts[1]; - if (string.Compare(rootPart, defaultPageUrl, StringComparison.OrdinalIgnoreCase) == 0) - { - // rewrite, but put in the querystring on the rewrite path - isChildPortalRootUrl = true; - aliasQueryString = "?" + queryString; + // this is just the portal alias root + /defualt.aspx. + // we don't want that, just the portalAliasRoot + "/" + string aliasPlusSlash = alias + "/"; - // 674: check for 301 if this value is a tabid/xx - otherwise the url will just evaluate as is - if (queryString.ToLowerInvariant().StartsWith("tabid=")) - { - result.Action = ActionType.CheckFor301; - } - } - } - } + // get everything up to the end of the portal alias + destUrl = destUrl.Substring(0, destUrl.IndexOf(aliasPlusSlash, StringComparison.Ordinal) + aliasPlusSlash.Length); } - return isChildPortalRootUrl; + return destUrl; } private static string MakeUrlWithAlias(Uri requestUri, string httpAlias) @@ -2607,7 +2629,7 @@ private static void CheckForRewrite( if (!doSiteUrlProcessing) - // if a virtual request, and not starting with the siteUrls.config file, go on to find the rewritten path + // if a virtual request, and not starting with the siteUrls.config file, go on to find the rewritten path { // looks up the page index to find the correct Url bool doRewrite = RewriteController.IdentifyByTabPathEx(fullUrl, querystring, result, queryStringCol, settings, parentTraceId); @@ -2626,23 +2648,6 @@ private static void CheckForRewrite( } } - private void SecurityCheck(HttpApplication app) - { - HttpRequest request = app.Request; - HttpServerUtility server = app.Server; - - // 675 : unnecessarily strict url validation - // URL validation - // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server - // the application should always use the exact relative location of the resource it is requesting - var strURL = request.Url.AbsolutePath; - var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.Url.AbsolutePath)) ?? string.Empty; - if (UrlSlashesRegex.Match(strURL).Success || UrlSlashesRegex.Match(strDoubleDecodeURL).Success) - { - throw new HttpException(404, "Not Found"); - } - } - private static bool CheckForRedirects( Uri requestUri, string fullUrl, @@ -3008,6 +3013,23 @@ private static string StripDebugParameter(string url) return AumDebugRegex.Replace(url, string.Empty); } + private void SecurityCheck(HttpApplication app) + { + HttpRequest request = app.Request; + HttpServerUtility server = app.Server; + + // 675 : unnecessarily strict url validation + // URL validation + // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server + // the application should always use the exact relative location of the resource it is requesting + var strURL = request.Url.AbsolutePath; + var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.Url.AbsolutePath)) ?? string.Empty; + if (UrlSlashesRegex.Match(strURL).Success || UrlSlashesRegex.Match(strDoubleDecodeURL).Success) + { + throw new HttpException(404, "Not Found"); + } + } + private static bool CheckFor301RedirectExclusion(int tabId, int portalId, bool checkBaseUrls, out TabInfo tab, FriendlyUrlSettings settings) { bool doRedirect = false; @@ -3029,27 +3051,5 @@ private static bool CheckFor301RedirectExclusion(int tabId, int portalId, bool c return doRedirect; } - - /// - /// Make sure any redirect to the site root doesn't append the nasty /default.aspx on the end. - /// - /// - /// - /// - internal static string CheckForSiteRootRedirect(string alias, string destUrl) - { - // 540 - don't append /default.aspx onto the end of a site root redirect. - if (destUrl.EndsWith(alias + "/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - // this is just the portal alias root + /defualt.aspx. - // we don't want that, just the portalAliasRoot + "/" - string aliasPlusSlash = alias + "/"; - - // get everything up to the end of the portal alias - destUrl = destUrl.Substring(0, destUrl.IndexOf(aliasPlusSlash, StringComparison.Ordinal) + aliasPlusSlash.Length); - } - - return destUrl; - } } } diff --git a/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs b/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs index 57d9390ec0e..688693413a4 100644 --- a/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs @@ -17,13 +17,13 @@ namespace DotNetNuke.Entities.Urls internal class BasicFriendlyUrlProvider : FriendlyUrlProviderBase { private const string RegexMatchExpression = "[^a-zA-Z0-9 ]"; + private static readonly Regex FriendlyPathRx = new Regex("(.[^\\\\?]*)\\\\?(.*)", RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex DefaultPageRx = new Regex(Globals.glbDefaultPage, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private readonly string _fileExtension; private readonly bool _includePageName; private readonly string _regexMatch; - private static readonly Regex FriendlyPathRx = new Regex("(.[^\\\\?]*)\\\\?(.*)", RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex DefaultPageRx = new Regex(Globals.glbDefaultPage, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - internal BasicFriendlyUrlProvider(NameValueCollection attributes) : base(attributes) { @@ -48,6 +48,18 @@ public string RegexMatch get { return this._regexMatch; } } + internal override string FriendlyUrl(TabInfo tab, string path) + { + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this.FriendlyUrl(tab, path, Globals.glbDefaultPage, _portalSettings); + } + + internal override string FriendlyUrl(TabInfo tab, string path, string pageName) + { + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this.FriendlyUrl(tab, path, pageName, _portalSettings); + } + /// ----------------------------------------------------------------------------- /// /// AddPage adds the page to the friendly url. @@ -292,18 +304,6 @@ private Dictionary GetQueryStringDictionary(string path) return results; } - internal override string FriendlyUrl(TabInfo tab, string path) - { - PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return this.FriendlyUrl(tab, path, Globals.glbDefaultPage, _portalSettings); - } - - internal override string FriendlyUrl(TabInfo tab, string path, string pageName) - { - PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return this.FriendlyUrl(tab, path, pageName, _portalSettings); - } - internal override string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings) { return this.FriendlyUrl(tab, path, pageName, ((PortalSettings)settings)?.PortalAlias.HTTPAlias, settings); diff --git a/DNN Platform/Library/Entities/Urls/CacheController.cs b/DNN Platform/Library/Entities/Urls/CacheController.cs index 02abe455b9e..b961049b907 100644 --- a/DNN Platform/Library/Entities/Urls/CacheController.cs +++ b/DNN Platform/Library/Entities/Urls/CacheController.cs @@ -22,11 +22,13 @@ namespace DotNetNuke.Entities.Urls public class CacheController { + internal const string VanityUrlLookupKey = "url_VanityUrlLookup_{0}"; + + private const string PageIndexKey = "url_PageIndex"; + private const string PageIndexDepthKey = "url_PageIndexDepth"; private static CacheItemRemovedReason cacheItemRemovedReason; private static bool LogRemovedReason; private CacheItemRemovedCallback onRemovePageIndex; - private const string PageIndexKey = "url_PageIndex"; - private const string PageIndexDepthKey = "url_PageIndexDepth"; private const string UrlDictKey = "url_UrlDict"; private const string UrlPortalsKey = "url_UrlPortals"; private const string CustomAliasTabsKey = "url_CustomAliasTabsKey"; @@ -44,79 +46,23 @@ public class CacheController private const string AlwaysCallProviderTabsKey = "url_AlwaysCallProviderTabs_{0}"; private const string HomePageSkinsKey = "url_HomePageSkins_{0}"; private const string TabPathsKey = "url_TabPathsKey_{0}"; - - internal const string VanityUrlLookupKey = "url_VanityUrlLookup_{0}"; - - private static CacheDependency GetPortalsCacheDependency() - { - var keys = new List { "DNN_PortalDictionary" }; - var portalsDepedency = new CacheDependency(null, keys.ToArray()); - return portalsDepedency; - } - - private CacheDependency GetTabsCacheDependency(IEnumerable portalIds) - { - var keys = new List(); - foreach (int portalId in portalIds) - { - const string cacheKey = DataCache.TabCacheKey; - string key = string.Format(cacheKey, portalId); - key = "DNN_" + key; // add on the DNN_ prefix - keys.Add(key); - } - - // get the portals list dependency - var portalKeys = new List(); - if (portalKeys.Count > 0) - { - keys.AddRange(portalKeys); - } - var tabsDependency = new CacheDependency(null, keys.ToArray()); - return tabsDependency; - } - - private static void SetPageCache(string key, object value, FriendlyUrlSettings settings) + public static void FlushFriendlyUrlSettingsFromCache() { - SetPageCache(key, value, null, settings, null); + DataCache.RemoveCache(FriendlyUrlSettingsKey); } - private static void SetPageCache(string key, object value, DNNCacheDependency dependency, FriendlyUrlSettings settings, CacheItemRemovedCallback callback) + public static void FlushPageIndexFromCache() { - DateTime absoluteExpiration = DateTime.Now.Add(settings.CacheTime); - DataCache.SetCache( - key, - value, - dependency, - absoluteExpiration, - Cache.NoSlidingExpiration, - CacheItemPriority.AboveNormal, - callback); + DataCache.RemoveCache(UrlDictKey); + DataCache.RemoveCache(PageIndexKey); + DataCache.RemoveCache(PageIndexDepthKey); + DataCache.RemoveCache(UrlPortalsKey); + DataCache.RemoveCache(UserProfileActionsKey); + DataCache.RemoveCache(PortalAliasListKey); + DataCache.RemoveCache(PortalAliasesKey); + DataCache.RemoveCache(TabPathsKey); } - - private static void SetPortalCache(string key, object value, FriendlyUrlSettings settings) - { - var absoluteExpiration = DateTime.Now.Add(new TimeSpan(24, 0, 0)); - if (settings != null) - { - absoluteExpiration = DateTime.Now.Add(settings.CacheTime); - } - - // 857 : use cache dependency for portal alias cache - if (settings != null) - { - DataCache.SetCache( - key, - value, - new DNNCacheDependency(GetPortalsCacheDependency()), - absoluteExpiration, - Cache.NoSlidingExpiration); - } - else - { - DataCache.SetCache(key, value, absoluteExpiration); - } - } /// /// Finds the best match friendlyurlparms.config file path. @@ -202,6 +148,77 @@ internal static List GetAlwaysCallProviderTabs(int portalId) return result; } + + private static CacheDependency GetPortalsCacheDependency() + { + var keys = new List { "DNN_PortalDictionary" }; + var portalsDepedency = new CacheDependency(null, keys.ToArray()); + return portalsDepedency; + } + + private static void SetPageCache(string key, object value, FriendlyUrlSettings settings) + { + SetPageCache(key, value, null, settings, null); + } + + private static void SetPageCache(string key, object value, DNNCacheDependency dependency, FriendlyUrlSettings settings, CacheItemRemovedCallback callback) + { + DateTime absoluteExpiration = DateTime.Now.Add(settings.CacheTime); + DataCache.SetCache( + key, + value, + dependency, + absoluteExpiration, + Cache.NoSlidingExpiration, + CacheItemPriority.AboveNormal, + callback); + } + + private CacheDependency GetTabsCacheDependency(IEnumerable portalIds) + { + var keys = new List(); + foreach (int portalId in portalIds) + { + const string cacheKey = DataCache.TabCacheKey; + string key = string.Format(cacheKey, portalId); + key = "DNN_" + key; // add on the DNN_ prefix + keys.Add(key); + } + + // get the portals list dependency + var portalKeys = new List(); + if (portalKeys.Count > 0) + { + keys.AddRange(portalKeys); + } + + var tabsDependency = new CacheDependency(null, keys.ToArray()); + return tabsDependency; + } + + private static void SetPortalCache(string key, object value, FriendlyUrlSettings settings) + { + var absoluteExpiration = DateTime.Now.Add(new TimeSpan(24, 0, 0)); + if (settings != null) + { + absoluteExpiration = DateTime.Now.Add(settings.CacheTime); + } + + // 857 : use cache dependency for portal alias cache + if (settings != null) + { + DataCache.SetCache( + key, + value, + new DNNCacheDependency(GetPortalsCacheDependency()), + absoluteExpiration, + Cache.NoSlidingExpiration); + } + else + { + DataCache.SetCache(key, value, absoluteExpiration); + } + } // 770 : customised portal alias per-tab internal static List GetCustomAliasesFromCache() @@ -215,6 +232,26 @@ internal static void ClearCustomAliasesCache() DataCache.ClearCache(CustomPortalAliasesKey); } + internal static Hashtable GetHomePageSkinsFromCache(int portalId) + { + string key = string.Format(HomePageSkinsKey, portalId); + var result = (Hashtable)DataCache.GetCache(key); + return result; + } + + internal static List GetListOfTabsWithProviders(int portalId, FriendlyUrlSettings settings) + { + List result = null; + string key = string.Format(PortalModuleProviderTabsKey, portalId); + var tabIdsForPortal = (int[])DataCache.GetCache(key); + if (tabIdsForPortal != null) + { + result = new List(tabIdsForPortal); + } + + return result; + } + /// /// Retrieve the Url Dictionary for the installation. /// @@ -254,45 +291,6 @@ internal void GetFriendlyUrlIndexFromCache( } } - internal static Hashtable GetHomePageSkinsFromCache(int portalId) - { - string key = string.Format(HomePageSkinsKey, portalId); - var result = (Hashtable)DataCache.GetCache(key); - return result; - } - - internal static List GetListOfTabsWithProviders(int portalId, FriendlyUrlSettings settings) - { - List result = null; - string key = string.Format(PortalModuleProviderTabsKey, portalId); - var tabIdsForPortal = (int[])DataCache.GetCache(key); - if (tabIdsForPortal != null) - { - result = new List(tabIdsForPortal); - } - - return result; - } - - internal void GetPageIndexFromCache( - out SharedDictionary dict, - out SharedDictionary portalDepthInfo, - FriendlyUrlSettings settings) - { - object raw = DataCache.GetCache(PageIndexKey); - if (raw != null) - { - dict = (SharedDictionary)raw; - raw = DataCache.GetCache(PageIndexDepthKey); - portalDepthInfo = (SharedDictionary)raw; - } - else - { - dict = null; - portalDepthInfo = null; - } - } - internal static Dictionary> GetParameterRedirects(FriendlyUrlSettings settings, int portalId, ref List messages) { string redirectActionKey = string.Format(RedirectActionsKey, portalId); // cached one portal at a time @@ -384,6 +382,25 @@ internal static Dictionary> GetParameterReplac return replaceActions; } + internal void GetPageIndexFromCache( + out SharedDictionary dict, + out SharedDictionary portalDepthInfo, + FriendlyUrlSettings settings) + { + object raw = DataCache.GetCache(PageIndexKey); + if (raw != null) + { + dict = (SharedDictionary)raw; + raw = DataCache.GetCache(PageIndexDepthKey); + portalDepthInfo = (SharedDictionary)raw; + } + else + { + dict = null; + portalDepthInfo = null; + } + } + internal static Dictionary> GetParameterRewrites(int portalId, ref List messages, Guid parentTraceId) { string rewriteActionKey = string.Format(RewriteActionsKey, portalId.ToString()); @@ -511,60 +528,6 @@ internal static void StoreCustomAliasesInCache(List aliases, FriendlyUrl DataCache.SetCache(CustomPortalAliasesKey, aliases, absoluteExpiration); } - /// - /// Store the Url Dictionary (all tab urls / tabids) for the installation. - /// - /// - /// - /// - /// - /// - /// - /// - internal void StoreFriendlyUrlIndexInCache( - SharedDictionary> urlDict, - ConcurrentBag urlPortals, - SharedDictionary customAliasTabs, - FriendlyUrlSettings settings, - string reason) - { - if (settings.LogCacheMessages) - { - this.onRemovePageIndex = this.RemovedPageIndexCallBack; - } - else - { - this.onRemovePageIndex = null; - } - - LogRemovedReason = settings.LogCacheMessages; - - SetPageCache(UrlDictKey, urlDict, new DNNCacheDependency(this.GetTabsCacheDependency(urlPortals)), settings, this.onRemovePageIndex); - SetPageCache(UrlPortalsKey, urlPortals, settings); - SetPageCache(CustomAliasTabsKey, customAliasTabs, settings); - - if (settings.LogCacheMessages) - { - var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; - log.AddProperty("Url Rewriting Caching Message", "Friendly Url Index built and Stored in Cache."); - log.AddProperty("Build Reason", reason); - log.AddProperty("Cache Key", UrlDictKey); - using (urlDict.GetReadLock()) - { - log.AddProperty("Item Count", urlDict.Values.Count.ToString()); - } - - log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); - log.AddProperty("Item added to cache", "Url Portals object added to cache. Key:" + UrlPortalsKey + " Items: " + urlPortals.Count.ToString()); - using (customAliasTabs.GetReadLock()) - { - log.AddProperty("Item added to cache", "Custom Alias Tabs added to cache. Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString()); - } - - LogController.Instance.AddLog(log); - } - } - internal static void StoreHomePageSkinsInCache(int portalId, Hashtable homePageSkins) { if (homePageSkins != null && homePageSkins.Count > 0) @@ -633,6 +596,60 @@ internal static void StoreListOfTabsWithProviders(List pro } } + /// + /// Store the Url Dictionary (all tab urls / tabids) for the installation. + /// + /// + /// + /// + /// + /// + /// + /// + internal void StoreFriendlyUrlIndexInCache( + SharedDictionary> urlDict, + ConcurrentBag urlPortals, + SharedDictionary customAliasTabs, + FriendlyUrlSettings settings, + string reason) + { + if (settings.LogCacheMessages) + { + this.onRemovePageIndex = this.RemovedPageIndexCallBack; + } + else + { + this.onRemovePageIndex = null; + } + + LogRemovedReason = settings.LogCacheMessages; + + SetPageCache(UrlDictKey, urlDict, new DNNCacheDependency(this.GetTabsCacheDependency(urlPortals)), settings, this.onRemovePageIndex); + SetPageCache(UrlPortalsKey, urlPortals, settings); + SetPageCache(CustomAliasTabsKey, customAliasTabs, settings); + + if (settings.LogCacheMessages) + { + var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + log.AddProperty("Url Rewriting Caching Message", "Friendly Url Index built and Stored in Cache."); + log.AddProperty("Build Reason", reason); + log.AddProperty("Cache Key", UrlDictKey); + using (urlDict.GetReadLock()) + { + log.AddProperty("Item Count", urlDict.Values.Count.ToString()); + } + + log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); + log.AddProperty("Item added to cache", "Url Portals object added to cache. Key:" + UrlPortalsKey + " Items: " + urlPortals.Count.ToString()); + using (customAliasTabs.GetReadLock()) + { + log.AddProperty("Item added to cache", "Custom Alias Tabs added to cache. Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString()); + } + + LogController.Instance.AddLog(log); + } + } + internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSettings settings, List providers) { // get the key for the portal module providers @@ -723,6 +740,16 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett LogController.Instance.AddLog(log); } } + + internal static void StorePortalAliasesInCache(SharedDictionary aliases, FriendlyUrlSettings settings) + { + SetPortalCache(PortalAliasListKey, aliases, settings); + } + + internal static void StorePortalAliasesInCache(OrderedDictionary aliasList, FriendlyUrlSettings settings) + { + SetPortalCache(PortalAliasesKey, aliasList, settings); + } internal void StorePageIndexInCache( SharedDictionary tabDictionary, @@ -763,16 +790,6 @@ internal void StorePageIndexInCache( } } - internal static void StorePortalAliasesInCache(SharedDictionary aliases, FriendlyUrlSettings settings) - { - SetPortalCache(PortalAliasListKey, aliases, settings); - } - - internal static void StorePortalAliasesInCache(OrderedDictionary aliasList, FriendlyUrlSettings settings) - { - SetPortalCache(PortalAliasesKey, aliasList, settings); - } - internal void StoreTabPathsInCache(int portalId, SharedDictionary tabPathDictionary, FriendlyUrlSettings settings) { SetPageCache( @@ -782,23 +799,6 @@ internal void StoreTabPathsInCache(int portalId, SharedDictionary /// Returns a portal info object for the portal. @@ -862,12 +862,12 @@ public static PortalInfo GetPortal(int portalId, bool exceptionOnNull) portals.Add(pi.PortalID, pi); DataCache.SetCache(PortalsKey, portals); // store back in dictionary } - } + } -// ReSharper disable EmptyGeneralCatchClause - catch + // ReSharper disable EmptyGeneralCatchClause + catch -// ReSharper restore EmptyGeneralCatchClause + // ReSharper restore EmptyGeneralCatchClause { // 912: capture as fall back any exception resulting from doing a portal lookup in 6.x // this happens when portalId = -1 diff --git a/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs b/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs index 2835d288d7c..c0d73733e95 100644 --- a/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs +++ b/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs @@ -58,11 +58,11 @@ public static RewriterConfiguration GetConfig() config = new RewriterConfiguration { Rules = new RewriterRuleCollection() }; foreach (XPathNavigator nav in doc.CreateNavigator().Select("RewriterConfig/Rules/RewriterRule")) { - var rule = new RewriterRule - { - LookFor = nav.SelectSingleNode("LookFor").Value, - SendTo = nav.SelectSingleNode("SendTo").Value, - }; + var rule = new RewriterRule + { + LookFor = nav.SelectSingleNode("LookFor").Value, + SendTo = nav.SelectSingleNode("SendTo").Value, + }; config.Rules.Add(rule); } diff --git a/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs b/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs index 15a8f6d2d28..f303f84c881 100644 --- a/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs +++ b/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs @@ -10,14 +10,14 @@ namespace DotNetNuke.Entities.Urls.Config [Serializable] public class RewriterRule - { - [NonSerialized] - private Regex _matchRx; - - private string _lookFor; - private string _sendTo; - - public string LookFor + { + [NonSerialized] + private Regex _matchRx; + + private string _lookFor; + private string _sendTo; + + public string LookFor { get { @@ -32,9 +32,9 @@ public string LookFor this._matchRx = null; } } - } - - public string SendTo + } + + public string SendTo { get { @@ -45,11 +45,11 @@ public string SendTo { this._sendTo = value; } - } - - // HACK: we cache this in the first call assuming applicationPath never changes during the whole lifetime of the application - // also don't worry about locking; the worst case this will be created more than once - public Regex GetRuleRegex(string applicationPath) + } + + // HACK: we cache this in the first call assuming applicationPath never changes during the whole lifetime of the application + // also don't worry about locking; the worst case this will be created more than once + public Regex GetRuleRegex(string applicationPath) { return this._matchRx ?? (this._matchRx = RegexUtils.GetCachedRegex( diff --git a/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs b/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs index 3899b0e508c..cdbc03c5243 100644 --- a/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs +++ b/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs @@ -15,6 +15,79 @@ namespace DotNetNuke.Entities.Urls internal static class CustomUrlDictController { + /// + /// returns a tabId indexed dictionary of Friendly Urls. + /// + /// + /// + /// + /// + /// + /// + /// + internal static SharedDictionary> FetchCustomUrlDictionary( + int portalId, + bool forceRebuild, + bool bypassCache, + FriendlyUrlSettings settings, + out SharedDictionary customAliasForTabs, + Guid parentTraceId) + { + SharedDictionary> urlDict; + + // this contains a list of all tabs for all the portals that have been retrieved + ConcurrentBag urlPortals; // this contains a list of the portals that have been retrieved + + // get the objects from the cache + var cc = new CacheController(); + cc.GetFriendlyUrlIndexFromCache(out urlDict, out urlPortals, out customAliasForTabs); + + if (urlDict != null && forceRebuild == false && bypassCache == false) + { + if (urlPortals == null) + + // no portals retrieved from cache, but was a dictionary. Bit weird, but we'll run with it + { + urlPortals = new ConcurrentBag(); + } + + // check to see if this portal has been included in the dict + if (urlPortals.Contains(portalId) == false) + { + // ok, there is a url dictionary, but this portal isn't in it, so + // put it in and get the urls for this portal + // this call appends extra portals to the list + urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs); + urlPortals.Add(portalId); + + cc.StoreFriendlyUrlIndexInCache( + urlDict, + urlPortals, + customAliasForTabs, settings, + "Portal Id " + portalId.ToString() + " added to index."); + } + } + else // 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 + if (bypassCache == false) // if we are to cache this item (byPassCache = false) + { + // cache these items + string reason = forceRebuild ? "Force Rebuild of Index" : "Index not in cache"; + cc.StoreFriendlyUrlIndexInCache(urlDict, urlPortals, customAliasForTabs, settings, reason); + } + } + + return urlDict; + } + + internal static void InvalidateDictionary() + { + CacheController.FlushPageIndexFromCache(); + } + /// /// Returns a list of tab and redirects from the database, for the specified portal /// Assumes that the dictionary should have any existing items replaced if the portalid is specified @@ -139,78 +212,5 @@ private static void AddEntryToDictionary(SharedDictionary - /// returns a tabId indexed dictionary of Friendly Urls. - /// - /// - /// - /// - /// - /// - /// - /// - internal static SharedDictionary> FetchCustomUrlDictionary( - int portalId, - bool forceRebuild, - bool bypassCache, - FriendlyUrlSettings settings, - out SharedDictionary customAliasForTabs, - Guid parentTraceId) - { - SharedDictionary> urlDict; - - // this contains a list of all tabs for all the portals that have been retrieved - ConcurrentBag urlPortals; // this contains a list of the portals that have been retrieved - - // get the objects from the cache - var cc = new CacheController(); - cc.GetFriendlyUrlIndexFromCache(out urlDict, out urlPortals, out customAliasForTabs); - - if (urlDict != null && forceRebuild == false && bypassCache == false) - { - if (urlPortals == null) - - // no portals retrieved from cache, but was a dictionary. Bit weird, but we'll run with it - { - urlPortals = new ConcurrentBag(); - } - - // check to see if this portal has been included in the dict - if (urlPortals.Contains(portalId) == false) - { - // ok, there is a url dictionary, but this portal isn't in it, so - // put it in and get the urls for this portal - // this call appends extra portals to the list - urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs); - urlPortals.Add(portalId); - - cc.StoreFriendlyUrlIndexInCache( - urlDict, - urlPortals, - customAliasForTabs, settings, - "Portal Id " + portalId.ToString() + " added to index."); - } - } - else // 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 - if (bypassCache == false) // if we are to cache this item (byPassCache = false) - { - // cache these items - string reason = forceRebuild ? "Force Rebuild of Index" : "Index not in cache"; - cc.StoreFriendlyUrlIndexInCache(urlDict, urlPortals, customAliasForTabs, settings, reason); - } - } - - return urlDict; - } - - internal static void InvalidateDictionary() - { - CacheController.FlushPageIndexFromCache(); - } } } diff --git a/DNN Platform/Library/Entities/Urls/ExtensionUrlProvider.cs b/DNN Platform/Library/Entities/Urls/ExtensionUrlProvider.cs index 8b5a871e52e..2ca2945b421 100644 --- a/DNN Platform/Library/Entities/Urls/ExtensionUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/ExtensionUrlProvider.cs @@ -23,6 +23,39 @@ public abstract class ExtensionUrlProvider { public ExtensionUrlProviderInfo ProviderConfig { get; internal set; } + /// + /// When true, output Urls from the provider for the specified portalId always include the current DotNetNuke page path (ie example.com/pagename/friendlyUrl) + /// When false, output Urls from the provider for the specified portalId may sometimes not include the current DotNetNUke page path (ie example.com/friendlyUrl). + /// + /// + /// Defaults to true. Must be set to false by the provider if any call to the 'ChangeFriendlyUrl' method results in the output + /// parameter 'useDnnPagePath' is false. If 'false' is possible, then 'false' must be returned in this method. + /// + /// + public abstract bool AlwaysUsesDnnPagePath(int portalId); + + /// + /// Generates a new friendly Url based on the parameters supplied. + /// + /// The current Tab the Friendly Url is for. + /// The current friendly Url Path (minus alias) as generated by the Advanced Friendly Url provider. + /// The current friendly Url options that apply to the current portal, as configured within the Extension Url Provider settings. These include space replacement values and other settings which should be incorporated into the Friendly Url generation. + /// The 'pageName' value that comes from the FriendlyUrl API of DNN. Normally this is the 'default.aspx' value (DotNetNuke.Common.Globals.glbDefaultPage). A value of 'default.aspx' is discarded. However, it may be a different value for other modules and if not default.aspx will be appended to the end of the Url. + /// This is a ref parameter, so it can either be left as-is, or changed to default.aspx or "" if no specific value is required. + /// Output parameter, must be set by module Friendly Url Provider. If true, the /pagename/ part of the Url will be removed, and the Url path will be relative from the site root (example.com/custom-module-path instead of example.com/pagename/custom-module-path). + /// A list of information messages used for both debug output and UI information. Add any informational message to this collection if desired. + /// Note using 'useDnnPagePath' = true requires having a specific tab returned from the TransformFriendlyUrlToQueryString below. Usage of the 'useDnnPagePath' implies the TransformFriendlyUrlToQueryString method returns a ?tabid=xx value in the querystring. + /// It also means the provider level property 'AlwaysUsesDnnPagePath' must return 'false'. + /// Friendly Url for specified values. Return friendlyUrlPath if no change is made. + public abstract string ChangeFriendlyUrl( + TabInfo tab, + string friendlyUrlPath, + FriendlyUrlOptions options, + string cultureCode, + ref string endingPageName, + out bool useDnnPagePath, + ref List messages); + protected string CleanNameForUrl(string urlValue, FriendlyUrlOptions options) { bool changed; @@ -78,39 +111,6 @@ protected string EnsureLeadingChar(string leading, string path) return FriendlyUrlController.EnsureLeadingChar(leading, path); } - /// - /// When true, output Urls from the provider for the specified portalId always include the current DotNetNuke page path (ie example.com/pagename/friendlyUrl) - /// When false, output Urls from the provider for the specified portalId may sometimes not include the current DotNetNUke page path (ie example.com/friendlyUrl). - /// - /// - /// Defaults to true. Must be set to false by the provider if any call to the 'ChangeFriendlyUrl' method results in the output - /// parameter 'useDnnPagePath' is false. If 'false' is possible, then 'false' must be returned in this method. - /// - /// - public abstract bool AlwaysUsesDnnPagePath(int portalId); - - /// - /// Generates a new friendly Url based on the parameters supplied. - /// - /// The current Tab the Friendly Url is for. - /// The current friendly Url Path (minus alias) as generated by the Advanced Friendly Url provider. - /// The current friendly Url options that apply to the current portal, as configured within the Extension Url Provider settings. These include space replacement values and other settings which should be incorporated into the Friendly Url generation. - /// The 'pageName' value that comes from the FriendlyUrl API of DNN. Normally this is the 'default.aspx' value (DotNetNuke.Common.Globals.glbDefaultPage). A value of 'default.aspx' is discarded. However, it may be a different value for other modules and if not default.aspx will be appended to the end of the Url. - /// This is a ref parameter, so it can either be left as-is, or changed to default.aspx or "" if no specific value is required. - /// Output parameter, must be set by module Friendly Url Provider. If true, the /pagename/ part of the Url will be removed, and the Url path will be relative from the site root (example.com/custom-module-path instead of example.com/pagename/custom-module-path). - /// A list of information messages used for both debug output and UI information. Add any informational message to this collection if desired. - /// Note using 'useDnnPagePath' = true requires having a specific tab returned from the TransformFriendlyUrlToQueryString below. Usage of the 'useDnnPagePath' implies the TransformFriendlyUrlToQueryString method returns a ?tabid=xx value in the querystring. - /// It also means the provider level property 'AlwaysUsesDnnPagePath' must return 'false'. - /// Friendly Url for specified values. Return friendlyUrlPath if no change is made. - public abstract string ChangeFriendlyUrl( - TabInfo tab, - string friendlyUrlPath, - FriendlyUrlOptions options, - string cultureCode, - ref string endingPageName, - out bool useDnnPagePath, - ref List messages); - /// /// /// diff --git a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs index 488f2ee90e1..cc2cadf9d66 100644 --- a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs +++ b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs @@ -30,79 +30,18 @@ public class ExtensionUrlProviderController @"(?(?:\?|&)tabid=\d+)(?&[^=]+=[^&]*)*", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static void ClearCache() + public static void DeleteProvider(ExtensionUrlProviderInfo urlProvider) { - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - ClearCache(portal.PortalID); - } + DataProvider.Instance().DeleteExtensionUrlProvider(urlProvider.ExtensionUrlProviderId); + ClearCache(); } - private static void ClearCache(int portalId) + public static void DisableProvider(int providerId, int portalId) { - var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); - DataCache.RemoveCache(cacheKey); + DataProvider.Instance().UpdateExtensionUrlProvider(providerId, false); + ClearCache(portalId); } - /// - /// Returns the providers to call. Returns tabid matches first, and any portal id matches after that. - /// - /// - /// - /// - /// - /// - private static List GetProvidersToCall( - int tabId, - int portalId, - FriendlyUrlSettings settings, - Guid parentTraceId) - { - List providers; - - // 887 : introduce lockable code to prevent caching race errors - lock (providersBuildLock) - { - bool definitelyNoProvider; - - // 887 : use cached list of tabs instead of per-tab cache of provider - // get the list of providers to call based on the tab and the portal - var providersToCall = CacheController.GetProvidersForTabAndPortal( - tabId, - portalId, - settings, - out definitelyNoProvider, - parentTraceId); - if (definitelyNoProvider == false && providersToCall == null) - - // nothing in the cache, and we don't have a definitive 'no' that there isn't a provider - { - // get all providers for the portal - var allProviders = GetModuleProviders(portalId).Where(p => p.ProviderConfig.IsActive).ToList(); - - // store the list of tabs for this portal that have a provider attached - CacheController.StoreListOfTabsWithProviders(allProviders, portalId, settings); - - // stash the provider portals in the cache - CacheController.StoreModuleProvidersForPortal(portalId, settings, allProviders); - - // now check if there is a provider for this tab/portal combination - if (allProviders.Count > 0) - { - // find if a module is specific to a tab - providersToCall = new List(); - providersToCall.AddRange(allProviders); - } - } - - // always return an instantiated provider collection - providers = providersToCall ?? new List(); - } - - // return the collection of module providers - return providers; - } - /// /// Checks to see if any providers are marked as 'always call for rewrites'. /// @@ -214,6 +153,79 @@ internal static bool CheckForRedirect( return redirected; } + + private static void ClearCache() + { + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + ClearCache(portal.PortalID); + } + } + + private static void ClearCache(int portalId) + { + var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); + DataCache.RemoveCache(cacheKey); + } + + /// + /// Returns the providers to call. Returns tabid matches first, and any portal id matches after that. + /// + /// + /// + /// + /// + /// + private static List GetProvidersToCall( + int tabId, + int portalId, + FriendlyUrlSettings settings, + Guid parentTraceId) + { + List providers; + + // 887 : introduce lockable code to prevent caching race errors + lock (providersBuildLock) + { + bool definitelyNoProvider; + + // 887 : use cached list of tabs instead of per-tab cache of provider + // get the list of providers to call based on the tab and the portal + var providersToCall = CacheController.GetProvidersForTabAndPortal( + tabId, + portalId, + settings, + out definitelyNoProvider, + parentTraceId); + if (definitelyNoProvider == false && providersToCall == null) + + // nothing in the cache, and we don't have a definitive 'no' that there isn't a provider + { + // get all providers for the portal + var allProviders = GetModuleProviders(portalId).Where(p => p.ProviderConfig.IsActive).ToList(); + + // store the list of tabs for this portal that have a provider attached + CacheController.StoreListOfTabsWithProviders(allProviders, portalId, settings); + + // stash the provider portals in the cache + CacheController.StoreModuleProvidersForPortal(portalId, settings, allProviders); + + // now check if there is a provider for this tab/portal combination + if (allProviders.Count > 0) + { + // find if a module is specific to a tab + providersToCall = new List(); + providersToCall.AddRange(allProviders); + } + } + + // always return an instantiated provider collection + providers = providersToCall ?? new List(); + } + + // return the collection of module providers + return providers; + } /// /// Returns boolean value is any loaded providers require checking of rewrite / redirect values from the site root (ie, not dnn tab path). @@ -463,18 +475,6 @@ internal static bool TransformFriendlyUrlPath( return rewriteDone; } - - public static void DeleteProvider(ExtensionUrlProviderInfo urlProvider) - { - DataProvider.Instance().DeleteExtensionUrlProvider(urlProvider.ExtensionUrlProviderId); - ClearCache(); - } - - public static void DisableProvider(int providerId, int portalId) - { - DataProvider.Instance().UpdateExtensionUrlProvider(providerId, false); - ClearCache(portalId); - } public static void EnableProvider(int providerId, int portalId) { diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs index 2bb8235ec6e..e78a517aa02 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs @@ -29,7 +29,7 @@ public class FriendlyUrlController private const string DisableMobileRedirectQueryStringName = "nomo"; - // google uses the same name nomo=1 means do not redirect to mobile + // google uses the same name nomo=1 means do not redirect to mobile private const string MobileViewSiteCookieName = "dnn_IsMobile"; private const string DisableMobileViewCookieName = "dnn_NoMobile"; @@ -694,117 +694,6 @@ public static TabInfo GetTab(int tabId, bool addStdUrls, PortalSettings portalSe return tab; } - private static bool IsMobileClient() - { - return (HttpContext.Current.Request.Browser != null) && (ClientCapabilityProvider.Instance() != null) && ClientCapabilityProvider.CurrentClientCapability.IsMobile; - } - - private static void CheckIllegalChars(string illegalChars, ref string ch, ref bool replacedUnwantedChars) - { - var resultingCh = new StringBuilder(ch.Length); - foreach (char c in ch) // ch could contain several chars from the pre-defined replacement list - { - if (illegalChars.ToUpperInvariant().Contains(char.ToUpperInvariant(c))) - { - replacedUnwantedChars = true; - } - else - { - resultingCh.Append(c); - } - } - - ch = resultingCh.ToString(); - } - - private static void CheckCharsForReplace(FriendlyUrlOptions options, ref string ch, - ref bool replacedUnwantedChars) - { - if (!options.ReplaceChars.ToUpperInvariant().Contains(ch.ToUpperInvariant())) - { - return; - } - - if (ch != " ") // if not replacing spaces, which are implied - { - replacedUnwantedChars = true; - } - - ch = options.PunctuationReplacement; // in list of replacment chars - - // If we still have a space ensure it's encoded - if (ch == " ") - { - ch = options.SpaceEncoding; - } - } - - internal static bool CanUseMobileDevice(HttpRequest request, HttpResponse response) - { - var canUseMobileDevice = true; - int val; - if (int.TryParse(request.QueryString[DisableMobileRedirectQueryStringName], out val)) - { - // the nomo value is in the querystring - if (val == 1) - { - // no, can't do it - canUseMobileDevice = false; - var cookie = new HttpCookie(DisableMobileViewCookieName) - { - Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", - }; - response.Cookies.Set(cookie); - } - else - { - // check for disable mobile view cookie name - var cookie = request.Cookies[DisableMobileViewCookieName]; - if (cookie != null) - { - // if exists, expire cookie to allow redirect - cookie = new HttpCookie(DisableMobileViewCookieName) - { - Expires = DateTime.Now.AddMinutes(-1), - Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", - }; - response.Cookies.Set(cookie); - } - - // check the DotNetNuke cookies for allowed - if (request.Cookies[DisableMobileRedirectCookieName] != null - && request.Cookies[DisableRedirectPresistCookieName] != null) // check for cookie - { - // cookies exist, can't use mobile device - canUseMobileDevice = false; - } - } - } - else - { - // look for disable mobile view cookie - var cookie = request.Cookies[DisableMobileViewCookieName]; - if (cookie != null) - { - canUseMobileDevice = false; - } - } - - return canUseMobileDevice; - } - - /// - /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0. - /// - /// The path of the tab //admin//someothername. - /// - /// Duplicated in RewriteController.cs. - /// - internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings) - { - return RewriteController.IsAdminTab(portalId, tabPath, settings); - } - public static string CleanNameForUrl(string urlName, FriendlyUrlOptions options, out bool replacedUnwantedChars) { replacedUnwantedChars = false; @@ -939,6 +828,117 @@ public static string EnsureLeadingChar(string leading, string path) return path; } + internal static bool CanUseMobileDevice(HttpRequest request, HttpResponse response) + { + var canUseMobileDevice = true; + int val; + if (int.TryParse(request.QueryString[DisableMobileRedirectQueryStringName], out val)) + { + // the nomo value is in the querystring + if (val == 1) + { + // no, can't do it + canUseMobileDevice = false; + var cookie = new HttpCookie(DisableMobileViewCookieName) + { + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", + }; + response.Cookies.Set(cookie); + } + else + { + // check for disable mobile view cookie name + var cookie = request.Cookies[DisableMobileViewCookieName]; + if (cookie != null) + { + // if exists, expire cookie to allow redirect + cookie = new HttpCookie(DisableMobileViewCookieName) + { + Expires = DateTime.Now.AddMinutes(-1), + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", + }; + response.Cookies.Set(cookie); + } + + // check the DotNetNuke cookies for allowed + if (request.Cookies[DisableMobileRedirectCookieName] != null + && request.Cookies[DisableRedirectPresistCookieName] != null) // check for cookie + { + // cookies exist, can't use mobile device + canUseMobileDevice = false; + } + } + } + else + { + // look for disable mobile view cookie + var cookie = request.Cookies[DisableMobileViewCookieName]; + if (cookie != null) + { + canUseMobileDevice = false; + } + } + + return canUseMobileDevice; + } + + /// + /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0. + /// + /// The path of the tab //admin//someothername. + /// + /// Duplicated in RewriteController.cs. + /// + internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings) + { + return RewriteController.IsAdminTab(portalId, tabPath, settings); + } + + private static bool IsMobileClient() + { + return (HttpContext.Current.Request.Browser != null) && (ClientCapabilityProvider.Instance() != null) && ClientCapabilityProvider.CurrentClientCapability.IsMobile; + } + + private static void CheckIllegalChars(string illegalChars, ref string ch, ref bool replacedUnwantedChars) + { + var resultingCh = new StringBuilder(ch.Length); + foreach (char c in ch) // ch could contain several chars from the pre-defined replacement list + { + if (illegalChars.ToUpperInvariant().Contains(char.ToUpperInvariant(c))) + { + replacedUnwantedChars = true; + } + else + { + resultingCh.Append(c); + } + } + + ch = resultingCh.ToString(); + } + + private static void CheckCharsForReplace(FriendlyUrlOptions options, ref string ch, + ref bool replacedUnwantedChars) + { + if (!options.ReplaceChars.ToUpperInvariant().Contains(ch.ToUpperInvariant())) + { + return; + } + + if (ch != " ") // if not replacing spaces, which are implied + { + replacedUnwantedChars = true; + } + + ch = options.PunctuationReplacement; // in list of replacment chars + + // If we still have a space ensure it's encoded + if (ch == " ") + { + ch = options.SpaceEncoding; + } + } + public static string EnsureNotLeadingChar(string leading, string path) { if (leading != null && path != null @@ -985,7 +985,7 @@ public static BrowserTypes GetBrowserType(HttpRequest request, HttpResponse resp if (viewMobileCookie == null) { response.Cookies.Add(new HttpCookie(MobileViewSiteCookieName, isMobile.ToString()) - { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); + { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); } else { diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs index 959a1c7f98d..a8642a0335a 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs @@ -15,11 +15,11 @@ namespace DotNetNuke.Entities.Urls [Serializable] public class FriendlyUrlOptions { - private static readonly object _regexLookupLock = new object(); - private static readonly Dictionary _regexLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); - public bool ConvertDiacriticChars; public string IllegalChars; + + private static readonly object _regexLookupLock = new object(); + private static readonly Dictionary _regexLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); public int MaxUrlPathLength; public string PageExtension; public string PunctuationReplacement; @@ -60,6 +60,23 @@ public Regex RegexMatchRegex get { return GetRegex(this.RegexMatch); } } + public FriendlyUrlOptions Clone() + { + var cloned = new FriendlyUrlOptions + { + PunctuationReplacement = this.PunctuationReplacement, + SpaceEncoding = this.SpaceEncoding, + MaxUrlPathLength = this.MaxUrlPathLength, + ConvertDiacriticChars = this.ConvertDiacriticChars, + PageExtension = this.PageExtension, + RegexMatch = this.RegexMatch, + ReplaceCharWithChar = this.ReplaceCharWithChar, + IllegalChars = this.IllegalChars, + ReplaceChars = this.ReplaceChars, + }; + return cloned; + } + private static Regex GetRegex(string regexText) { Regex compiledRegex; @@ -78,22 +95,5 @@ private static Regex GetRegex(string regexText) return _regexLookup[regexText] = RegexUtils.GetCachedRegex(regexText, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } } - - public FriendlyUrlOptions Clone() - { - var cloned = new FriendlyUrlOptions - { - PunctuationReplacement = this.PunctuationReplacement, - SpaceEncoding = this.SpaceEncoding, - MaxUrlPathLength = this.MaxUrlPathLength, - ConvertDiacriticChars = this.ConvertDiacriticChars, - PageExtension = this.PageExtension, - RegexMatch = this.RegexMatch, - ReplaceCharWithChar = this.ReplaceCharWithChar, - IllegalChars = this.IllegalChars, - ReplaceChars = this.ReplaceChars, - }; - return cloned; - } } } diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs index 55e00106b6a..4f575f0b74a 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs @@ -14,111 +14,6 @@ namespace DotNetNuke.Entities.Urls internal class FriendlyUrlPathController { - /// - /// Splits out the userid value from the supplied Friendly Url Path. - /// - /// - /// The 'other' parameters which form the total UserProfile Url (if supplied). - /// - /// The remaining path not associated with the user id. - /// - private static void SplitUserIdFromFriendlyUrlPath( - string urlPath, - string parmName, - string otherParametersPath, - out string rawUserId, - out string remainingPath) - { - // 688 : allow for other parts to be in the url by capturing more with the regex filters - string regexPattern; - rawUserId = null; - remainingPath = string.Empty; - - // generally the path will start with a / and not end with one, but it's possible to get all sorts of things - 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("/")) - { - otherParametersPath = otherParametersPath.Substring(0, otherParametersPath.Length - 1); - } - - const string patternFormatWithParameters = @"/?(?.*)(?=_parm_)(?(?<=/|^)(?:_parm_)/(?[\d\w]+)){0,1}/?(?_otherparm_){0,1}/?(?(?<=/)(?:_parm_)/(?[\d\w]+)){0,1}(?.*)"; - regexPattern = patternFormatWithParameters.Replace("_parm_", parmName); - regexPattern = regexPattern.Replace("_otherparm_", otherParametersPath); - } - else - { - const string patternNoParameters = @"/?(?.*)(?(?<=/|^)(?:_parm_)/(?[\d\w]+)/?)+(?.*)"; - regexPattern = patternNoParameters.Replace("_parm_", parmName); - } - - // check the regex match - Match parmMatch = Regex.Match(urlPath, regexPattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - if (parmMatch.Success) - { - // must be nothing in the op1 and op2 values - Group otherParmsGp = parmMatch.Groups["op"]; - Group parm1ValueGp = parmMatch.Groups["p1v"]; - Group parm2ValueGp = parmMatch.Groups["p2v"]; - Group rem1ParmsGp = parmMatch.Groups["rem1"]; // remainder at the start of the match - Group rem2ParmsGp = parmMatch.Groups["rem2"]; // remainder at the end of the match - - if (otherParmsGp != null && otherParmsGp.Success && (parm1ValueGp.Success || parm2ValueGp.Success)) - { - // matched the other parm value and either the p1 or p2 value - rawUserId = parm1ValueGp.Success ? parm1ValueGp.Value : parm2ValueGp.Value; - } - else - { - if ((otherParmsGp == null || otherParmsGp.Success == false) && parm1ValueGp != null && - parm1ValueGp.Success) - { - rawUserId = parm1ValueGp.Value; - } - } - - // add back the remainders - if (rem1ParmsGp != null && rem1ParmsGp.Success) - { - remainingPath = rem1ParmsGp.Value; - } - - if (rem2ParmsGp != null && rem2ParmsGp.Success) - { - remainingPath += rem2ParmsGp.Value; - } - - if (remainingPath.EndsWith("/")) - { - remainingPath = remainingPath.Substring(0, remainingPath.Length - 1); - } - - // 722: drop out the parts of the remaining path that are in the 'otherParameters' path. - // the other parameters path will be automatically provided upon rewrite - if (otherParametersPath != null) - { - remainingPath = Regex.Replace(remainingPath, Regex.Escape(otherParametersPath), string.Empty, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - - if (parmName.Contains("|") && rawUserId != null) - { - // eliminate any dups from the remaining path - string[] vals = parmName.Split('|'); - foreach (string val in vals) - { - string find = "/?" + Regex.Escape(val + "/" + rawUserId); - remainingPath = Regex.Replace(remainingPath, find, string.Empty, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - } - - if (remainingPath.Length > 0 && remainingPath.StartsWith("/") == false) - { - remainingPath = "/" + remainingPath; - } - } - } - /// /// This method checks the list of rules for parameter replacement and modifies the parameter path accordingly. /// @@ -335,5 +230,110 @@ internal static bool CheckUserProfileReplacement( return urlWasChanged; } + + /// + /// Splits out the userid value from the supplied Friendly Url Path. + /// + /// + /// The 'other' parameters which form the total UserProfile Url (if supplied). + /// + /// The remaining path not associated with the user id. + /// + private static void SplitUserIdFromFriendlyUrlPath( + string urlPath, + string parmName, + string otherParametersPath, + out string rawUserId, + out string remainingPath) + { + // 688 : allow for other parts to be in the url by capturing more with the regex filters + string regexPattern; + rawUserId = null; + remainingPath = string.Empty; + + // generally the path will start with a / and not end with one, but it's possible to get all sorts of things + 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("/")) + { + otherParametersPath = otherParametersPath.Substring(0, otherParametersPath.Length - 1); + } + + const string patternFormatWithParameters = @"/?(?.*)(?=_parm_)(?(?<=/|^)(?:_parm_)/(?[\d\w]+)){0,1}/?(?_otherparm_){0,1}/?(?(?<=/)(?:_parm_)/(?[\d\w]+)){0,1}(?.*)"; + regexPattern = patternFormatWithParameters.Replace("_parm_", parmName); + regexPattern = regexPattern.Replace("_otherparm_", otherParametersPath); + } + else + { + const string patternNoParameters = @"/?(?.*)(?(?<=/|^)(?:_parm_)/(?[\d\w]+)/?)+(?.*)"; + regexPattern = patternNoParameters.Replace("_parm_", parmName); + } + + // check the regex match + Match parmMatch = Regex.Match(urlPath, regexPattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + if (parmMatch.Success) + { + // must be nothing in the op1 and op2 values + Group otherParmsGp = parmMatch.Groups["op"]; + Group parm1ValueGp = parmMatch.Groups["p1v"]; + Group parm2ValueGp = parmMatch.Groups["p2v"]; + Group rem1ParmsGp = parmMatch.Groups["rem1"]; // remainder at the start of the match + Group rem2ParmsGp = parmMatch.Groups["rem2"]; // remainder at the end of the match + + if (otherParmsGp != null && otherParmsGp.Success && (parm1ValueGp.Success || parm2ValueGp.Success)) + { + // matched the other parm value and either the p1 or p2 value + rawUserId = parm1ValueGp.Success ? parm1ValueGp.Value : parm2ValueGp.Value; + } + else + { + if ((otherParmsGp == null || otherParmsGp.Success == false) && parm1ValueGp != null && + parm1ValueGp.Success) + { + rawUserId = parm1ValueGp.Value; + } + } + + // add back the remainders + if (rem1ParmsGp != null && rem1ParmsGp.Success) + { + remainingPath = rem1ParmsGp.Value; + } + + if (rem2ParmsGp != null && rem2ParmsGp.Success) + { + remainingPath += rem2ParmsGp.Value; + } + + if (remainingPath.EndsWith("/")) + { + remainingPath = remainingPath.Substring(0, remainingPath.Length - 1); + } + + // 722: drop out the parts of the remaining path that are in the 'otherParameters' path. + // the other parameters path will be automatically provided upon rewrite + if (otherParametersPath != null) + { + remainingPath = Regex.Replace(remainingPath, Regex.Escape(otherParametersPath), string.Empty, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + + if (parmName.Contains("|") && rawUserId != null) + { + // eliminate any dups from the remaining path + string[] vals = parmName.Split('|'); + foreach (string val in vals) + { + string find = "/?" + Regex.Escape(val + "/" + rawUserId); + remainingPath = Regex.Replace(remainingPath, find, string.Empty, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + } + + if (remainingPath.Length > 0 && remainingPath.StartsWith("/") == false) + { + remainingPath = "/" + remainingPath; + } + } + } } } diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs index 34b34687847..b28facf2d3e 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs @@ -12,8 +12,6 @@ namespace DotNetNuke.Entities.Urls public abstract class FriendlyUrlProviderBase { - protected UrlFormatType UrlFormat { get; private set; } - internal FriendlyUrlProviderBase(NameValueCollection attributes) { if (!string.IsNullOrEmpty(attributes["urlFormat"])) @@ -36,6 +34,8 @@ internal FriendlyUrlProviderBase(NameValueCollection attributes) } } } + + protected UrlFormatType UrlFormat { get; private set; } internal abstract string FriendlyUrl(TabInfo tab, string path); diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs index d7ad7fa9555..1e16d3da195 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs @@ -12,6 +12,10 @@ namespace DotNetNuke.Entities.Urls [Serializable] public class FriendlyUrlSettings { + public const string ReplaceSpaceWithNothing = "None"; + public const string SpaceEncodingPlus = "+"; + public const string SpaceEncodingHex = "%20"; + private readonly IHostController _hostControllerInstance = HostController.Instance; // 894 : new switch to disable custom url provider @@ -59,10 +63,6 @@ public class FriendlyUrlSettings private Dictionary _replaceCharacterDictionary; internal List PortalValues { get; private set; } - - public const string ReplaceSpaceWithNothing = "None"; - public const string SpaceEncodingPlus = "+"; - public const string SpaceEncodingHex = "%20"; // Settings Keys public const string DeletedTabHandlingTypeSetting = "AUM_DeletedTabHandlingType"; @@ -108,6 +108,28 @@ public class FriendlyUrlSettings public const string CacheTimeSetting = "AUM_CacheTime"; public const string IncludePageNameSetting = "AUM_IncludePageName"; + public FriendlyUrlSettings(int portalId) + { + this.PortalId = portalId < -1 ? -1 : portalId; + this.IsDirty = false; + this.IsLoading = false; + + this.PortalValues = new List(); + + this.TabId500 = this.TabId404 = -1; + + if (portalId > -1) + { + var portal = PortalController.Instance.GetPortal(portalId); + this.TabId500 = this.TabId404 = portal.Custom404TabId; + + if (this.TabId500 == -1) + { + this.TabId500 = this.TabId404; + } + } + } + public List InternalAliasList { get; private set; } public List ProcessRequestList @@ -722,28 +744,6 @@ private string GetStringSetting(string key, string defaultValue) return returnValue; } - - public FriendlyUrlSettings(int portalId) - { - this.PortalId = portalId < -1 ? -1 : portalId; - this.IsDirty = false; - this.IsLoading = false; - - this.PortalValues = new List(); - - this.TabId500 = this.TabId404 = -1; - - if (portalId > -1) - { - var portal = PortalController.Instance.GetPortal(portalId); - this.TabId500 = this.TabId404 = portal.Custom404TabId; - - if (this.TabId500 == -1) - { - this.TabId500 = this.TabId404; - } - } - } private void ParseInternalAliases() { diff --git a/DNN Platform/Library/Entities/Urls/RedirectTokens.cs b/DNN Platform/Library/Entities/Urls/RedirectTokens.cs index de11f7c34d0..7927efcf1ba 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectTokens.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectTokens.cs @@ -26,121 +26,6 @@ internal static class RedirectTokens @"(?<=(?

&|\?))(?do301|do302|do404)=(?[^&]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - ///

- /// Returns the list of tokens found in a rewrite path as a key/value dictionary. - /// - /// - /// Rewritten Url path. - /// - /// - /// - /// Returns a list of the redirect tokens found in the querystring. - /// - /// - private static List GetRedirectReasonTokensFromRewritePath(string rewritePath) - { - var reasons = new List(); - MatchCollection matches = RewritePathRx.Matches(rewritePath); - foreach (Match match in matches) - { - if (match.Success) - { - Group rrG = match.Groups["rr"]; - if (rrG.Success) - { - string rr = match.Groups["rr"].Value; - reasons.Add(rr); - } - } - } - - return reasons; - } - - private static void GetRedirectActionTokenAndValue(ActionType action, out string token, out string value) - { - switch (action) - { - case ActionType.CheckFor301: - token = "do301"; - value = "check"; - break; - case ActionType.Redirect301: - token = "do301"; - value = "true"; - break; - case ActionType.Output404: - token = "do404"; - value = "true"; - break; - case ActionType.Redirect302: - token = "do302"; - value = "true"; - break; - default: - token = string.Empty; - value = string.Empty; - break; - } - } - - private static string GetRedirectReasonRewriteToken(RedirectReason reason) - { - string result = string.Empty; - switch (reason) - { - case RedirectReason.Deleted_Page: - result = "&rr=dl"; - break; - case RedirectReason.Disabled_Page: - // 838 : handle disabled page separately - result = "&rr=db"; - break; - case RedirectReason.Tab_Permanent_Redirect: - result = "&rr=pr"; - break; - case RedirectReason.Spaces_Replaced: - result = "&rr=sr"; - break; - case RedirectReason.Site_Root_Home: - result = "&rr=hp"; - break; - case RedirectReason.Diacritic_Characters: - result = "&rr=dc"; - break; - case RedirectReason.User_Profile_Url: - result = "&rr=up"; - break; - case RedirectReason.Custom_Redirect: - result = "&rr=cr"; - break; - } - - return result; - } - - private static Dictionary GetRedirectTokensAndValuesFromRewritePath(string rewritePath, out bool hasDupes) - { - hasDupes = false; - var results = new Dictionary(); - MatchCollection matches = RedirectTokensRx.Matches(rewritePath); - foreach (Match tokenMatch in matches) - { - string tk = tokenMatch.Groups["tk"].Value; - string val = tokenMatch.Groups["val"].Value; - if (results.ContainsKey(tk)) - { - hasDupes = true; - } - else - { - results.Add(tk, val); - } - } - - return results; - } - /// /// Adds on a redirect reason to the rewrite path. /// @@ -358,6 +243,121 @@ internal static void DetermineRedirectReasonAndAction( newUrl = RemoveAnyRedirectReasons(newUrl); } } + + /// + /// Returns the list of tokens found in a rewrite path as a key/value dictionary. + /// + /// + /// Rewritten Url path. + /// + /// + /// + /// Returns a list of the redirect tokens found in the querystring. + /// + /// + private static List GetRedirectReasonTokensFromRewritePath(string rewritePath) + { + var reasons = new List(); + MatchCollection matches = RewritePathRx.Matches(rewritePath); + foreach (Match match in matches) + { + if (match.Success) + { + Group rrG = match.Groups["rr"]; + if (rrG.Success) + { + string rr = match.Groups["rr"].Value; + reasons.Add(rr); + } + } + } + + return reasons; + } + + private static void GetRedirectActionTokenAndValue(ActionType action, out string token, out string value) + { + switch (action) + { + case ActionType.CheckFor301: + token = "do301"; + value = "check"; + break; + case ActionType.Redirect301: + token = "do301"; + value = "true"; + break; + case ActionType.Output404: + token = "do404"; + value = "true"; + break; + case ActionType.Redirect302: + token = "do302"; + value = "true"; + break; + default: + token = string.Empty; + value = string.Empty; + break; + } + } + + private static string GetRedirectReasonRewriteToken(RedirectReason reason) + { + string result = string.Empty; + switch (reason) + { + case RedirectReason.Deleted_Page: + result = "&rr=dl"; + break; + case RedirectReason.Disabled_Page: + // 838 : handle disabled page separately + result = "&rr=db"; + break; + case RedirectReason.Tab_Permanent_Redirect: + result = "&rr=pr"; + break; + case RedirectReason.Spaces_Replaced: + result = "&rr=sr"; + break; + case RedirectReason.Site_Root_Home: + result = "&rr=hp"; + break; + case RedirectReason.Diacritic_Characters: + result = "&rr=dc"; + break; + case RedirectReason.User_Profile_Url: + result = "&rr=up"; + break; + case RedirectReason.Custom_Redirect: + result = "&rr=cr"; + break; + } + + return result; + } + + private static Dictionary GetRedirectTokensAndValuesFromRewritePath(string rewritePath, out bool hasDupes) + { + hasDupes = false; + var results = new Dictionary(); + MatchCollection matches = RedirectTokensRx.Matches(rewritePath); + foreach (Match tokenMatch in matches) + { + string tk = tokenMatch.Groups["tk"].Value; + string val = tokenMatch.Groups["val"].Value; + if (results.ContainsKey(tk)) + { + hasDupes = true; + } + else + { + results.Add(tk, val); + } + } + + return results; + } /// /// Return the action type from a rewritten Url. diff --git a/DNN Platform/Library/Entities/Urls/RewriteController.cs b/DNN Platform/Library/Entities/Urls/RewriteController.cs index a10201e654e..e338bec765f 100644 --- a/DNN Platform/Library/Entities/Urls/RewriteController.cs +++ b/DNN Platform/Library/Entities/Urls/RewriteController.cs @@ -44,6 +44,115 @@ public class RewriteController private static readonly Regex RewriteParamsRegex = new Regex( @"(?:\&|\?)(?:(?.[^\=\&]*)\=(?.[^\=\&]*))", RegexOptions.IgnoreCase | RegexOptions.Compiled); + + internal static string CheckLanguageMatch(ref string url, UrlAction result) + { + // ok now scan for the language modifier + Match langMatch = LangMatchRegex.Match(url); + + // searches for a string like language/en-US/ in the url + string langParms = string.Empty; + if (langMatch.Success) + { + // OK there is a language modifier in the path + // we want to shift this so it is back on the end where it belongs + langParms = langMatch.Value.TrimEnd('/'); // in the format of /language/en-US only + + // it doesn't matter if you get /home.aspx/language/en-US in the url field because the .aspx gets + // removed when matching with the tab dictionary + url = url.Replace(langParms, string.Empty) + langParms; + result.CultureCode = langMatch.Groups["code"].Value; // get the culture code in the requested url + + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (primaryAliases.Count > 0) + { + string aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); + if (aliasCulture != null) + { + // want to do a 301 check because this potentially has a duplicate of portal alias and culture code in the url, which + // is not the best combination + if (result.Action == ActionType.Continue) + { + result.Action = ActionType.CheckFor301; + } + } + } + } + + return langParms; + } + + /// + /// appends a language/culture code value if it is not already present in the rewrite path. + /// + /// + /// + /// + internal static bool AddLanguageCodeToRewritePath(ref string rewritePath, string cultureCode) + { + bool changed = false; + + // 758 : check for any language identifier in the Url before adding a new one, not just the same one + if (!string.IsNullOrEmpty(cultureCode) && !rewritePath.ToLowerInvariant().Contains("language=")) + { + changed = true; + if (rewritePath.Contains("?")) + { + rewritePath += "&language=" + cultureCode; + } + else + { + rewritePath += "?language=" + cultureCode; + } + } + + return changed; + } + + /// + /// appends a skin value to the rewrite path, as long as there is no existing skin in the path. + /// + /// + /// The current rewrite path. + /// The selected skin. + /// + /// + /// 852 : Add skin src to rewrite path for specific aliases. + /// + internal static bool AddSkinToRewritePath(int tabId, int portalId, ref string rewritePath, string skin, out string message) + { + bool changed = false; + message = null; + TabInfo tab = null; + if (tabId > 0 && portalId > -1) + { + tab = TabController.Instance.GetTab(tabId, portalId, false); + } + + // don't overwrite specific skin at tab level for rewritten Urls + if (tab == null || string.IsNullOrEmpty(tab.SkinSrc)) + { + if (!string.IsNullOrEmpty(skin) && skin != "default" && !rewritePath.ToLowerInvariant().Contains("skinsrc=")) + { + message = "Added SkinSrc : " + skin; + changed = true; + rewritePath += rewritePath.Contains("?") ? "&SkinSrc=" + skin.Replace(".ascx", string.Empty) : "?SkinSrc=" + skin.Replace(".ascx", string.Empty); + } + } + else + { + if (!string.IsNullOrEmpty(tab.SkinSrc)) + { + message = "Tab " + tab.TabID.ToString() + " has skin specified : " + tab.SkinSrc; + if (skin != tab.SkinSrc) + { + message += " - " + skin + " not applied due to tab specific skin"; + } + } + } + + return changed; + } private static string AddQueryStringToRewritePath(string rewritePath, string queryString) { @@ -476,43 +585,6 @@ private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrl return found; } - internal static string CheckLanguageMatch(ref string url, UrlAction result) - { - // ok now scan for the language modifier - Match langMatch = LangMatchRegex.Match(url); - - // searches for a string like language/en-US/ in the url - string langParms = string.Empty; - if (langMatch.Success) - { - // OK there is a language modifier in the path - // we want to shift this so it is back on the end where it belongs - langParms = langMatch.Value.TrimEnd('/'); // in the format of /language/en-US only - - // it doesn't matter if you get /home.aspx/language/en-US in the url field because the .aspx gets - // removed when matching with the tab dictionary - url = url.Replace(langParms, string.Empty) + langParms; - result.CultureCode = langMatch.Groups["code"].Value; // get the culture code in the requested url - - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - if (primaryAliases.Count > 0) - { - string aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(result.PortalId, result.HttpAlias); - if (aliasCulture != null) - { - // want to do a 301 check because this potentially has a duplicate of portal alias and culture code in the url, which - // is not the best combination - if (result.Action == ActionType.Continue) - { - result.Action = ActionType.CheckFor301; - } - } - } - } - - return langParms; - } - private static string ReplaceDefaultPage(string newUrl, string requestUrl, IEnumerable list) { string url = newUrl; // fall back case: we don't change anything @@ -602,78 +674,6 @@ private static void SetRewriteParameters(ref UrlAction result, string rewritePat // remove the application path result.RewritePath = result.RewritePath.Replace(result.ApplicationPath + "/", string.Empty); } - - /// - /// appends a language/culture code value if it is not already present in the rewrite path. - /// - /// - /// - /// - internal static bool AddLanguageCodeToRewritePath(ref string rewritePath, string cultureCode) - { - bool changed = false; - - // 758 : check for any language identifier in the Url before adding a new one, not just the same one - if (!string.IsNullOrEmpty(cultureCode) && !rewritePath.ToLowerInvariant().Contains("language=")) - { - changed = true; - if (rewritePath.Contains("?")) - { - rewritePath += "&language=" + cultureCode; - } - else - { - rewritePath += "?language=" + cultureCode; - } - } - - return changed; - } - - /// - /// appends a skin value to the rewrite path, as long as there is no existing skin in the path. - /// - /// - /// The current rewrite path. - /// The selected skin. - /// - /// - /// 852 : Add skin src to rewrite path for specific aliases. - /// - internal static bool AddSkinToRewritePath(int tabId, int portalId, ref string rewritePath, string skin, out string message) - { - bool changed = false; - message = null; - TabInfo tab = null; - if (tabId > 0 && portalId > -1) - { - tab = TabController.Instance.GetTab(tabId, portalId, false); - } - - // don't overwrite specific skin at tab level for rewritten Urls - if (tab == null || string.IsNullOrEmpty(tab.SkinSrc)) - { - if (!string.IsNullOrEmpty(skin) && skin != "default" && !rewritePath.ToLowerInvariant().Contains("skinsrc=")) - { - message = "Added SkinSrc : " + skin; - changed = true; - rewritePath += rewritePath.Contains("?") ? "&SkinSrc=" + skin.Replace(".ascx", string.Empty) : "?SkinSrc=" + skin.Replace(".ascx", string.Empty); - } - } - else - { - if (!string.IsNullOrEmpty(tab.SkinSrc)) - { - message = "Tab " + tab.TabID.ToString() + " has skin specified : " + tab.SkinSrc; - if (skin != tab.SkinSrc) - { - message += " - " + skin + " not applied due to tab specific skin"; - } - } - } - - return changed; - } /// /// Checks for exclusions on Rewriting the path, based on a regex pattern. @@ -686,28 +686,28 @@ internal static bool CanRewriteRequest(UrlAction result, string requestedPath, F { bool retVal; try - { - // var uri = new Uri(requestedPath); - // if (uri.PathAndQuery.ToLowerInvariant().StartsWith("/default.aspx")) - // { - // retVal = false; - // result.CanRewrite = StateBoolean.True; - // result.RewritePath = uri.PathAndQuery.Substring(1); - // } - // else - // { - if (string.IsNullOrEmpty(settings.DoNotRewriteRegex) || - (!Regex.IsMatch(requestedPath, settings.DoNotRewriteRegex, - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))) - { - retVal = true; - result.CanRewrite = StateBoolean.True; - } - else - { - retVal = false; - result.CanRewrite = StateBoolean.False; - } + { + // var uri = new Uri(requestedPath); + // if (uri.PathAndQuery.ToLowerInvariant().StartsWith("/default.aspx")) + // { + // retVal = false; + // result.CanRewrite = StateBoolean.True; + // result.RewritePath = uri.PathAndQuery.Substring(1); + // } + // else + // { + if (string.IsNullOrEmpty(settings.DoNotRewriteRegex) || + (!Regex.IsMatch(requestedPath, settings.DoNotRewriteRegex, + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))) + { + retVal = true; + result.CanRewrite = StateBoolean.True; + } + else + { + retVal = false; + result.CanRewrite = StateBoolean.False; + } // } } @@ -1060,15 +1060,15 @@ internal static string GetTabFromDictionary(string url, NameValueCollection quer // 948 : use new 'no downgrade' method result.SetActionWithNoDowngrade(ActionType.CheckFor301); } - else + else - // 866 : redirect back from no extension to extension if it didn't have one + // 866 : redirect back from no extension to extension if it didn't have one if (settings.PageExtensionUsageType != PageExtensionUsageType.Never && - hadExtension == false) - { - // 948 : use new 'no downgrade' method - result.SetActionWithNoDowngrade(ActionType.CheckFor301); - } + hadExtension == false) + { + // 948 : use new 'no downgrade' method + result.SetActionWithNoDowngrade(ActionType.CheckFor301); + } } if (isSiteRootMatch && !finished) diff --git a/DNN Platform/Library/Entities/Urls/TabIndexController.cs b/DNN Platform/Library/Entities/Urls/TabIndexController.cs index 2bac36e912f..cdb5fc9b2a8 100644 --- a/DNN Platform/Library/Entities/Urls/TabIndexController.cs +++ b/DNN Platform/Library/Entities/Urls/TabIndexController.cs @@ -23,6 +23,49 @@ internal static class TabIndexController { private static readonly object tabPathDictBuildLock = new object(); + public static void InvalidateDictionary(string reason, PageIndexData rebuildData, int portalId) + { + // if supplied, store the rebuildData for when the dictionary gets rebuilt + // this is a way of storing data between dictionary rebuilds + if (rebuildData != null) + { + DataCache.SetCache("rebuildData", rebuildData); + } + + // add log entry for cache clearance + var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + try + { + // 817 : not clearing items correctly from dictionary + CacheController.FlushPageIndexFromCache(); + } + catch (Exception ex) + { + // do nothing ; can be from trying to access cache after system restart + Services.Exceptions.Exceptions.LogException(ex); + } + + log.AddProperty("Url Rewriting Caching Message", "Page Index Cache Cleared. Reason: " + reason); + log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); + LogController.Instance.AddLog(log); + } + + internal static string CreateRewritePath(int tabId, string cultureCode, params string[] keyValuePair) + { + string rewritePath = "?TabId=" + tabId.ToString(); + + // 736 : 5.5 compatibility - identify tab rewriting at source by tab culture code + RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, cultureCode); + return keyValuePair.Aggregate(rewritePath, (current, keyValue) => current + ("&" + keyValue)); + } + + internal static string CreateRewritePath(int tabId, string cultureCode, ActionType action, RedirectReason reason) + { + string rewritePath = CreateRewritePath(tabId, cultureCode); + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, action, reason); + return rewritePath; + } + private static void AddCustomRedirectsToDictionary( SharedDictionary tabIndex, Dictionary dupCheck, @@ -1001,17 +1044,17 @@ private static void AddToTabDict( } private static OrderedDictionary BuildPortalAliasesDictionary() - { - var aliases = PortalAliasController.Instance.GetPortalAliases(); - - // create a new OrderedDictionary. We use this because we - // want to key by the correct regex pattern and return the - // portalAlias that matches, and we want to preserve the - // order of the items, such that the item with the most path separators (/) - // is at the front of the list. - var aliasList = new OrderedDictionary(aliases.Count); - var pathLengths = new List(); - foreach (string aliasKey in aliases.Keys) + { + var aliases = PortalAliasController.Instance.GetPortalAliases(); + + // create a new OrderedDictionary. We use this because we + // want to key by the correct regex pattern and return the + // portalAlias that matches, and we want to preserve the + // order of the items, such that the item with the most path separators (/) + // is at the front of the list. + var aliasList = new OrderedDictionary(aliases.Count); + var pathLengths = new List(); + foreach (string aliasKey in aliases.Keys) { PortalAliasInfo alias = aliases[aliasKey]; @@ -1084,9 +1127,9 @@ private static OrderedDictionary BuildPortalAliasesDictionary() pathLengths.Add(pathLength); } } - } + } - return aliasList; + return aliasList; } private static SharedDictionary BuildTabDictionary( @@ -1203,9 +1246,9 @@ private static SharedDictionary BuildTabDictionary( // the tab is the wrong culture, so don't add it to the dictionary if (aliasCulture != string.Empty) { - if (tabCulture != aliasCulture + if (tabCulture != aliasCulture - // this is a language-specific alias that's different to the culture for this alias + // this is a language-specific alias that's different to the culture for this alias && !string.IsNullOrEmpty(tabCulture) // and the tab culture is set && aliasSpecificCultures.Contains(tabCulture)) @@ -1472,43 +1515,6 @@ private static string ManageCustomAliases( return customHttpAlias; } - - internal static string CreateRewritePath(int tabId, string cultureCode, params string[] keyValuePair) - { - string rewritePath = "?TabId=" + tabId.ToString(); - - // 736 : 5.5 compatibility - identify tab rewriting at source by tab culture code - RewriteController.AddLanguageCodeToRewritePath(ref rewritePath, cultureCode); - return keyValuePair.Aggregate(rewritePath, (current, keyValue) => current + ("&" + keyValue)); - } - - internal static string CreateRewritePath(int tabId, string cultureCode, ActionType action, RedirectReason reason) - { - string rewritePath = CreateRewritePath(tabId, cultureCode); - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, action, reason); - return rewritePath; - } - - /// - /// Returns whether the portal specified exists in the Tab index or not. - /// - /// The current portalDepths dictionary. - /// The id of the portal to search for. - /// - private static bool PortalExistsInIndex(SharedDictionary portalDepths, int portalId) - { - bool result = false; - - if (portalDepths != null) - { - using (portalDepths.GetReadLock()) - { - result = portalDepths.ContainsKey(portalId); - } - } - - return result; - } /// /// Gets the Tab Dictionary from the DataCache memory location, if it's empty or missing, builds a new one. @@ -1665,6 +1671,27 @@ internal static List GetCustomPortalAliases(FriendlyUrlSettings settings return aliases; } + /// + /// Returns whether the portal specified exists in the Tab index or not. + /// + /// The current portalDepths dictionary. + /// The id of the portal to search for. + /// + private static bool PortalExistsInIndex(SharedDictionary portalDepths, int portalId) + { + bool result = false; + + if (portalDepths != null) + { + using (portalDepths.GetReadLock()) + { + result = portalDepths.ContainsKey(portalId); + } + } + + return result; + } + /// /// Gets the portal alias by portal. /// @@ -1785,32 +1812,5 @@ internal static string GetTabPath(TabInfo tab, FriendlyUrlOptions options, Guid return tabPath ?? TabPathHelper.GetFriendlyUrlTabPath(tab, options, parentTraceId); } - - public static void InvalidateDictionary(string reason, PageIndexData rebuildData, int portalId) - { - // if supplied, store the rebuildData for when the dictionary gets rebuilt - // this is a way of storing data between dictionary rebuilds - if (rebuildData != null) - { - DataCache.SetCache("rebuildData", rebuildData); - } - - // add log entry for cache clearance - var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; - try - { - // 817 : not clearing items correctly from dictionary - CacheController.FlushPageIndexFromCache(); - } - catch (Exception ex) - { - // do nothing ; can be from trying to access cache after system restart - Services.Exceptions.Exceptions.LogException(ex); - } - - log.AddProperty("Url Rewriting Caching Message", "Page Index Cache Cleared. Reason: " + reason); - log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); - LogController.Instance.AddLog(log); - } } } diff --git a/DNN Platform/Library/Entities/Urls/TabPathController.cs b/DNN Platform/Library/Entities/Urls/TabPathController.cs index e29bab0f525..16d21f1d567 100644 --- a/DNN Platform/Library/Entities/Urls/TabPathController.cs +++ b/DNN Platform/Library/Entities/Urls/TabPathController.cs @@ -20,27 +20,49 @@ namespace DotNetNuke.Entities.Urls /// public class TabPathHelper { - private static string AppendToTabPath(string path, TabInfo tab, FriendlyUrlOptions options, out bool modified) + public static string BuildTabPathWithReplacement(TabInfo tab, FriendlyUrlOptions options, Guid parentTraceId) { - string tabName = tab.TabName; - var result = new StringBuilder(tabName.Length); - - // 922 : change to harmonise cleaning of tab + other url name items - tabName = FriendlyUrlController.CleanNameForUrl(tabName, options, out modified); - if (!modified - && string.IsNullOrEmpty(options.PunctuationReplacement) == false - && tab.TabName.Contains(" ") - && tabName.Contains(" ") == false) + string path = string.Empty; + if (tab.ParentId > -1) { - modified = true; + TabInfo parentTab = TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false); - // spaces replaced - the modified parameter is for all other replacements but space replacements + // 822 : don't assume parent tab is going to exist - database might be corrupted + // 896 : check to make sure tabid and parentid are different - or stack overflow occurs with terminal loop + if (parentTab != null && parentTab.TabID != tab.TabID) + { + path = BuildTabPathWithReplacement(parentTab, options, parentTraceId); + } } - result.Append(tabName); - result.Insert(0, "//"); - result.Insert(0, path); // effectively adds result to the end of the path - return result.ToString(); + bool modified; + path = AppendToTabPath(path, tab, options, out modified); + + return path; + } + + /// + /// Replaces the diacritic characters in a path with other values. + /// + /// + /// + /// + public static string ReplaceDiacritics(string tabPath, out bool replacedDiacritic) + { + string nmTabPath = tabPath.Normalize(NormalizationForm.FormD); + var sb = new StringBuilder(); + for (int i = 0; i < nmTabPath.Length; i++) + { + char c = nmTabPath[i]; + if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) + { + sb.Append(c); + } + } + + string result = sb.ToString(); + replacedDiacritic = string.CompareOrdinal(tabPath, result) != 0; + return sb.ToString(); } /// @@ -97,6 +119,29 @@ internal static int GetHomePageTabIdForCulture(string defaultCulture, int portal return homeTabId; } + + private static string AppendToTabPath(string path, TabInfo tab, FriendlyUrlOptions options, out bool modified) + { + string tabName = tab.TabName; + var result = new StringBuilder(tabName.Length); + + // 922 : change to harmonise cleaning of tab + other url name items + tabName = FriendlyUrlController.CleanNameForUrl(tabName, options, out modified); + if (!modified + && string.IsNullOrEmpty(options.PunctuationReplacement) == false + && tab.TabName.Contains(" ") + && tabName.Contains(" ") == false) + { + modified = true; + + // spaces replaced - the modified parameter is for all other replacements but space replacements + } + + result.Append(tabName); + result.Insert(0, "//"); + result.Insert(0, path); // effectively adds result to the end of the path + return result.ToString(); + } internal static string GetTabAliasSkinForTabAndAlias(int portalId, string httpAlias, string culture) { @@ -348,50 +393,5 @@ internal static bool IsTabHomePage(TabInfo tab, PortalSettings portalSettings) return isTabHomePage; } - - public static string BuildTabPathWithReplacement(TabInfo tab, FriendlyUrlOptions options, Guid parentTraceId) - { - string path = string.Empty; - if (tab.ParentId > -1) - { - TabInfo parentTab = TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false); - - // 822 : don't assume parent tab is going to exist - database might be corrupted - // 896 : check to make sure tabid and parentid are different - or stack overflow occurs with terminal loop - if (parentTab != null && parentTab.TabID != tab.TabID) - { - path = BuildTabPathWithReplacement(parentTab, options, parentTraceId); - } - } - - bool modified; - path = AppendToTabPath(path, tab, options, out modified); - - return path; - } - - /// - /// Replaces the diacritic characters in a path with other values. - /// - /// - /// - /// - public static string ReplaceDiacritics(string tabPath, out bool replacedDiacritic) - { - string nmTabPath = tabPath.Normalize(NormalizationForm.FormD); - var sb = new StringBuilder(); - for (int i = 0; i < nmTabPath.Length; i++) - { - char c = nmTabPath[i]; - if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) - { - sb.Append(c); - } - } - - string result = sb.ToString(); - replacedDiacritic = string.CompareOrdinal(tabPath, result) != 0; - return sb.ToString(); - } } } diff --git a/DNN Platform/Library/Entities/Urls/UrlAction.cs b/DNN Platform/Library/Entities/Urls/UrlAction.cs index b8db7874ae5..9ddc42cd9a0 100644 --- a/DNN Platform/Library/Entities/Urls/UrlAction.cs +++ b/DNN Platform/Library/Entities/Urls/UrlAction.cs @@ -16,6 +16,9 @@ namespace DotNetNuke.Entities.Urls /// public class UrlAction { + private List _licensedProviders; + private PortalAliasInfo _portalAlias; + // 829 add in constructor that works around physical path length restriction public UrlAction(HttpRequest request) { @@ -52,6 +55,8 @@ public UrlAction(string scheme, string applicationPath, string physicalPath) this.Action = ActionType.Continue; this.Constructor(scheme, applicationPath, physicalPath); } + + public Uri Url { get; set; } private void Constructor(string scheme, string applicationPath, string physicalPath) { @@ -80,11 +85,6 @@ private void Constructor(string scheme, string applicationPath, string physicalP this.CultureCode = null; } - private List _licensedProviders; - private PortalAliasInfo _portalAlias; - - public Uri Url { get; set; } - public bool DoRewrite { get; set; } public bool FriendlyRewrite { get; set; } diff --git a/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs b/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs index e6e251d89dc..464e17525a8 100644 --- a/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs +++ b/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs @@ -26,23 +26,23 @@ public static class UrlRewriterUtils /// public static FriendlyUrlOptions GetOptionsFromSettings(FriendlyUrlSettings settings) { - var options = new FriendlyUrlOptions - { - PunctuationReplacement = (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) + var options = new FriendlyUrlOptions + { + PunctuationReplacement = (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) ? settings.ReplaceSpaceWith - : string.Empty, - SpaceEncoding = settings.SpaceEncodingValue, - MaxUrlPathLength = 200, - ConvertDiacriticChars = settings.AutoAsciiConvert, - RegexMatch = settings.RegexMatch, - IllegalChars = settings.IllegalChars, - ReplaceChars = settings.ReplaceChars, - ReplaceDoubleChars = settings.ReplaceDoubleChars, - ReplaceCharWithChar = settings.ReplaceCharacterDictionary, - PageExtension = (settings.PageExtensionUsageType == PageExtensionUsageType.Never) + : string.Empty, + SpaceEncoding = settings.SpaceEncodingValue, + MaxUrlPathLength = 200, + ConvertDiacriticChars = settings.AutoAsciiConvert, + RegexMatch = settings.RegexMatch, + IllegalChars = settings.IllegalChars, + ReplaceChars = settings.ReplaceChars, + ReplaceDoubleChars = settings.ReplaceDoubleChars, + ReplaceCharWithChar = settings.ReplaceCharacterDictionary, + PageExtension = (settings.PageExtensionUsageType == PageExtensionUsageType.Never) ? string.Empty - : settings.PageExtension, - }; + : settings.PageExtension, + }; return options; } @@ -77,14 +77,14 @@ public static FriendlyUrlOptions ExtendOptionsForCustomURLs(FriendlyUrlOptions o /// public static void Log404(HttpRequest request, FriendlyUrlSettings settings, UrlAction result) { - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), - LogPortalID = (result.PortalAlias != null) ? result.PortalId : -1, - }; + var log = new LogInfo + { + LogTypeKey = EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString(), + 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("PortalAlias", (result.PortalAlias != null) ? result.PortalAlias.HTTPAlias : string.Empty)); - log.LogProperties.Add(new LogDetailInfo("OriginalUrl", result.RawUrl)); + log.LogProperties.Add(new LogDetailInfo("PortalAlias", (result.PortalAlias != null) ? result.PortalAlias.HTTPAlias : string.Empty)); + log.LogProperties.Add(new LogDetailInfo("OriginalUrl", result.RawUrl)); if (request != null) { diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs index 206c8464908..701ae832ed0 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs @@ -20,6 +20,28 @@ public class MembershipPasswordController { private readonly DataProvider _dataProvider = DataProvider.Instance(); + /// + /// returns the password history of the supplied user. + /// + /// list of PasswordHistory objects. + public List GetPasswordHistory(int userId) + { + return this.GetPasswordHistory(userId, Null.NullInteger); + } + + /// + /// returns the password history of the supplied user. + /// + /// portalid - futureproofing against any setting become site level. + /// list of PasswordHistory objects. + public List GetPasswordHistory(int userId, int portalId) + { + var settings = new MembershipPasswordSettings(portalId); + List history = + CBO.FillCollection(this._dataProvider.GetPasswordHistory(userId, settings.NumberOfPasswordsStored, settings.NumberOfDaysBeforePasswordReuse)); + return history; + } + private void AddPasswordHistory(int userId, string password, int passwordsRetained, int daysRetained) { using (HashAlgorithm ha = HashAlgorithm.Create()) @@ -45,28 +67,6 @@ private byte[] GetRandomSaltValue() return bSalt; } } - - /// - /// returns the password history of the supplied user. - /// - /// list of PasswordHistory objects. - public List GetPasswordHistory(int userId) - { - return this.GetPasswordHistory(userId, Null.NullInteger); - } - - /// - /// returns the password history of the supplied user. - /// - /// portalid - futureproofing against any setting become site level. - /// list of PasswordHistory objects. - public List GetPasswordHistory(int userId, int portalId) - { - var settings = new MembershipPasswordSettings(portalId); - List history = - CBO.FillCollection(this._dataProvider.GetPasswordHistory(userId, settings.NumberOfPasswordsStored, settings.NumberOfDaysBeforePasswordReuse)); - return history; - } /// /// checks to see if the password is in history and adds it if it is not. diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs index cc6bd1fdc91..e4b7928a62e 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs @@ -13,6 +13,34 @@ namespace DotNetNuke.Entities.Users.Membership public class MembershipPasswordSettings { + /// + /// Initializes a new instance of the class. + /// Initialiser for MembershipPasswordSettings provider object. + /// + public MembershipPasswordSettings(int portalId) + { + // portalId not used currently - left in place for potential site specific settings + this.PortalId = portalId; + + if (HttpContext.Current != null && !IsInstallRequest(HttpContext.Current.Request)) + { + this.EnableBannedList = Host.Host.EnableBannedList; + this.EnableStrengthMeter = Host.Host.EnableStrengthMeter; + this.EnableIPChecking = Host.Host.EnableIPChecking; + this.EnablePasswordHistory = Host.Host.EnablePasswordHistory; + + this.ResetLinkValidity = Host.Host.MembershipResetLinkValidity; + this.NumberOfPasswordsStored = Host.Host.MembershipNumberPasswords; + this.NumberOfDaysBeforePasswordReuse = Host.Host.MembershipDaysBeforePasswordReuse; + } + else // setup default values during install process. + { + this.EnableStrengthMeter = true; + this.EnableBannedList = true; + this.EnablePasswordHistory = true; + } + } + public bool EnableBannedList { get; set; } public bool EnableStrengthMeter { get; set; } @@ -75,34 +103,6 @@ public string ValidationExpression { get { return System.Web.Security.Membership.PasswordStrengthRegularExpression; } } - - /// - /// Initializes a new instance of the class. - /// Initialiser for MembershipPasswordSettings provider object. - /// - public MembershipPasswordSettings(int portalId) - { - // portalId not used currently - left in place for potential site specific settings - this.PortalId = portalId; - - if (HttpContext.Current != null && !IsInstallRequest(HttpContext.Current.Request)) - { - this.EnableBannedList = Host.Host.EnableBannedList; - this.EnableStrengthMeter = Host.Host.EnableStrengthMeter; - this.EnableIPChecking = Host.Host.EnableIPChecking; - this.EnablePasswordHistory = Host.Host.EnablePasswordHistory; - - this.ResetLinkValidity = Host.Host.MembershipResetLinkValidity; - this.NumberOfPasswordsStored = Host.Host.MembershipNumberPasswords; - this.NumberOfDaysBeforePasswordReuse = Host.Host.MembershipDaysBeforePasswordReuse; - } - else // setup default values during install process. - { - this.EnableStrengthMeter = true; - this.EnableBannedList = true; - this.EnablePasswordHistory = true; - } - } public int PortalId { get; set; } diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs index 8e752d4dd10..b936c44b878 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs @@ -16,6 +16,14 @@ public MembershipPropertyAccess(UserInfo User) { this.objUser = User; } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope CurrentScope, ref bool PropertyNotFound) { @@ -75,13 +83,5 @@ public string GetProperty(string propertyName, string format, CultureInfo format return PropertyAccess.GetObjectProperty(objMembership, propertyName, format, formatProvider, ref PropertyNotFound); } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } } } diff --git a/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs b/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs index ae8ca4bb9e2..252a0dc7aae 100644 --- a/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs +++ b/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs @@ -60,13 +60,6 @@ public bool Approved } } - internal bool Approving { get; private set; } - - internal void ConfirmApproved() - { - this.Approving = false; - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the User's Creation Date. @@ -89,6 +82,13 @@ internal void ConfirmApproved() [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public bool IsOnLine { get; set; } + internal bool Approving { get; private set; } + + internal void ConfirmApproved() + { + this.Approving = false; + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Last Activity Date of the User. diff --git a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs index 8fcad57dd35..f13eaf3482e 100644 --- a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs @@ -33,75 +33,6 @@ public ProfilePropertyAccess(UserInfo user) this.user = user; } - private static bool IsAdminUser(PortalSettings portalSettings, UserInfo accessingUser, UserInfo targetUser) - { - bool isAdmin = false; - - if (accessingUser != null) - { - // Is Super User? - isAdmin = accessingUser.IsSuperUser; - - if (!isAdmin && targetUser.PortalID != -1) - { - // Is Administrator - var administratorRoleName = portalSettings != null - ? portalSettings.AdministratorRoleName - : PortalController.Instance.GetPortal(targetUser.PortalID).AdministratorRoleName; - - isAdmin = accessingUser.IsInRole(administratorRoleName); - } - } - - return isAdmin; - } - - private static bool IsMember(UserInfo accessingUser) - { - return accessingUser != null && accessingUser.UserID != -1; - } - - private static bool IsUser(UserInfo accessingUser, UserInfo targetUser) - { - return accessingUser != null && accessingUser.UserID == targetUser.UserID; - } - - 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) - { - var profile = this.user.Profile; - var property = profile.ProfileProperties.Cast() - .SingleOrDefault(p => string.Equals(p.PropertyName, propertyName, StringComparison.CurrentCultureIgnoreCase)); - - if (property != null) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (CheckAccessLevel(portalSettings, property, accessingUser, this.user)) - { - switch (property.PropertyName.ToLowerInvariant()) - { - case "photo": - return this.user.Profile.PhotoURL; - case "country": - return this.user.Profile.Country; - case "region": - return this.user.Profile.Region; - default: - return GetRichValue(property, format, formatProvider); - } - } - } - - propertyNotFound = true; - return property != null && property.PropertyName.Equals("photo", StringComparison.InvariantCultureIgnoreCase) - ? Globals.ApplicationPath + "/images/no_avatar.gif" : PropertyAccess.ContentLocked; - } - - propertyNotFound = true; - return string.Empty; - } - public CacheLevel Cacheability { get @@ -237,6 +168,75 @@ public static string GetRichValue(ProfilePropertyDefinition property, string for return result; } + 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) + { + var profile = this.user.Profile; + var property = profile.ProfileProperties.Cast() + .SingleOrDefault(p => string.Equals(p.PropertyName, propertyName, StringComparison.CurrentCultureIgnoreCase)); + + if (property != null) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (CheckAccessLevel(portalSettings, property, accessingUser, this.user)) + { + switch (property.PropertyName.ToLowerInvariant()) + { + case "photo": + return this.user.Profile.PhotoURL; + case "country": + return this.user.Profile.Country; + case "region": + return this.user.Profile.Region; + default: + return GetRichValue(property, format, formatProvider); + } + } + } + + propertyNotFound = true; + return property != null && property.PropertyName.Equals("photo", StringComparison.InvariantCultureIgnoreCase) + ? Globals.ApplicationPath + "/images/no_avatar.gif" : PropertyAccess.ContentLocked; + } + + propertyNotFound = true; + return string.Empty; + } + + private static bool IsAdminUser(PortalSettings portalSettings, UserInfo accessingUser, UserInfo targetUser) + { + bool isAdmin = false; + + if (accessingUser != null) + { + // Is Super User? + isAdmin = accessingUser.IsSuperUser; + + if (!isAdmin && targetUser.PortalID != -1) + { + // Is Administrator + var administratorRoleName = portalSettings != null + ? portalSettings.AdministratorRoleName + : PortalController.Instance.GetPortal(targetUser.PortalID).AdministratorRoleName; + + isAdmin = accessingUser.IsInRole(administratorRoleName); + } + } + + return isAdmin; + } + + private static bool IsMember(UserInfo accessingUser) + { + return accessingUser != null && accessingUser.UserID != -1; + } + + private static bool IsUser(UserInfo accessingUser, UserInfo targetUser) + { + return accessingUser != null && accessingUser.UserID == targetUser.UserID; + } + public static string DisplayDataType(ProfilePropertyDefinition definition) { string cacheKey = string.Format("DisplayDataType:{0}", definition.DataType); diff --git a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs index 13bb9648d17..84b3a9a2fa3 100644 --- a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs +++ b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs @@ -516,6 +516,48 @@ public string Website } } + public string Biography + { + get + { + return this.GetPropertyValue(USERPROFILE_Biography); + } + + set + { + this.SetProfileProperty(USERPROFILE_Biography, value); + } + } + + public object this[string name] + { + get + { + return this.GetPropertyValue(name); + } + + set + { + string stringValue; + if (value is DateTime) + { + var dateValue = (DateTime)value; + stringValue = dateValue.ToString(CultureInfo.InvariantCulture); + } + else if (value is TimeZoneInfo) + { + var timezoneValue = (TimeZoneInfo)value; + stringValue = timezoneValue.Id; + } + else + { + stringValue = Convert.ToString(value); + } + + this.SetProfileProperty(name, stringValue); + } + } + /// ----------------------------------------------------------------------------- /// /// Clears the IsDirty Flag. @@ -573,22 +615,6 @@ public string GetPropertyValue(string propName) return propValue; } - private string GetListValue(string listName, string value) - { - ListController lc = new ListController(); - int entryId; - if (int.TryParse(value, out entryId)) - { - ListEntryInfo item = lc.GetListEntryInfo(listName, entryId); - if (item != null) - { - return item.Text; - } - } - - return value; - } - /// ----------------------------------------------------------------------------- /// /// Initialises the Profile with an empty collection of profile properties. @@ -622,6 +648,22 @@ public void InitialiseProfile(int portalId, bool useDefaults) } } + private string GetListValue(string listName, string value) + { + ListController lc = new ListController(); + int entryId; + if (int.TryParse(value, out entryId)) + { + ListEntryInfo item = lc.GetListEntryInfo(listName, entryId); + if (item != null) + { + return item.Text; + } + } + + return value; + } + /// ----------------------------------------------------------------------------- /// /// Sets a Profile Property Value in the Profile. @@ -644,47 +686,5 @@ public void SetProfileProperty(string propName, string propValue) } } } - - public string Biography - { - get - { - return this.GetPropertyValue(USERPROFILE_Biography); - } - - set - { - this.SetProfileProperty(USERPROFILE_Biography, value); - } - } - - public object this[string name] - { - get - { - return this.GetPropertyValue(name); - } - - set - { - string stringValue; - if (value is DateTime) - { - var dateValue = (DateTime)value; - stringValue = dateValue.ToString(CultureInfo.InvariantCulture); - } - else if (value is TimeZoneInfo) - { - var timezoneValue = (TimeZoneInfo)value; - stringValue = timezoneValue.Id; - } - else - { - stringValue = Convert.ToString(value); - } - - this.SetProfileProperty(name, stringValue); - } - } } } diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs index eee83cc93aa..9e33f985a39 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs @@ -363,14 +363,14 @@ public UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserIn status = RelationshipStatus.Pending; } - var userRelationship = new UserRelationship - { - UserRelationshipId = Null.NullInteger, - UserId = initiatingUser.UserID, - RelatedUserId = targetUser.UserID, - RelationshipId = relationship.RelationshipId, - Status = status, - }; + var userRelationship = new UserRelationship + { + UserRelationshipId = Null.NullInteger, + UserId = initiatingUser.UserID, + RelatedUserId = targetUser.UserID, + RelationshipId = relationship.RelationshipId, + Status = status, + }; this.SaveUserRelationship(userRelationship); @@ -519,43 +519,43 @@ public void CreateDefaultRelationshipsForPortal(int portalId) // create default Friend Relationship if (this.GetFriendsRelationshipByPortal(portalId) == null) { - var friendRelationship = new Relationship - { - RelationshipId = Null.NullInteger, - Name = DefaultRelationshipTypes.Friends.ToString(), - Description = DefaultRelationshipTypes.Friends.ToString(), - PortalId = portalId, - UserId = Null.NullInteger, - DefaultResponse = RelationshipStatus.None, + var friendRelationship = new Relationship + { + RelationshipId = Null.NullInteger, + Name = DefaultRelationshipTypes.Friends.ToString(), + Description = DefaultRelationshipTypes.Friends.ToString(), + PortalId = portalId, + UserId = Null.NullInteger, + DefaultResponse = RelationshipStatus.None, - // default response is None - RelationshipTypeId = (int)DefaultRelationshipTypes.Friends, - }; + // default response is None + RelationshipTypeId = (int)DefaultRelationshipTypes.Friends, + }; this.SaveRelationship(friendRelationship); } // create default Follower Relationship if (this.GetFollowersRelationshipByPortal(portalId) == null) { - var followerRelationship = new Relationship - { - RelationshipId = Null.NullInteger, - Name = DefaultRelationshipTypes.Followers.ToString(), - Description = DefaultRelationshipTypes.Followers.ToString(), - PortalId = portalId, - UserId = Null.NullInteger, - DefaultResponse = RelationshipStatus.Accepted, + var followerRelationship = new Relationship + { + RelationshipId = Null.NullInteger, + Name = DefaultRelationshipTypes.Followers.ToString(), + Description = DefaultRelationshipTypes.Followers.ToString(), + PortalId = portalId, + UserId = Null.NullInteger, + DefaultResponse = RelationshipStatus.Accepted, - // default response is Accepted - RelationshipTypeId = (int)DefaultRelationshipTypes.Followers, - }; + // default response is Accepted + RelationshipTypeId = (int)DefaultRelationshipTypes.Followers, + }; this.SaveRelationship(followerRelationship); } } public Relationship GetFriendsRelationshipByPortal(int portalId) - { - return this.GetRelationshipsByPortalId(portalId).FirstOrDefault(re => re.RelationshipTypeId == (int)DefaultRelationshipTypes.Friends); + { + return this.GetRelationshipsByPortalId(portalId).FirstOrDefault(re => re.RelationshipTypeId == (int)DefaultRelationshipTypes.Friends); } public Relationship GetFollowersRelationshipByPortal(int portalId) diff --git a/DNN Platform/Library/Entities/Users/UserController.cs b/DNN Platform/Library/Entities/Users/UserController.cs index e1aebccece0..c6f4141f230 100644 --- a/DNN Platform/Library/Entities/Users/UserController.cs +++ b/DNN Platform/Library/Entities/Users/UserController.cs @@ -61,172 +61,52 @@ namespace DotNetNuke.Entities.Users /// ----------------------------------------------------------------------------- public partial class UserController : ServiceLocator, IUserController { - protected override Func GetFactory() - { - return () => new UserController(); - } - public string DisplayFormat { get; set; } public int PortalId { get; set; } - private static void AddEventLog(int portalId, string username, int userId, string portalName, string ip, UserLoginStatus loginStatus) - { - // initialize log record - var objSecurity = PortalSecurity.Instance; - var log = new LogInfo - { - LogTypeKey = loginStatus.ToString(), - LogPortalID = portalId, - LogPortalName = portalName, - LogUserName = objSecurity.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup), - LogUserID = userId, - }; - log.AddProperty("IP", ip); - - // create log record - LogController.Instance.AddLog(log); - } - - private static void AutoAssignUsersToPortalRoles(UserInfo user, int portalId) - { - foreach (var role in RoleController.Instance.GetRoles(portalId, role => role.AutoAssignment && role.Status == RoleStatus.Approved)) - { - RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - - // Clear the roles cache - so the usercount is correct - RoleController.Instance.ClearRoleCache(portalId); - } - - private static void AutoAssignUsersToRoles(UserInfo user, int portalId) - { - var thisPortal = PortalController.Instance.GetPortal(portalId); - - if (IsMemberOfPortalGroup(portalId)) - { - foreach (var portal in PortalGroupController.Instance.GetPortalsByGroup(thisPortal.PortalGroupID)) - { - if (!user.Membership.Approved && portal.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) - { - var role = RoleController.Instance.GetRole(portal.PortalID, r => r.RoleName == "Unverified Users"); - RoleController.Instance.AddUserRole(portal.PortalID, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - else - { - AutoAssignUsersToPortalRoles(user, portal.PortalID); - } - } - } - else - { - if (!user.Membership.Approved && thisPortal.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) - { - var role = RoleController.Instance.GetRole(portalId, r => r.RoleName == "Unverified Users"); - RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - else - { - AutoAssignUsersToPortalRoles(user, portalId); - } - } - } - - // TODO - Handle Portal Groups - private static void DeleteUserPermissions(UserInfo user) - { - FolderPermissionController.DeleteFolderPermissionsByUser(user); - - // Delete Module Permissions - ModulePermissionController.DeleteModulePermissionsByUser(user); - - // Delete Tab Permissions - TabPermissionController.DeleteTabPermissionsByUser(user); - } - - private static void RestoreUserPermissions(UserInfo user) - { - // restore user's folder permission - var userFolderPath = ((PathUtils)PathUtils.Instance).GetUserFolderPathInternal(user); - var portalId = user.IsSuperUser ? Null.NullInteger : user.PortalID; - var userFolder = FolderManager.Instance.GetFolder(portalId, userFolderPath); - - if (userFolder != null) - { - foreach (PermissionInfo permission in PermissionController.GetPermissionsByFolder()) - { - if (permission.PermissionKey.Equals("READ", StringComparison.OrdinalIgnoreCase) - || permission.PermissionKey.Equals("WRITE", StringComparison.OrdinalIgnoreCase) - || permission.PermissionKey.Equals("BROWSE", StringComparison.OrdinalIgnoreCase)) - { - var folderPermission = new FolderPermissionInfo(permission) - { - FolderID = userFolder.FolderID, - UserID = user.UserID, - RoleID = int.Parse(Globals.glbRoleNothing), - AllowAccess = true, - }; - - userFolder.FolderPermissions.Add(folderPermission, true); - } - } - - FolderPermissionController.SaveFolderPermissions((FolderInfo)userFolder); - } - } - - private static void FixMemberPortalId(UserInfo user, int portalId) + /// ----------------------------------------------------------------------------- + /// + /// Gets the number count for all duplicate e-mail adresses in the database. + /// + /// + /// ----------------------------------------------------------------------------- + public static int GetDuplicateEmailCount() { - if (user != null) - { - user.PortalID = portalId; - } + return DataProvider.Instance().GetDuplicateEmailCount(PortalSettings.Current.PortalId); } - private static UserInfo GetCurrentUserInternal() + /// + /// add new userportal record (used for creating sites with existing user). + /// + /// portalid. + /// userid. + public static void AddUserPortal(int portalId, int userId) { - UserInfo user; - if (HttpContext.Current == null) - { - if (!Thread.CurrentPrincipal.Identity.IsAuthenticated) - { - return new UserInfo(); - } - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (portalSettings != null) - { - user = GetCachedUser(portalSettings.PortalId, Thread.CurrentPrincipal.Identity.Name); - return user ?? new UserInfo(); - } - - return new UserInfo(); - } - - user = (UserInfo)HttpContext.Current.Items["UserInfo"]; - return user ?? new UserInfo(); - } + Requires.NotNullOrEmpty("portalId", portalId.ToString()); + Requires.NotNullOrEmpty("userId", userId.ToString()); - private static int GetEffectivePortalId(int portalId) - { - return PortalController.GetEffectivePortalId(portalId); + MembershipProvider.Instance().AddUserPortal(portalId, userId); } - private static object GetUserCountByPortalCallBack(CacheItemArgs cacheItemArgs) + UserInfo IUserController.GetCurrentUserInfo() { - var portalId = (int)cacheItemArgs.ParamList[0]; - var portalUserCount = MembershipProvider.Instance().GetUserCountByPortal(portalId); - DataCache.SetCache(cacheItemArgs.CacheKey, portalUserCount); - return portalUserCount; + return GetCurrentUserInternal(); } - private static SharedDictionary GetUserLookupDictionary(int portalId) + /// ----------------------------------------------------------------------------- + /// + /// GetUser retrieves a User from the DataStore. + /// + /// + /// + /// The Id of the Portal. + /// The Id of the user being retrieved from the Data Store. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public UserInfo GetUser(int portalId, int userId) { - var masterPortalId = GetEffectivePortalId(portalId); - var cacheKey = string.Format(DataCache.UserLookupCacheKey, masterPortalId); - return CBO.GetCachedObject>( - new CacheItemArgs(cacheKey, DataCache.UserLookupCacheTimeOut, - DataCache.UserLookupCachePriority), (c) => new SharedDictionary(), true); + return GetUserById(portalId, userId); } internal static Hashtable GetUserSettings(int portalId, Hashtable settings) @@ -445,6 +325,170 @@ internal static Hashtable GetUserSettings(int portalId, Hashtable settings) return settings; } + protected override Func GetFactory() + { + return () => new UserController(); + } + + private static void AddEventLog(int portalId, string username, int userId, string portalName, string ip, UserLoginStatus loginStatus) + { + // initialize log record + var objSecurity = PortalSecurity.Instance; + var log = new LogInfo + { + LogTypeKey = loginStatus.ToString(), + LogPortalID = portalId, + LogPortalName = portalName, + LogUserName = objSecurity.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup), + LogUserID = userId, + }; + log.AddProperty("IP", ip); + + // create log record + LogController.Instance.AddLog(log); + } + + private static void AutoAssignUsersToPortalRoles(UserInfo user, int portalId) + { + foreach (var role in RoleController.Instance.GetRoles(portalId, role => role.AutoAssignment && role.Status == RoleStatus.Approved)) + { + RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + + // Clear the roles cache - so the usercount is correct + RoleController.Instance.ClearRoleCache(portalId); + } + + private static void AutoAssignUsersToRoles(UserInfo user, int portalId) + { + var thisPortal = PortalController.Instance.GetPortal(portalId); + + if (IsMemberOfPortalGroup(portalId)) + { + foreach (var portal in PortalGroupController.Instance.GetPortalsByGroup(thisPortal.PortalGroupID)) + { + if (!user.Membership.Approved && portal.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) + { + var role = RoleController.Instance.GetRole(portal.PortalID, r => r.RoleName == "Unverified Users"); + RoleController.Instance.AddUserRole(portal.PortalID, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + else + { + AutoAssignUsersToPortalRoles(user, portal.PortalID); + } + } + } + else + { + if (!user.Membership.Approved && thisPortal.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) + { + var role = RoleController.Instance.GetRole(portalId, r => r.RoleName == "Unverified Users"); + RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + else + { + AutoAssignUsersToPortalRoles(user, portalId); + } + } + } + + // TODO - Handle Portal Groups + private static void DeleteUserPermissions(UserInfo user) + { + FolderPermissionController.DeleteFolderPermissionsByUser(user); + + // Delete Module Permissions + ModulePermissionController.DeleteModulePermissionsByUser(user); + + // Delete Tab Permissions + TabPermissionController.DeleteTabPermissionsByUser(user); + } + + private static void RestoreUserPermissions(UserInfo user) + { + // restore user's folder permission + var userFolderPath = ((PathUtils)PathUtils.Instance).GetUserFolderPathInternal(user); + var portalId = user.IsSuperUser ? Null.NullInteger : user.PortalID; + var userFolder = FolderManager.Instance.GetFolder(portalId, userFolderPath); + + if (userFolder != null) + { + foreach (PermissionInfo permission in PermissionController.GetPermissionsByFolder()) + { + if (permission.PermissionKey.Equals("READ", StringComparison.OrdinalIgnoreCase) + || permission.PermissionKey.Equals("WRITE", StringComparison.OrdinalIgnoreCase) + || permission.PermissionKey.Equals("BROWSE", StringComparison.OrdinalIgnoreCase)) + { + var folderPermission = new FolderPermissionInfo(permission) + { + FolderID = userFolder.FolderID, + UserID = user.UserID, + RoleID = int.Parse(Globals.glbRoleNothing), + AllowAccess = true, + }; + + userFolder.FolderPermissions.Add(folderPermission, true); + } + } + + FolderPermissionController.SaveFolderPermissions((FolderInfo)userFolder); + } + } + + private static void FixMemberPortalId(UserInfo user, int portalId) + { + if (user != null) + { + user.PortalID = portalId; + } + } + + private static UserInfo GetCurrentUserInternal() + { + UserInfo user; + if (HttpContext.Current == null) + { + if (!Thread.CurrentPrincipal.Identity.IsAuthenticated) + { + return new UserInfo(); + } + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (portalSettings != null) + { + user = GetCachedUser(portalSettings.PortalId, Thread.CurrentPrincipal.Identity.Name); + return user ?? new UserInfo(); + } + + return new UserInfo(); + } + + user = (UserInfo)HttpContext.Current.Items["UserInfo"]; + return user ?? new UserInfo(); + } + + private static int GetEffectivePortalId(int portalId) + { + return PortalController.GetEffectivePortalId(portalId); + } + + private static object GetUserCountByPortalCallBack(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + var portalUserCount = MembershipProvider.Instance().GetUserCountByPortal(portalId); + DataCache.SetCache(cacheItemArgs.CacheKey, portalUserCount); + return portalUserCount; + } + + private static SharedDictionary GetUserLookupDictionary(int portalId) + { + var masterPortalId = GetEffectivePortalId(portalId); + var cacheKey = string.Format(DataCache.UserLookupCacheKey, masterPortalId); + return CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, DataCache.UserLookupCacheTimeOut, + DataCache.UserLookupCachePriority), (c) => new SharedDictionary(), true); + } + private static bool IsMemberOfPortalGroup(int portalId) { return PortalController.IsMemberOfPortalGroup(portalId); @@ -493,42 +537,22 @@ private static void SendDeleteEmailNotifications(UserInfo user, PortalSettings p user.Profile.PreferredLocale, portalSettings, "EMAIL_USER_UNREGISTER_SUBJECT", - user, - Localization.GlobalResourceFile, - null, - string.Empty, - portalSettings.AdministratorId); - message.Body = Localization.GetSystemMessage( - user.Profile.PreferredLocale, - portalSettings, - "EMAIL_USER_UNREGISTER_BODY", - user, - Localization.GlobalResourceFile, - null, - string.Empty, - portalSettings.AdministratorId); - message.Status = MessageStatusType.Unread; - Mail.SendEmail(portalSettings.Email, portalSettings.Email, message.Subject, message.Body); - } - - UserInfo IUserController.GetCurrentUserInfo() - { - return GetCurrentUserInternal(); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetUser retrieves a User from the DataStore. - /// - /// - /// - /// The Id of the Portal. - /// The Id of the user being retrieved from the Data Store. - /// The User as a UserInfo object. - /// ----------------------------------------------------------------------------- - public UserInfo GetUser(int portalId, int userId) - { - return GetUserById(portalId, userId); + user, + Localization.GlobalResourceFile, + null, + string.Empty, + portalSettings.AdministratorId); + message.Body = Localization.GetSystemMessage( + user.Profile.PreferredLocale, + portalSettings, + "EMAIL_USER_UNREGISTER_BODY", + user, + Localization.GlobalResourceFile, + null, + string.Empty, + portalSettings.AdministratorId); + message.Status = MessageStatusType.Unread; + Mail.SendEmail(portalSettings.Email, portalSettings.Email, message.Subject, message.Body); } public UserInfo GetUserByDisplayname(int portalId, string displayName) @@ -604,6 +628,23 @@ public string GetUserProfilePictureUrl(int portalId, int userId, int width, int : Globals.ApplicationPath + childPortalAlias + url + cdv; } + /// ----------------------------------------------------------------------------- + /// + /// Update all the Users Display Names. + /// + /// ----------------------------------------------------------------------------- + public void UpdateDisplayNames() + { + int portalId = GetEffectivePortalId(this.PortalId); + + var arrUsers = GetUsers(this.PortalId); + foreach (UserInfo objUser in arrUsers) + { + objUser.UpdateDisplayName(this.DisplayFormat); + UpdateUser(portalId, objUser); + } + } + private static string GetChildPortalAlias() { var settings = PortalController.Instance.GetCurrentPortalSettings(); @@ -662,47 +703,6 @@ private static string GetProfilePictureCdv(int portalId, int userId) return cdv; } - /// ----------------------------------------------------------------------------- - /// - /// Update all the Users Display Names. - /// - /// ----------------------------------------------------------------------------- - public void UpdateDisplayNames() - { - int portalId = GetEffectivePortalId(this.PortalId); - - var arrUsers = GetUsers(this.PortalId); - foreach (UserInfo objUser in arrUsers) - { - objUser.UpdateDisplayName(this.DisplayFormat); - UpdateUser(portalId, objUser); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the number count for all duplicate e-mail adresses in the database. - /// - /// - /// ----------------------------------------------------------------------------- - public static int GetDuplicateEmailCount() - { - return DataProvider.Instance().GetDuplicateEmailCount(PortalSettings.Current.PortalId); - } - - /// - /// add new userportal record (used for creating sites with existing user). - /// - /// portalid. - /// userid. - public static void AddUserPortal(int portalId, int userId) - { - Requires.NotNullOrEmpty("portalId", portalId.ToString()); - Requires.NotNullOrEmpty("userId", userId.ToString()); - - MembershipProvider.Instance().AddUserPortal(portalId, userId); - } - /// /// ApproveUser removes the Unverified Users role from the user and adds the auto assigned roles. /// @@ -1851,6 +1851,36 @@ public static bool RemoveUser(UserInfo user) return retValue; } + /// + /// reset and change password + /// used by admin/host users who do not need to supply an "old" password. + /// + /// user being changed. + /// new password. + /// + public static bool ResetAndChangePassword(UserInfo user, string newPassword) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (GetCurrentUserInternal().IsInRole(portalSettings.AdministratorRoleName)) + { + string resetPassword = ResetPassword(user, string.Empty); + return ChangePassword(user, resetPassword, newPassword); + } + + return false; + } + + public static bool ResetAndChangePassword(UserInfo user, string oldPassword, string newPassword) + { + if (System.Web.Security.Membership.ValidateUser(user.Username, oldPassword)) + { + string resetPassword = ResetPassword(user, string.Empty); + return ChangePassword(user, resetPassword, newPassword); + } + + return false; + } + /// /// Delete the contents and folder that belongs to a user in a specific portal. /// @@ -1891,36 +1921,6 @@ private static void DeleteUserFolder(UserInfo user) } } - /// - /// reset and change password - /// used by admin/host users who do not need to supply an "old" password. - /// - /// user being changed. - /// new password. - /// - public static bool ResetAndChangePassword(UserInfo user, string newPassword) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (GetCurrentUserInternal().IsInRole(portalSettings.AdministratorRoleName)) - { - string resetPassword = ResetPassword(user, string.Empty); - return ChangePassword(user, resetPassword, newPassword); - } - - return false; - } - - public static bool ResetAndChangePassword(UserInfo user, string oldPassword, string newPassword) - { - if (System.Web.Security.Membership.ValidateUser(user.Username, oldPassword)) - { - string resetPassword = ResetPassword(user, string.Empty); - return ChangePassword(user, resetPassword, newPassword); - } - - return false; - } - /// ----------------------------------------------------------------------------- /// /// Resets the password for the specified user. @@ -2079,67 +2079,6 @@ public static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bo UpdateUser(portalId, user, loggedAction, sendNotification, true); } - /// ----------------------------------------------------------------------------- - /// - /// updates a user. - /// - /// the portalid 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 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. - /// - internal static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bool sendNotification, bool clearCache) - { - var originalPortalId = user.PortalID; - portalId = GetEffectivePortalId(portalId); - user.PortalID = portalId; - - // clear the cache so that can get original info from database. - DataCache.RemoveCache(string.Format(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. - - // Update the User - MembershipProvider.Instance().UpdateUser(user); - if (loggedAction) - { - // if the httpcontext is null, then get portal settings by portal id. - PortalSettings portalSettings = null; - if (HttpContext.Current != null) - { - portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - } - else if (portalId > Null.NullInteger) - { - portalSettings = new PortalSettings(portalId); - } - - EventLogController.Instance.AddLog(user, portalSettings, GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_UPDATED); - } - - EventManager.Instance.OnUserUpdated(new UpdateUserEventArgs { User = user, OldUser = oldUser }); - - // Reset PortalId - FixMemberPortalId(user, originalPortalId); - - // Remove the UserInfo from the Cache, as it has been modified - if (clearCache) - { - DataCache.ClearUserCache(portalId, user.Username); - } - - if (!user.Membership.Approving) - { - return; - } - - user.Membership.ConfirmApproved(); - EventManager.Instance.OnUserApproved(new UserEventArgs { User = user }); - } - /// ----------------------------------------------------------------------------- /// /// Validates a User's credentials against the Data Store, and sets the Forms Authentication @@ -2209,6 +2148,67 @@ public static void UserLogin(int portalId, UserInfo user, string portalName, str EventManager.Instance.OnUserAuthenticated(new UserEventArgs { User = user }); } + /// ----------------------------------------------------------------------------- + /// + /// updates a user. + /// + /// the portalid 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 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. + /// + internal static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bool sendNotification, bool clearCache) + { + var originalPortalId = user.PortalID; + portalId = GetEffectivePortalId(portalId); + user.PortalID = portalId; + + // clear the cache so that can get original info from database. + DataCache.RemoveCache(string.Format(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. + + // Update the User + MembershipProvider.Instance().UpdateUser(user); + if (loggedAction) + { + // if the httpcontext is null, then get portal settings by portal id. + PortalSettings portalSettings = null; + if (HttpContext.Current != null) + { + portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + } + else if (portalId > Null.NullInteger) + { + portalSettings = new PortalSettings(portalId); + } + + EventLogController.Instance.AddLog(user, portalSettings, GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_UPDATED); + } + + EventManager.Instance.OnUserUpdated(new UpdateUserEventArgs { User = user, OldUser = oldUser }); + + // Reset PortalId + FixMemberPortalId(user, originalPortalId); + + // Remove the UserInfo from the Cache, as it has been modified + if (clearCache) + { + DataCache.ClearUserCache(portalId, user.Username); + } + + if (!user.Membership.Approving) + { + return; + } + + user.Membership.ConfirmApproved(); + EventManager.Instance.OnUserApproved(new UserEventArgs { User = user }); + } + /// ----------------------------------------------------------------------------- /// /// Validates a Password. diff --git a/DNN Platform/Library/Entities/Users/UserInfo.cs b/DNN Platform/Library/Entities/Users/UserInfo.cs index a08ed6bc41d..b79d46ef03f 100644 --- a/DNN Platform/Library/Entities/Users/UserInfo.cs +++ b/DNN Platform/Library/Entities/Users/UserInfo.cs @@ -293,6 +293,15 @@ public UserSocial Social public string Username { get; set; } public string VanityUrl { get; set; } + + [Browsable(false)] + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } /// /// Property access, initially provided for TokenReplace. @@ -426,41 +435,6 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return string.Empty; } - - [Browsable(false)] - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } - - /// - /// Determine, if accessing user is Administrator. - /// - /// userinfo of the user to query. - /// true, if user is portal administrator or superuser. - private bool isAdminUser(ref UserInfo accessingUser) - { - if (accessingUser == null || accessingUser.UserID == -1) - { - return false; - } - - if (string.IsNullOrEmpty(this._administratorRoleName)) - { - PortalInfo ps = PortalController.Instance.GetPortal(accessingUser.PortalID); - this._administratorRoleName = ps.AdministratorRoleName; - } - - return accessingUser.IsInRole(this._administratorRoleName) || accessingUser.IsSuperUser; - } - - private string GetMembershipUserId() - { - return MembershipProvider.Instance().GetProviderUserKey(this)?.Replace("-", string.Empty) ?? string.Empty; - } /// ----------------------------------------------------------------------------- /// @@ -511,6 +485,32 @@ public DateTime LocalTime() { return this.LocalTime(DateUtils.GetDatabaseUtcTime()); } + + /// + /// Determine, if accessing user is Administrator. + /// + /// userinfo of the user to query. + /// true, if user is portal administrator or superuser. + private bool isAdminUser(ref UserInfo accessingUser) + { + if (accessingUser == null || accessingUser.UserID == -1) + { + return false; + } + + if (string.IsNullOrEmpty(this._administratorRoleName)) + { + PortalInfo ps = PortalController.Instance.GetPortal(accessingUser.PortalID); + this._administratorRoleName = ps.AdministratorRoleName; + } + + return accessingUser.IsInRole(this._administratorRoleName) || accessingUser.IsSuperUser; + } + + private string GetMembershipUserId() + { + return MembershipProvider.Instance().GetProviderUserKey(this)?.Replace("-", string.Empty) ?? string.Empty; + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs b/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs index 36974453e14..a7361bf83c0 100644 --- a/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs +++ b/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs @@ -15,11 +15,11 @@ namespace DotNetNuke.Entities.Users public class UserRegistrationEmailNotifier { - private static UserInfo CurrentUser => UserController.Instance.GetCurrentUserInfo(); - public UserRegistrationEmailNotifier() { } + + private static UserInfo CurrentUser => UserController.Instance.GetCurrentUserInfo(); public static void NotifyAdministrator(UserInfo user) { diff --git a/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs b/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs index 4983dd401a3..910ba317b1a 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs @@ -38,27 +38,6 @@ public PurgeUsersOnline(ScheduleHistoryItem objScheduleHistoryItem) this.ScheduleHistoryItem = objScheduleHistoryItem; } - /// ----------------------------------------------------------------------------- - /// - /// UpdateUsersOnline updates the Users Online information. - /// - /// ----------------------------------------------------------------------------- - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - private void UpdateUsersOnline() - { - var objUserOnlineController = new UserOnlineController(); - - // Is Users Online Enabled? - if (objUserOnlineController.IsEnabled()) - { - // Update the Users Online records from Cache - this.Status = "Updating Users Online"; - objUserOnlineController.UpdateUsersOnline(); - this.Status = "Update Users Online Successfully"; - this.ScheduleHistoryItem.Succeeded = true; - } - } - /// ----------------------------------------------------------------------------- /// /// DoWork does th4 Scheduler work. @@ -87,5 +66,26 @@ public override void DoWork() Exceptions.LogException(exc); } } + + /// ----------------------------------------------------------------------------- + /// + /// UpdateUsersOnline updates the Users Online information. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + private void UpdateUsersOnline() + { + var objUserOnlineController = new UserOnlineController(); + + // Is Users Online Enabled? + if (objUserOnlineController.IsEnabled()) + { + // Update the Users Online records from Cache + this.Status = "Updating Users Online"; + objUserOnlineController.UpdateUsersOnline(); + this.Status = "Update Users Online Successfully"; + this.ScheduleHistoryItem.Succeeded = true; + } + } } } diff --git a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs index 7b836775742..c1ea8093a47 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs @@ -124,6 +124,67 @@ public void SetUserList(Hashtable userList) DataCache.SetCache(CacheKey, userList); } + /// ----------------------------------------------------------------------------- + /// + /// Tracks an online User. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + public void TrackUsers() + { + HttpContext context = HttpContext.Current; + + // Have we already done the work for this request? + if (context.Items["CheckedUsersOnlineCookie"] != null) + { + return; + } + else + { + context.Items["CheckedUsersOnlineCookie"] = "true"; + } + + if (context.Request.IsAuthenticated) + { + this.TrackAuthenticatedUser(context); + } + else if (context.Request.Browser.Cookies) + { + this.TrackAnonymousUser(context); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Update the Users Online information. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + public void UpdateUsersOnline() + { + // Get a Current User List + Hashtable userList = this.GetUserList(); + + // Create a shallow copy of the list to Process + var listToProcess = (Hashtable)userList.Clone(); + + // Clear the list + this.ClearUserList(); + + // Persist the current User List + try + { + memberProvider.UpdateUsersOnline(listToProcess); + } + catch (Exception exc) + { + Logger.Error(exc); + } + + // Remove users that have expired + memberProvider.DeleteUsersOnline(this.GetOnlineTimeWindow()); + } + /// ----------------------------------------------------------------------------- /// /// Tracks an Anonymous User. @@ -254,66 +315,5 @@ private void TrackAuthenticatedUser(HttpContext context) userList[objUserInfo.UserID.ToString()] = user; this.SetUserList(userList); } - - /// ----------------------------------------------------------------------------- - /// - /// Tracks an online User. - /// - /// ----------------------------------------------------------------------------- - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public void TrackUsers() - { - HttpContext context = HttpContext.Current; - - // Have we already done the work for this request? - if (context.Items["CheckedUsersOnlineCookie"] != null) - { - return; - } - else - { - context.Items["CheckedUsersOnlineCookie"] = "true"; - } - - if (context.Request.IsAuthenticated) - { - this.TrackAuthenticatedUser(context); - } - else if (context.Request.Browser.Cookies) - { - this.TrackAnonymousUser(context); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Update the Users Online information. - /// - /// ----------------------------------------------------------------------------- - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public void UpdateUsersOnline() - { - // Get a Current User List - Hashtable userList = this.GetUserList(); - - // Create a shallow copy of the list to Process - var listToProcess = (Hashtable)userList.Clone(); - - // Clear the list - this.ClearUserList(); - - // Persist the current User List - try - { - memberProvider.UpdateUsersOnline(listToProcess); - } - catch (Exception exc) - { - Logger.Error(exc); - } - - // Remove users that have expired - memberProvider.DeleteUsersOnline(this.GetOnlineTimeWindow()); - } } } diff --git a/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs index eb5109bc013..1bd6556f22a 100644 --- a/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs @@ -14,40 +14,6 @@ namespace DotNetNuke.ExtensionPoints [ToolboxData("<{0}:EditPagePanelExtensionControl runat=server>")] public class EditPagePanelExtensionControl : DefaultExtensionControl { - private void LoadControl(IEditPagePanelExtensionPoint extension) - { - var editPanel = new PanelEditPagePanelExtensionControl { PanelId = extension.EditPagePanelId, Text = extension.Text, CssClass = extension.CssClass }; - var control = this.Page.LoadControl(extension.UserControlSrc); - control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); - editPanel.Controls.Add(control); - this.Controls.Add(editPanel); - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - var extensionPointManager = new ExtensionPointManager(); - - if (!string.IsNullOrEmpty(this.Name)) - { - var extension = extensionPointManager.GetEditPagePanelExtensionPointFirstByPriority(this.Module, this.Name); - if (extension != null) - { - this.LoadControl(extension); - } - } - else - { - foreach (var extension in extensionPointManager.GetEditPagePanelExtensionPoints(this.Module, this.Group)) - { - if (extension != null) - { - this.LoadControl(extension); - } - } - } - } - public void BindAction(int portalId, int tabId, int moduleId) { foreach (var control in this.Controls) @@ -85,6 +51,40 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + var extensionPointManager = new ExtensionPointManager(); + + if (!string.IsNullOrEmpty(this.Name)) + { + var extension = extensionPointManager.GetEditPagePanelExtensionPointFirstByPriority(this.Module, this.Name); + if (extension != null) + { + this.LoadControl(extension); + } + } + else + { + foreach (var extension in extensionPointManager.GetEditPagePanelExtensionPoints(this.Module, this.Group)) + { + if (extension != null) + { + this.LoadControl(extension); + } + } + } + } + + private void LoadControl(IEditPagePanelExtensionPoint extension) + { + var editPanel = new PanelEditPagePanelExtensionControl { PanelId = extension.EditPagePanelId, Text = extension.Text, CssClass = extension.CssClass }; + var control = this.Page.LoadControl(extension.UserControlSrc); + control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); + editPanel.Controls.Add(control); + this.Controls.Add(editPanel); + } public void CancelAction(int portalId, int tabId, int moduleId) { diff --git a/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs index 2b6e44acbad..4bfb7c3ab98 100644 --- a/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs @@ -47,33 +47,6 @@ public string PanelControlId } } - protected override void OnInit(EventArgs e) - { - var extensionPointManager = new ExtensionPointManager(); - - var tabs = (HtmlGenericControl)this.Parent.FindControl(this.TabControlId); - var panel = this.Parent.FindControl(this.PanelControlId); - - foreach (var extension in extensionPointManager.GetEditPageTabExtensionPoints(this.Module, this.Group)) - { - if (extension.Visible) - { - var liElement = new HtmlGenericControl("li") - { - InnerHtml = "" + extension.Text + "", - }; - liElement.Attributes.Add("class", extension.CssClass); - tabs.Controls.Add(liElement); - - var container = new PanelTabExtensionControl { PanelId = extension.EditPageTabId }; - var control = this.Page.LoadControl(extension.UserControlSrc); - control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); - container.Controls.Add(control); - panel.Controls.Add(container); - } - } - } - public void BindAction(int portalId, int tabId, int moduleId) { var panel = this.Parent.FindControl(this.PanelControlId); @@ -116,6 +89,33 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } + protected override void OnInit(EventArgs e) + { + var extensionPointManager = new ExtensionPointManager(); + + var tabs = (HtmlGenericControl)this.Parent.FindControl(this.TabControlId); + var panel = this.Parent.FindControl(this.PanelControlId); + + foreach (var extension in extensionPointManager.GetEditPageTabExtensionPoints(this.Module, this.Group)) + { + if (extension.Visible) + { + var liElement = new HtmlGenericControl("li") + { + InnerHtml = "" + extension.Text + "", + }; + liElement.Attributes.Add("class", extension.CssClass); + tabs.Controls.Add(liElement); + + var container = new PanelTabExtensionControl { PanelId = extension.EditPageTabId }; + var control = this.Page.LoadControl(extension.UserControlSrc); + control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); + container.Controls.Add(control); + panel.Controls.Add(container); + } + } + } + public void CancelAction(int portalId, int tabId, int moduleId) { var panel = this.Parent.FindControl(this.PanelControlId); diff --git a/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs b/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs index a554f457138..193e0b8c1f3 100644 --- a/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs +++ b/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs @@ -18,6 +18,8 @@ public class ExtensionPointManager { private static readonly object SyncRoot = new object(); + private static readonly CompositionContainer MefCompositionContainer = InitializeMefCompositionContainer(); + #pragma warning disable 649 [ImportMany] @@ -51,16 +53,6 @@ public ExtensionPointManager() ComposeParts(this); } - private static readonly CompositionContainer MefCompositionContainer = InitializeMefCompositionContainer(); - - private static CompositionContainer InitializeMefCompositionContainer() - { - var catalog = new AggregateCatalog(); - var path = Path.Combine(Globals.ApplicationMapPath, "bin"); - catalog.Catalogs.Add(new SafeDirectoryCatalog(path)); - return new CompositionContainer(catalog, true); - } - public static void ComposeParts(params object[] attributeParts) { lock (SyncRoot) @@ -74,6 +66,14 @@ public IEnumerable GetEditPageTabExtensionPoints(str return this.GetEditPageTabExtensionPoints(module, null); } + private static CompositionContainer InitializeMefCompositionContainer() + { + var catalog = new AggregateCatalog(); + var path = Path.Combine(Globals.ApplicationMapPath, "bin"); + catalog.Catalogs.Add(new SafeDirectoryCatalog(path)); + return new CompositionContainer(catalog, true); + } + public IEnumerable GetEditPageTabExtensionPoints(string module, string group) { return from e in this._editPageTabExtensionPoint @@ -116,11 +116,11 @@ public IEnumerable GetScriptItemExtensionPoints(strin public IEnumerable GetScriptItemExtensionPoints(string module, string group) { - return from e in this._scripts - where e.Metadata.Module == module - && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) - orderby e.Value.Order - select e.Value; + return from e in this._scripts + where e.Metadata.Module == module + && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) + orderby e.Value.Order + select e.Value; } public IEnumerable GetEditPagePanelExtensionPoints(string module) @@ -169,10 +169,10 @@ orderby e.Metadata.Priority public IEnumerable GetUserControlExtensionPoints(string module, string group) { - return from e in this._userControlExtensionPoints - where e.Metadata.Module == module && e.Metadata.Group == @group - orderby e.Value.Order - select e.Value; + return from e in this._userControlExtensionPoints + where e.Metadata.Module == module && e.Metadata.Group == @group + orderby e.Value.Order + select e.Value; } public IEnumerable GetMenuItemExtensionPoints(string module) diff --git a/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs index a87bfea16ac..9a0606a89e7 100644 --- a/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs @@ -13,32 +13,6 @@ namespace DotNetNuke.ExtensionPoints [ToolboxData("<{0}:UserControlExtensionControl runat=server>")] public class UserControlExtensionControl : DefaultExtensionControl { - private void LoadControl(IUserControlExtensionPoint extension) - { - var control = this.Page.LoadControl(extension.UserControlSrc); - control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); - this.Controls.Add(control); - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - var extensionPointManager = new ExtensionPointManager(); - - if (!string.IsNullOrEmpty(this.Name)) - { - var extension = extensionPointManager.GetUserControlExtensionPointFirstByPriority(this.Module, this.Name); - this.LoadControl(extension); - } - else - { - foreach (var extension in extensionPointManager.GetUserControlExtensionPoints(this.Module, this.Group)) - { - this.LoadControl(extension); - } - } - } - public void BindAction(int portalId, int tabId, int moduleId) { foreach (var control in this.Controls) @@ -62,6 +36,32 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + var extensionPointManager = new ExtensionPointManager(); + + if (!string.IsNullOrEmpty(this.Name)) + { + var extension = extensionPointManager.GetUserControlExtensionPointFirstByPriority(this.Module, this.Name); + this.LoadControl(extension); + } + else + { + foreach (var extension in extensionPointManager.GetUserControlExtensionPoints(this.Module, this.Group)) + { + this.LoadControl(extension); + } + } + } + + private void LoadControl(IUserControlExtensionPoint extension) + { + var control = this.Page.LoadControl(extension.UserControlSrc); + control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc); + this.Controls.Add(control); + } public void CancelAction(int portalId, int tabId, int moduleId) { diff --git a/DNN Platform/Library/Framework/AJAX.cs b/DNN Platform/Library/Framework/AJAX.cs index c89b6d41fa9..4ded65c023a 100644 --- a/DNN Platform/Library/Framework/AJAX.cs +++ b/DNN Platform/Library/Framework/AJAX.cs @@ -37,12 +37,12 @@ public static void AddScriptManager(Page page, bool checkCdn) { try { - using (var scriptManager = new ScriptManager // RadScriptManager - { - ID = "ScriptManager", - EnableScriptGlobalization = true, - SupportsPartialRendering = true, - }) + using (var scriptManager = new ScriptManager // RadScriptManager + { + ID = "ScriptManager", + EnableScriptGlobalization = true, + SupportsPartialRendering = true, + }) { if (checkCdn) { @@ -92,11 +92,11 @@ public static void AddScriptManager(Page page, bool checkCdn) } } } - } - - /// Gets the current ScriptManager on the page. - /// the page instance. - /// The ScriptManager instance, or null. + } + + /// Gets the current ScriptManager on the page. + /// the page instance. + /// The ScriptManager instance, or null. public static ScriptManager GetScriptManager(Page objPage) { return objPage.FindControl("ScriptManager") as ScriptManager; diff --git a/DNN Platform/Library/Framework/BaseHttpHandler.cs b/DNN Platform/Library/Framework/BaseHttpHandler.cs index 2151845b952..b2e8a2fbe3b 100644 --- a/DNN Platform/Library/Framework/BaseHttpHandler.cs +++ b/DNN Platform/Library/Framework/BaseHttpHandler.cs @@ -125,6 +125,14 @@ public virtual Encoding ContentEncoding return Encoding.UTF8; } } + + public virtual bool IsReusable + { + get + { + return true; + } + } /// /// Processs the incoming HTTP request. @@ -153,14 +161,6 @@ public void ProcessRequest(HttpContext context) this.HandleRequest(); } - - public virtual bool IsReusable - { - get - { - return true; - } - } /// /// Handles the request. This is where you put your diff --git a/DNN Platform/Library/Framework/CDefault.cs b/DNN Platform/Library/Framework/CDefault.cs index af8ae38d387..5d986eeaa23 100644 --- a/DNN Platform/Library/Framework/CDefault.cs +++ b/DNN Platform/Library/Framework/CDefault.cs @@ -31,14 +31,25 @@ public class CDefault : PageBase private static readonly object InstallerFilesRemovedLock = new object(); - protected override void RegisterAjaxScript() + protected string AdvancedSettingsPageUrl { - if (this.Page.Form != null) + get { - if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired) + string result; + var tab = TabController.Instance.GetTabByName("Advanced Settings", this.PortalSettings.PortalId); + var modules = ModuleController.Instance.GetTabModules(tab.TabID).Values; + + if (modules.Count > 0) { - ServicesFrameworkInternal.Instance.RegisterAjaxScript(this.Page); + var pmb = new PortalModuleBase(); + result = pmb.EditUrl(tab.TabID, string.Empty, false, string.Concat("mid=", modules.ElementAt(0).ModuleID), "popUp=true", string.Concat("ReturnUrl=", this.Server.UrlEncode(TestableGlobals.Instance.NavigateURL()))); } + else + { + result = TestableGlobals.Instance.NavigateURL(tab.TabID); + } + + return result; } } @@ -58,6 +69,17 @@ public void ScrollToControl(Control objControl) } } + protected override void RegisterAjaxScript() + { + if (this.Page.Form != null) + { + if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired) + { + ServicesFrameworkInternal.Instance.RegisterAjaxScript(this.Page); + } + } + } + protected void ManageInstallerFiles() { if (!HostController.Instance.GetBoolean("InstallerFilesRemoved")) @@ -72,27 +94,5 @@ protected void ManageInstallerFiles() } } } - - protected string AdvancedSettingsPageUrl - { - get - { - string result; - var tab = TabController.Instance.GetTabByName("Advanced Settings", this.PortalSettings.PortalId); - var modules = ModuleController.Instance.GetTabModules(tab.TabID).Values; - - if (modules.Count > 0) - { - var pmb = new PortalModuleBase(); - result = pmb.EditUrl(tab.TabID, string.Empty, false, string.Concat("mid=", modules.ElementAt(0).ModuleID), "popUp=true", string.Concat("ReturnUrl=", this.Server.UrlEncode(TestableGlobals.Instance.NavigateURL()))); - } - else - { - result = TestableGlobals.Instance.NavigateURL(tab.TabID); - } - - return result; - } - } } } diff --git a/DNN Platform/Library/Framework/IServiceFrameworkInternals.cs b/DNN Platform/Library/Framework/IServiceFrameworkInternals.cs index c9830d2e9f6..67e96aed4e8 100644 --- a/DNN Platform/Library/Framework/IServiceFrameworkInternals.cs +++ b/DNN Platform/Library/Framework/IServiceFrameworkInternals.cs @@ -11,10 +11,10 @@ internal interface IServiceFrameworkInternals { bool IsAjaxAntiForgerySupportRequired { get; } - void RegisterAjaxAntiForgery(Page page); - bool IsAjaxScriptSupportRequired { get; } + void RegisterAjaxAntiForgery(Page page); + void RegisterAjaxScript(Page page); } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs index 76d375d71f1..7bbe86f8ebe 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs @@ -32,6 +32,13 @@ public class JavaScript private const string ScriptPrefix = "JSL."; private const string LegacyPrefix = "LEGACY."; + private const string jQueryUIDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.js"; + private const string jQueryUIMinFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.min.js"; + + protected JavaScript() + { + } + /// /// checks whether the script file is a known javascript library. /// @@ -150,8 +157,15 @@ public static void Register(Page page) } } - protected JavaScript() + public static string JQueryUIFile(bool getMinFile) { + string jfile = jQueryUIDebugFile; + if (getMinFile) + { + jfile = jQueryUIMinFile; + } + + return jfile; } private static void RequestHighestVersionLibraryRegistration(string jsname) @@ -550,20 +564,6 @@ where item.ToString().StartsWith(LegacyPrefix) #pragma warning restore 618 } - private const string jQueryUIDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.js"; - private const string jQueryUIMinFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.min.js"; - - public static string JQueryUIFile(bool getMinFile) - { - string jfile = jQueryUIDebugFile; - if (getMinFile) - { - jfile = jQueryUIMinFile; - } - - return jfile; - } - public static string GetJQueryScriptReference() { #pragma warning disable 618 diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs index ae37a00cec0..154603fba3d 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs @@ -15,16 +15,6 @@ public class JavaScriptLibraryController : ServiceLocator, IJavaScriptLibraryController { - private void ClearCache() - { - DataCache.RemoveCache(DataCache.JavaScriptLibrariesCacheKey); - } - - protected override Func GetFactory() - { - return () => new JavaScriptLibraryController(); - } - /// Delete the library reference from the database. /// Library to be deleted. public void DeleteLibrary(JavaScriptLibrary library) @@ -43,6 +33,16 @@ public JavaScriptLibrary GetLibrary(Func predicate) { return this.GetLibraries(predicate).OrderByDescending(l => l.Version).FirstOrDefault(); } + + protected override Func GetFactory() + { + return () => new JavaScriptLibraryController(); + } + + private void ClearCache() + { + DataCache.RemoveCache(DataCache.JavaScriptLibrariesCacheKey); + } /// Gets all of the instances matching the given . /// A function used to filter the library. @@ -58,13 +58,13 @@ public IEnumerable GetLibraries(Func /// Gets all of the instances. /// A sequence of instances. public IEnumerable GetLibraries() - { - return CBO.GetCachedObject>( - new CacheItemArgs( - DataCache.JavaScriptLibrariesCacheKey, - DataCache.JavaScriptLibrariesCacheTimeout, - DataCache.JavaScriptLibrariesCachePriority), - c => CBO.FillCollection(DataProvider.Instance().ExecuteReader("GetJavaScriptLibraries"))); + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.JavaScriptLibrariesCacheKey, + DataCache.JavaScriptLibrariesCacheTimeout, + DataCache.JavaScriptLibrariesCachePriority), + c => CBO.FillCollection(DataProvider.Instance().ExecuteReader("GetJavaScriptLibraries"))); } /// Save a library to the database. diff --git a/DNN Platform/Library/Framework/PageBase.cs b/DNN Platform/Library/Framework/PageBase.cs index a58f51c59d1..cdc6719d6ae 100644 --- a/DNN Platform/Library/Framework/PageBase.cs +++ b/DNN Platform/Library/Framework/PageBase.cs @@ -38,11 +38,11 @@ namespace DotNetNuke.Framework /// ----------------------------------------------------------------------------- public abstract class PageBase : Page { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PageBase)); - private readonly ILog _tracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); - private const string LinkItemPattern = "<(a|link|img|script|input|form|object).[^>]*(href|src|action)=(\\\"|'|)(.[^\\\"']*)(\\\"|'|)[^>]*>"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PageBase)); private static readonly Regex LinkItemMatchRegex = new Regex(LinkItemPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); + private readonly ILog _tracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); private PageStatePersister _persister; private readonly NameValueCollection _htmlAttributes = new NameValueCollection(); @@ -61,6 +61,22 @@ protected PageBase() this._localizedControls = new ArrayList(); } + public PortalSettings PortalSettings + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } + } + + public NameValueCollection HtmlAttributes + { + get + { + return this._htmlAttributes; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets pageStatePersister returns an instance of the class that will be used to persist the Page State. @@ -93,22 +109,6 @@ protected override PageStatePersister PageStatePersister return this._persister; } } - - public PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - - public NameValueCollection HtmlAttributes - { - get - { - return this._htmlAttributes; - } - } public CultureInfo PageCulture { @@ -148,170 +148,28 @@ public string LocalResourceFile /// Gets a value indicating whether indicate whether http headers has been sent to client. /// public bool HeaderIsWritten { get; internal set; } - - private string GetErrorUrl(string url, Exception exc, bool hideContent = true) - { - if (this.Request.QueryString["error"] != null) - { - url += string.Concat(url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&", "error=terminate"); - } - else - { - url += string.Concat( - url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&", - "error=", - exc == null || UserController.Instance.GetCurrentUserInfo() == null || !UserController.Instance.GetCurrentUserInfo().IsSuperUser ? "An unexpected error has occurred" : this.Server.UrlEncode(exc.Message)); - if (!Globals.IsAdminControl() && hideContent) - { - url += "&content=0"; - } - } - - return url; - } - - private bool IsViewStateFailure(Exception e) - { - return !this.User.Identity.IsAuthenticated && e != null && e.InnerException is ViewStateException; - } - private void IterateControls(ControlCollection controls, ArrayList affectedControls, string resourceFileRoot) - { - foreach (Control c in controls) - { - this.ProcessControl(c, affectedControls, true, resourceFileRoot); - this.LogDnnTrace("PageBase.IterateControls", "Info", $"ControlId: {c.ID}"); - } - } - - private void LogDnnTrace(string origin, string action, string message) + /// + /// RemoveKeyAttribute remove the key attribute from the control. If this isn't done, then the HTML output will have + /// a bad attribute on it which could cause some older browsers problems. + /// + /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. + public static void RemoveKeyAttribute(ArrayList affectedControls) { - var tabId = -1; - if (this.PortalSettings?.ActiveTab != null) + if (affectedControls == null) { - tabId = this.PortalSettings.ActiveTab.TabID; + return; } - if (this._tracelLogger.IsDebugEnabled) - { - this._tracelLogger.Debug($"{origin} {action} (TabId:{tabId},{message})"); - } - } - - protected virtual void RegisterAjaxScript() - { - if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired) - { - ServicesFrameworkInternal.Instance.RegisterAjaxScript(this.Page); - } - } - - protected override void OnError(EventArgs e) - { - base.OnError(e); - Exception exc = this.Server.GetLastError(); - Logger.Fatal("An error has occurred while loading page.", exc); - - string strURL = Globals.ApplicationURL(); - if (exc is HttpException && !this.IsViewStateFailure(exc)) - { - try - { - // if the exception's status code set to 404, we need display 404 page if defined or show no found info. - var statusCode = (exc as HttpException).GetHttpCode(); - if (statusCode == 404) - { - UrlUtils.Handle404Exception(this.Response, this.PortalSettings); - } - - if (this.PortalSettings?.ErrorPage500 != -1) - { - var url = this.GetErrorUrl(string.Concat("~/Default.aspx?tabid=", this.PortalSettings.ErrorPage500), exc, - false); - HttpContext.Current.Response.Redirect(url); - } - else - { - HttpContext.Current.Response.Clear(); - HttpContext.Current.Server.Transfer("~/ErrorPage.aspx"); - } - } - catch (Exception) - { - HttpContext.Current.Response.Clear(); - var errorMessage = HttpUtility.UrlEncode(Localization.GetString("NoSitesForThisInstallation.Error", Localization.GlobalResourceFile)); - HttpContext.Current.Server.Transfer("~/ErrorPage.aspx?status=503&error=" + errorMessage); - } - } - - strURL = this.GetErrorUrl(strURL, exc); - Exceptions.ProcessPageLoadException(exc, strURL); - } - - protected override void OnInit(EventArgs e) - { - var isInstallPage = HttpContext.Current.Request.Url.LocalPath.ToLowerInvariant().Contains("installwizard.aspx"); - if (!isInstallPage) - { - Localization.SetThreadCultures(this.PageCulture, this.PortalSettings); - } - - if (ScriptManager.GetCurrent(this) == null) - { - AJAX.AddScriptManager(this, !isInstallPage); - } - - var dnncoreFilePath = HttpContext.Current.IsDebuggingEnabled - ? "~/js/Debug/dnncore.js" - : "~/js/dnncore.js"; - - ClientResourceManager.RegisterScript(this, dnncoreFilePath); - - base.OnInit(e); - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - // Because we have delayed registration of the jQuery script, - // Modules can override the standard behavior by including their own script on the page. - // The module must register the script with the "jQuery" key and should notify user - // of potential version conflicts with core jQuery support. - // if (jQuery.IsRequested) - // { - // jQuery.RegisterJQuery(Page); - // } - // if (jQuery.IsUIRequested) - // { - // jQuery.RegisterJQueryUI(Page); - // } - // if (jQuery.AreDnnPluginsRequested) - // { - // jQuery.RegisterDnnJQueryPlugins(Page); - // } - // if (jQuery.IsHoverIntentRequested) - // { - // jQuery.RegisterHoverIntent(Page); - // } - if (ServicesFrameworkInternal.Instance.IsAjaxAntiForgerySupportRequired) + int i; + for (i = 0; i <= affectedControls.Count - 1; i++) { - ServicesFrameworkInternal.Instance.RegisterAjaxAntiForgery(this.Page); + var ac = (AttributeCollection)affectedControls[i]; + ac.Remove(Localization.KeyName); + ac.Remove(IconController.IconKeyName); + ac.Remove(IconController.IconSizeName); + ac.Remove(IconController.IconStyleName); } - - this.RegisterAjaxScript(); - } - - protected override void Render(HtmlTextWriter writer) - { - this.LogDnnTrace("PageBase.Render", "Start", $"{this.Page.Request.Url.AbsoluteUri}"); - - this.IterateControls(this.Controls, this._localizedControls, this.LocalResourceFile); - RemoveKeyAttribute(this._localizedControls); - AJAX.RemoveScriptManager(this); - base.Render(writer); - - this.LogDnnTrace("PageBase.Render", "End", $"{this.Page.Request.Url.AbsoluteUri}"); } /// @@ -371,130 +229,34 @@ internal static string GetControlAttribute(Control control, ArrayList affectedCo return key; } - private void LocalizeControl(Control control, string value) + /// + /// ProcessControl peforms the high level localization for a single control and optionally it's children. + /// + /// Control to find the AttributeCollection on. + /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. + /// If true, causes this method to process children of this controls. + /// Root Resource File. + internal void ProcessControl(Control control, ArrayList affectedControls, bool includeChildren, string resourceFileRoot) { - if (string.IsNullOrEmpty(value)) + if (!control.Visible) { return; } - var validator = control as BaseValidator; - if (validator != null) - { - validator.ErrorMessage = value; - validator.Text = value; - return; - } - - var label = control as Label; - if (label != null) + // Perform the substitution if a key was found + var key = GetControlAttribute(control, affectedControls, Localization.KeyName); + if (!string.IsNullOrEmpty(key)) { - label.Text = value; - return; + // Translation starts here .... + var value = Localization.GetString(key, resourceFileRoot); + this.LocalizeControl(control, value); } - var linkButton = control as LinkButton; - if (linkButton != null) + // Translate listcontrol items here + var listControl = control as ListControl; + if (listControl != null) { - var imgMatches = LinkItemMatchRegex.Matches(value); - foreach (Match match in imgMatches) - { - if (match.Groups[match.Groups.Count - 2].Value.IndexOf("~", StringComparison.Ordinal) == -1) - { - continue; - } - - var resolvedUrl = this.Page.ResolveUrl(match.Groups[match.Groups.Count - 2].Value); - value = value.Replace(match.Groups[match.Groups.Count - 2].Value, resolvedUrl); - } - - linkButton.Text = value; - if (string.IsNullOrEmpty(linkButton.ToolTip)) - { - linkButton.ToolTip = value; - } - - return; - } - - var hyperLink = control as HyperLink; - if (hyperLink != null) - { - hyperLink.Text = value; - return; - } - - var button = control as Button; - if (button != null) - { - button.Text = value; - return; - } - - var htmlButton = control as HtmlButton; - if (htmlButton != null) - { - htmlButton.Attributes["Title"] = value; - return; - } - - var htmlImage = control as HtmlImage; - if (htmlImage != null) - { - htmlImage.Alt = value; - return; - } - - var checkBox = control as CheckBox; - if (checkBox != null) - { - checkBox.Text = value; - return; - } - - var image = control as Image; - if (image != null) - { - image.AlternateText = value; - image.ToolTip = value; - return; - } - - var textBox = control as TextBox; - if (textBox != null) - { - textBox.ToolTip = value; - } - } - - /// - /// ProcessControl peforms the high level localization for a single control and optionally it's children. - /// - /// Control to find the AttributeCollection on. - /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. - /// If true, causes this method to process children of this controls. - /// Root Resource File. - internal void ProcessControl(Control control, ArrayList affectedControls, bool includeChildren, string resourceFileRoot) - { - if (!control.Visible) - { - return; - } - - // Perform the substitution if a key was found - var key = GetControlAttribute(control, affectedControls, Localization.KeyName); - if (!string.IsNullOrEmpty(key)) - { - // Translation starts here .... - var value = Localization.GetString(key, resourceFileRoot); - this.LocalizeControl(control, value); - } - - // Translate listcontrol items here - var listControl = control as ListControl; - if (listControl != null) - { - for (var i = 0; i <= listControl.Items.Count - 1; i++) + for (var i = 0; i <= listControl.Items.Count - 1; i++) { var attributeCollection = listControl.Items[i].Attributes; key = attributeCollection[Localization.KeyName]; @@ -610,28 +372,266 @@ internal void ProcessControl(Control control, ArrayList affectedControls, bool i this.IterateControls(control.Controls, affectedControls, objModuleControl.LocalResourceFile); } } + + protected virtual void RegisterAjaxScript() + { + if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired) + { + ServicesFrameworkInternal.Instance.RegisterAjaxScript(this.Page); + } + } - /// - /// RemoveKeyAttribute remove the key attribute from the control. If this isn't done, then the HTML output will have - /// a bad attribute on it which could cause some older browsers problems. - /// - /// ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute. - public static void RemoveKeyAttribute(ArrayList affectedControls) + protected override void OnError(EventArgs e) { - if (affectedControls == null) + base.OnError(e); + Exception exc = this.Server.GetLastError(); + Logger.Fatal("An error has occurred while loading page.", exc); + + string strURL = Globals.ApplicationURL(); + if (exc is HttpException && !this.IsViewStateFailure(exc)) { - return; + try + { + // if the exception's status code set to 404, we need display 404 page if defined or show no found info. + var statusCode = (exc as HttpException).GetHttpCode(); + if (statusCode == 404) + { + UrlUtils.Handle404Exception(this.Response, this.PortalSettings); + } + + if (this.PortalSettings?.ErrorPage500 != -1) + { + var url = this.GetErrorUrl(string.Concat("~/Default.aspx?tabid=", this.PortalSettings.ErrorPage500), exc, + false); + HttpContext.Current.Response.Redirect(url); + } + else + { + HttpContext.Current.Response.Clear(); + HttpContext.Current.Server.Transfer("~/ErrorPage.aspx"); + } + } + catch (Exception) + { + HttpContext.Current.Response.Clear(); + var errorMessage = HttpUtility.UrlEncode(Localization.GetString("NoSitesForThisInstallation.Error", Localization.GlobalResourceFile)); + HttpContext.Current.Server.Transfer("~/ErrorPage.aspx?status=503&error=" + errorMessage); + } } + + strURL = this.GetErrorUrl(strURL, exc); + Exceptions.ProcessPageLoadException(exc, strURL); + } - int i; - for (i = 0; i <= affectedControls.Count - 1; i++) + private string GetErrorUrl(string url, Exception exc, bool hideContent = true) + { + if (this.Request.QueryString["error"] != null) { - var ac = (AttributeCollection)affectedControls[i]; - ac.Remove(Localization.KeyName); - ac.Remove(IconController.IconKeyName); - ac.Remove(IconController.IconSizeName); - ac.Remove(IconController.IconStyleName); + url += string.Concat(url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&", "error=terminate"); + } + else + { + url += string.Concat( + url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&", + "error=", + exc == null || UserController.Instance.GetCurrentUserInfo() == null || !UserController.Instance.GetCurrentUserInfo().IsSuperUser ? "An unexpected error has occurred" : this.Server.UrlEncode(exc.Message)); + if (!Globals.IsAdminControl() && hideContent) + { + url += "&content=0"; + } + } + + return url; + } + + private bool IsViewStateFailure(Exception e) + { + return !this.User.Identity.IsAuthenticated && e != null && e.InnerException is ViewStateException; + } + + private void IterateControls(ControlCollection controls, ArrayList affectedControls, string resourceFileRoot) + { + foreach (Control c in controls) + { + this.ProcessControl(c, affectedControls, true, resourceFileRoot); + this.LogDnnTrace("PageBase.IterateControls", "Info", $"ControlId: {c.ID}"); + } + } + + private void LogDnnTrace(string origin, string action, string message) + { + var tabId = -1; + if (this.PortalSettings?.ActiveTab != null) + { + tabId = this.PortalSettings.ActiveTab.TabID; } + + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"{origin} {action} (TabId:{tabId},{message})"); + } } + + protected override void OnInit(EventArgs e) + { + var isInstallPage = HttpContext.Current.Request.Url.LocalPath.ToLowerInvariant().Contains("installwizard.aspx"); + if (!isInstallPage) + { + Localization.SetThreadCultures(this.PageCulture, this.PortalSettings); + } + + if (ScriptManager.GetCurrent(this) == null) + { + AJAX.AddScriptManager(this, !isInstallPage); + } + + var dnncoreFilePath = HttpContext.Current.IsDebuggingEnabled + ? "~/js/Debug/dnncore.js" + : "~/js/dnncore.js"; + + ClientResourceManager.RegisterScript(this, dnncoreFilePath); + + base.OnInit(e); + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + // Because we have delayed registration of the jQuery script, + // Modules can override the standard behavior by including their own script on the page. + // The module must register the script with the "jQuery" key and should notify user + // of potential version conflicts with core jQuery support. + // if (jQuery.IsRequested) + // { + // jQuery.RegisterJQuery(Page); + // } + // if (jQuery.IsUIRequested) + // { + // jQuery.RegisterJQueryUI(Page); + // } + // if (jQuery.AreDnnPluginsRequested) + // { + // jQuery.RegisterDnnJQueryPlugins(Page); + // } + // if (jQuery.IsHoverIntentRequested) + // { + // jQuery.RegisterHoverIntent(Page); + // } + if (ServicesFrameworkInternal.Instance.IsAjaxAntiForgerySupportRequired) + { + ServicesFrameworkInternal.Instance.RegisterAjaxAntiForgery(this.Page); + } + + this.RegisterAjaxScript(); + } + + protected override void Render(HtmlTextWriter writer) + { + this.LogDnnTrace("PageBase.Render", "Start", $"{this.Page.Request.Url.AbsoluteUri}"); + + this.IterateControls(this.Controls, this._localizedControls, this.LocalResourceFile); + RemoveKeyAttribute(this._localizedControls); + AJAX.RemoveScriptManager(this); + base.Render(writer); + + this.LogDnnTrace("PageBase.Render", "End", $"{this.Page.Request.Url.AbsoluteUri}"); + } + + private void LocalizeControl(Control control, string value) + { + if (string.IsNullOrEmpty(value)) + { + return; + } + + var validator = control as BaseValidator; + if (validator != null) + { + validator.ErrorMessage = value; + validator.Text = value; + return; + } + + var label = control as Label; + if (label != null) + { + label.Text = value; + return; + } + + var linkButton = control as LinkButton; + if (linkButton != null) + { + var imgMatches = LinkItemMatchRegex.Matches(value); + foreach (Match match in imgMatches) + { + if (match.Groups[match.Groups.Count - 2].Value.IndexOf("~", StringComparison.Ordinal) == -1) + { + continue; + } + + var resolvedUrl = this.Page.ResolveUrl(match.Groups[match.Groups.Count - 2].Value); + value = value.Replace(match.Groups[match.Groups.Count - 2].Value, resolvedUrl); + } + + linkButton.Text = value; + if (string.IsNullOrEmpty(linkButton.ToolTip)) + { + linkButton.ToolTip = value; + } + + return; + } + + var hyperLink = control as HyperLink; + if (hyperLink != null) + { + hyperLink.Text = value; + return; + } + + var button = control as Button; + if (button != null) + { + button.Text = value; + return; + } + + var htmlButton = control as HtmlButton; + if (htmlButton != null) + { + htmlButton.Attributes["Title"] = value; + return; + } + + var htmlImage = control as HtmlImage; + if (htmlImage != null) + { + htmlImage.Alt = value; + return; + } + + var checkBox = control as CheckBox; + if (checkBox != null) + { + checkBox.Text = value; + return; + } + + var image = control as Image; + if (image != null) + { + image.AlternateText = value; + image.ToolTip = value; + return; + } + + var textBox = control as TextBox; + if (textBox != null) + { + textBox.ToolTip = value; + } + } } } diff --git a/DNN Platform/Library/Framework/Reflections/TypeLocator.cs b/DNN Platform/Library/Framework/Reflections/TypeLocator.cs index a29abaefe3c..7c953f2719e 100644 --- a/DNN Platform/Library/Framework/Reflections/TypeLocator.cs +++ b/DNN Platform/Library/Framework/Reflections/TypeLocator.cs @@ -16,6 +16,18 @@ public class TypeLocator : ITypeLocator, IAssemblyLocator { private IAssemblyLocator _assemblyLocator; + IEnumerable IAssemblyLocator.Assemblies + { + // this method is not readily testable as the assemblies in the current app domain + // will vary depending on the test runner and test configuration + get + { + return from assembly in AppDomain.CurrentDomain.GetAssemblies() + where this.CanScan(assembly) + select new AssemblyWrapper(assembly); + } + } + internal IAssemblyLocator AssemblyLocator { get { return this._assemblyLocator ?? (this._assemblyLocator = this); } @@ -106,17 +118,5 @@ private bool CanScan(Assembly assembly) return canScan; } - - IEnumerable IAssemblyLocator.Assemblies - { - // this method is not readily testable as the assemblies in the current app domain - // will vary depending on the test runner and test configuration - get - { - return from assembly in AppDomain.CurrentDomain.GetAssemblies() - where this.CanScan(assembly) - select new AssemblyWrapper(assembly); - } - } } } diff --git a/DNN Platform/Library/Framework/SecurityPolicy.cs b/DNN Platform/Library/Framework/SecurityPolicy.cs index 93c32d18682..d4e8828da8e 100644 --- a/DNN Platform/Library/Framework/SecurityPolicy.cs +++ b/DNN Platform/Library/Framework/SecurityPolicy.cs @@ -50,6 +50,18 @@ public static string Permissions } } + public static bool HasAspNetHostingPermission() + { + GetPermissions(); + return m_AspNetHostingPermission; + } + + public static bool HasReflectionPermission() + { + GetPermissions(); + return m_ReflectionPermission; + } + private static void GetPermissions() { if (!m_Initialized) @@ -110,18 +122,6 @@ private static void GetPermissions() } } - public static bool HasAspNetHostingPermission() - { - GetPermissions(); - return m_AspNetHostingPermission; - } - - public static bool HasReflectionPermission() - { - GetPermissions(); - return m_ReflectionPermission; - } - public static bool HasWebPermission() { GetPermissions(); diff --git a/DNN Platform/Library/Framework/ServiceLocator.cs b/DNN Platform/Library/Framework/ServiceLocator.cs index 26008b473ae..4e1e6fae109 100644 --- a/DNN Platform/Library/Framework/ServiceLocator.cs +++ b/DNN Platform/Library/Framework/ServiceLocator.cs @@ -13,28 +13,14 @@ namespace DotNetNuke.Framework /// The type of the controller itself, used to call the GetFactory override. public abstract class ServiceLocator where TSelf : ServiceLocator, new() - { -// ReSharper disable StaticFieldInGenericType -// ReSharper disable InconsistentNaming - private static Lazy _instance = new Lazy(InitInstance, true); + { + // ReSharper disable StaticFieldInGenericType + // ReSharper disable InconsistentNaming + private static Lazy _instance = new Lazy(InitInstance, true); -// ReSharper restore InconsistentNaming + // ReSharper restore InconsistentNaming private static TContract _testableInstance; - private static bool _useTestable; - -// ReSharper restore StaticFieldInGenericType - protected static Func Factory { get; set; } - - private static TContract InitInstance() - { - if (Factory == null) - { - var controllerInstance = new TSelf(); - Factory = controllerInstance.GetFactory(); - } - - return Factory(); - } + private static bool _useTestable; /// /// Gets a singleton of T. @@ -51,6 +37,9 @@ public static TContract Instance return _instance.Value; } } + + // ReSharper restore StaticFieldInGenericType + protected static Func Factory { get; set; } /// /// Registers an instance to use for the Singleton. @@ -74,6 +63,17 @@ public static void ClearInstance() _instance = new Lazy(InitInstance, true); } + private static TContract InitInstance() + { + if (Factory == null) + { + var controllerInstance = new TSelf(); + Factory = controllerInstance.GetFactory(); + } + + return Factory(); + } + protected abstract Func GetFactory(); } } diff --git a/DNN Platform/Library/Framework/ServicesFramework.cs b/DNN Platform/Library/Framework/ServicesFramework.cs index fb8bf134d51..f68a1f7a429 100644 --- a/DNN Platform/Library/Framework/ServicesFramework.cs +++ b/DNN Platform/Library/Framework/ServicesFramework.cs @@ -14,11 +14,6 @@ namespace DotNetNuke.Framework /// public class ServicesFramework : ServiceLocator { - protected override Func GetFactory() - { - return () => new ServicesFrameworkImpl(); - } - public static string GetServiceFrameworkRoot() { var portalSettings = PortalSettings.Current; @@ -44,5 +39,10 @@ public static string GetServiceFrameworkRoot() return path; } + + protected override Func GetFactory() + { + return () => new ServicesFrameworkImpl(); + } } } diff --git a/DNN Platform/Library/Framework/ServicesFrameworkImpl.cs b/DNN Platform/Library/Framework/ServicesFrameworkImpl.cs index b598b16d600..5513d244e9b 100644 --- a/DNN Platform/Library/Framework/ServicesFrameworkImpl.cs +++ b/DNN Platform/Library/Framework/ServicesFrameworkImpl.cs @@ -20,15 +20,20 @@ internal class ServicesFrameworkImpl : IServicesFramework, IServiceFrameworkInte private const string AntiForgeryKey = "dnnAntiForgeryRequested"; private const string ScriptKey = "dnnSFAjaxScriptRequested"; - public void RequestAjaxAntiForgerySupport() + public bool IsAjaxAntiForgerySupportRequired { - this.RequestAjaxScriptSupport(); - SetKey(AntiForgeryKey); + get { return CheckKey(AntiForgeryKey); } } - public bool IsAjaxAntiForgerySupportRequired + public bool IsAjaxScriptSupportRequired { - get { return CheckKey(AntiForgeryKey); } + get { return CheckKey(ScriptKey); } + } + + public void RequestAjaxAntiForgerySupport() + { + this.RequestAjaxScriptSupport(); + SetKey(AntiForgeryKey); } public void RegisterAjaxAntiForgery(Page page) @@ -40,11 +45,6 @@ public void RegisterAjaxAntiForgery(Page page) } } - public bool IsAjaxScriptSupportRequired - { - get { return CheckKey(ScriptKey); } - } - public void RequestAjaxScriptSupport() { JavaScript.RequestRegistration(CommonJs.jQuery); diff --git a/DNN Platform/Library/Framework/jQuery.cs b/DNN Platform/Library/Framework/jQuery.cs index 80cf092e82b..51bceb5c3d0 100644 --- a/DNN Platform/Library/Framework/jQuery.cs +++ b/DNN Platform/Library/Framework/jQuery.cs @@ -25,13 +25,6 @@ namespace DotNetNuke.Framework #pragma warning disable 618 public class jQuery { - private const string jQueryDebugFile = "~/Resources/Shared/Scripts/jquery/jquery.js"; - private const string jQueryMinFile = "~/Resources/Shared/Scripts/jquery/jquery.min.js"; - private const string jQueryMigrateDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-migrate.js"; - private const string jQueryMigrateMinFile = "~/Resources/Shared/Scripts/jquery/jquery-migrate.min.js"; - private const string jQueryVersionKey = "jQueryVersionKey"; - private const string jQueryVersionMatch = "(?<=(jquery|core_version)\\s*[:=]\\s*\")(.*)(?=\")"; - /// /// Returns the default URL for a hosted version of the jQuery script. /// @@ -41,12 +34,19 @@ public class jQuery /// cached in the users browser. /// public const string DefaultHostedUrl = "http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"; + + public const string DefaultUIHostedUrl = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"; + private const string jQueryDebugFile = "~/Resources/Shared/Scripts/jquery/jquery.js"; + private const string jQueryMinFile = "~/Resources/Shared/Scripts/jquery/jquery.min.js"; + private const string jQueryMigrateDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-migrate.js"; + private const string jQueryMigrateMinFile = "~/Resources/Shared/Scripts/jquery/jquery-migrate.min.js"; + private const string jQueryVersionKey = "jQueryVersionKey"; + private const string jQueryVersionMatch = "(?<=(jquery|core_version)\\s*[:=]\\s*\")(.*)(?=\")"; private const string jQueryUIDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.js"; private const string jQueryUIMinFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.min.js"; private const string jQueryUIVersionKey = "jQueryUIVersionKey"; private const string jQueryUIVersionMatch = "(?<=version:\\s\")(.*)(?=\")"; - public const string DefaultUIHostedUrl = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"; /// /// Gets the HostSetting for the URL of the hosted version of the jQuery script. @@ -298,6 +298,18 @@ public static string UIVersion } } + [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + public static string JQueryFileMapPath(bool getMinFile) + { + return HttpContext.Current.Server.MapPath(JQueryFile(getMinFile)); + } + + [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + public static string JQueryUIFileMapPath(bool getMinFile) + { + return HttpContext.Current.Server.MapPath(JQueryUIFile(getMinFile)); + } + private static bool GetSettingAsBoolean(string key, bool defaultValue) { bool retValue = defaultValue; @@ -316,18 +328,6 @@ private static bool GetSettingAsBoolean(string key, bool defaultValue) return retValue; } - - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryFileMapPath(bool getMinFile) - { - return HttpContext.Current.Server.MapPath(JQueryFile(getMinFile)); - } - - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryUIFileMapPath(bool getMinFile) - { - return HttpContext.Current.Server.MapPath(JQueryUIFile(getMinFile)); - } [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string JQueryFile(bool getMinFile) diff --git a/DNN Platform/Library/Modules/NavigationProvider.cs b/DNN Platform/Library/Modules/NavigationProvider.cs index b4dbbcf073e..e64163d15da 100644 --- a/DNN Platform/Library/Modules/NavigationProvider.cs +++ b/DNN Platform/Library/Modules/NavigationProvider.cs @@ -16,6 +16,10 @@ public abstract class NavigationProvider : UserControlBase public delegate void PopulateOnDemandEventHandler(NavigationEventArgs args); + public event NodeClickEventHandler NodeClick; + + public event PopulateOnDemandEventHandler PopulateOnDemand; + public enum Alignment { Left, @@ -974,10 +978,6 @@ public virtual List CustomAttributes { } } - - public event NodeClickEventHandler NodeClick; - - public event PopulateOnDemandEventHandler PopulateOnDemand; public static NavigationProvider Instance(string FriendlyName) { diff --git a/DNN Platform/Library/Obsolete/PortalAliasController.cs b/DNN Platform/Library/Obsolete/PortalAliasController.cs index 2808e08135f..e60ce140b61 100644 --- a/DNN Platform/Library/Obsolete/PortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/PortalAliasController.cs @@ -17,6 +17,27 @@ namespace DotNetNuke.Entities.Portals public partial class PortalAliasController { + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in version 7.3. Replaced by PortalAliasController.Instance.GetPortalAlias. Scheduled removal in v10.0.0.")] + public static PortalAliasInfo GetPortalAliasInfo(string httpAlias) + { + return Instance.GetPortalAlias(httpAlias); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.GetPortalAliases. Scheduled removal in v10.0.0.")] + public static PortalAliasCollection GetPortalAliasLookup() + { + var portalAliasCollection = new PortalAliasCollection(); + var aliasController = new PortalAliasController(); + foreach (var kvp in aliasController.GetPortalAliasesInternal()) + { + portalAliasCollection.Add(kvp.Key, kvp.Value); + } + + return portalAliasCollection; + } + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.DeletePortalAlias. Scheduled removal in v10.0.0.")] public void DeletePortalAlias(int portalAliasId) @@ -54,27 +75,6 @@ public PortalAliasCollection GetPortalAliasByPortalID(int PortalID) return portalAliasCollection; } - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in version 7.3. Replaced by PortalAliasController.Instance.GetPortalAlias. Scheduled removal in v10.0.0.")] - public static PortalAliasInfo GetPortalAliasInfo(string httpAlias) - { - return Instance.GetPortalAlias(httpAlias); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.GetPortalAliases. Scheduled removal in v10.0.0.")] - public static PortalAliasCollection GetPortalAliasLookup() - { - var portalAliasCollection = new PortalAliasCollection(); - var aliasController = new PortalAliasController(); - foreach (var kvp in aliasController.GetPortalAliasesInternal()) - { - portalAliasCollection.Add(kvp.Key, kvp.Value); - } - - return portalAliasCollection; - } - [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in version 7.3. Replaced by PortalAliasController.Instance.GetPortalAlias. Scheduled removal in v10.0.0.")] public static PortalAliasInfo GetPortalAliasLookup(string httpAlias) diff --git a/DNN Platform/Library/Obsolete/PortalController.cs b/DNN Platform/Library/Obsolete/PortalController.cs index 1a74fa49c7b..1015ad4d53a 100644 --- a/DNN Platform/Library/Obsolete/PortalController.cs +++ b/DNN Platform/Library/Obsolete/PortalController.cs @@ -30,6 +30,20 @@ namespace DotNetNuke.Entities.Portals /// public partial class PortalController { + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in DotNetNuke 7.3. Replaced by PortalController.Instance.GetCurrentPortalSettings. Scheduled removal in v10.0.0.")] + public static PortalSettings GetCurrentPortalSettings() + { + return GetCurrentPortalSettingsInternal(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in DNN 7.4.0. Replaced by PortalController.Instance.GetPortalSettings. Scheduled removal in v10.0.0.")] + public static Dictionary GetPortalSettingsDictionary(int portalId) + { + return Instance.GetPortalSettings(portalId); + } + [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] public int CreatePortal(string portalName, string firstName, string lastName, string username, string password, string email, @@ -77,20 +91,6 @@ public void DeletePortalInfo(int portalId) DataCache.ClearHostCache(true); } - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. Replaced by PortalController.Instance.GetCurrentPortalSettings. Scheduled removal in v10.0.0.")] - public static PortalSettings GetCurrentPortalSettings() - { - return GetCurrentPortalSettingsInternal(); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.4.0. Replaced by PortalController.Instance.GetPortalSettings. Scheduled removal in v10.0.0.")] - public static Dictionary GetPortalSettingsDictionary(int portalId) - { - return Instance.GetPortalSettings(portalId); - } - [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] public void ParseTemplate(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) diff --git a/DNN Platform/Library/Obsolete/RoleController.cs b/DNN Platform/Library/Obsolete/RoleController.cs index a8f96f1db2b..11f918160f0 100644 --- a/DNN Platform/Library/Obsolete/RoleController.cs +++ b/DNN Platform/Library/Obsolete/RoleController.cs @@ -103,6 +103,6 @@ public void UpdateUserRole(int portalId, int userId, int roleId) public void UpdateUserRole(int portalId, int userId, int roleId, bool cancel) { this.UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, cancel); - } - } + } + } } diff --git a/DNN Platform/Library/Obsolete/TestableModuleController.cs b/DNN Platform/Library/Obsolete/TestableModuleController.cs index 63358927f4c..4370da78661 100644 --- a/DNN Platform/Library/Obsolete/TestableModuleController.cs +++ b/DNN Platform/Library/Obsolete/TestableModuleController.cs @@ -14,24 +14,24 @@ namespace DotNetNuke.Entities.Modules.Internal [Obsolete("This class has been obsoleted in 7.3.0 - please use ModuleController instead. Scheduled removal in v10.0.0.")] public class TestableModuleController : ServiceLocator, IModuleController { + public ModuleInfo GetModule(int moduleId, int tabId) + { + return ModuleController.Instance.GetModule(moduleId, tabId, false); + } + + public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) + { + ModuleController.Instance.UpdateModuleSetting(moduleId, settingName, settingValue); + } + protected override Func GetFactory() { return () => new TestableModuleController(); } - public ModuleInfo GetModule(int moduleId, int tabId) - { - return ModuleController.Instance.GetModule(moduleId, tabId, false); - } - - public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) - { - ModuleController.Instance.UpdateModuleSetting(moduleId, settingName, settingValue); - } - - public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) - { - ModuleController.Instance.UpdateTabModuleSetting(tabModuleId, settingName, settingValue); - } + public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) + { + ModuleController.Instance.UpdateTabModuleSetting(tabModuleId, settingName, settingValue); + } } } diff --git a/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs b/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs index ef6d1ac58f7..3578b537a3f 100644 --- a/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs @@ -14,11 +14,6 @@ namespace DotNetNuke.Entities.Portals.Internal [Obsolete("This class has been obsoleted in 7.3.0 - please use PortalAliasController instead. Scheduled removal in v10.0.0.")] public class TestablePortalAliasController : ServiceLocator, IPortalAliasController { - protected override Func GetFactory() - { - return () => new TestablePortalAliasController(); - } - public int AddPortalAlias(PortalAliasInfo portalAlias) { return PortalAliasController.Instance.AddPortalAlias(portalAlias); @@ -28,6 +23,11 @@ public void DeletePortalAlias(PortalAliasInfo portalAlias) { PortalAliasController.Instance.DeletePortalAlias(portalAlias); } + + protected override Func GetFactory() + { + return () => new TestablePortalAliasController(); + } public PortalAliasInfo GetPortalAlias(string alias) { diff --git a/DNN Platform/Library/Obsolete/TestableRoleController.cs b/DNN Platform/Library/Obsolete/TestableRoleController.cs index fb4c5b95ec3..9f31cd0f437 100644 --- a/DNN Platform/Library/Obsolete/TestableRoleController.cs +++ b/DNN Platform/Library/Obsolete/TestableRoleController.cs @@ -14,11 +14,6 @@ namespace DotNetNuke.Security.Roles.Internal [Obsolete("This class has been obsoleted in 7.3.0 - please use RoleController instead. Scheduled removal in v10.0.0.")] public class TestableRoleController : ServiceLocator, IRoleController { - protected override Func GetFactory() - { - return () => new TestableRoleController(); - } - public int AddRole(RoleInfo role) { return RoleController.Instance.AddRole(role); @@ -28,6 +23,11 @@ public int AddRole(RoleInfo role, bool addToExistUsers) { return RoleController.Instance.AddRole(role, addToExistUsers); } + + protected override Func GetFactory() + { + return () => new TestableRoleController(); + } public void DeleteRole(RoleInfo role) { diff --git a/DNN Platform/Library/Obsolete/TestableTabController.cs b/DNN Platform/Library/Obsolete/TestableTabController.cs index f9f1b6dd038..89756458e56 100644 --- a/DNN Platform/Library/Obsolete/TestableTabController.cs +++ b/DNN Platform/Library/Obsolete/TestableTabController.cs @@ -15,11 +15,6 @@ namespace DotNetNuke.Entities.Tabs.Internal [Obsolete("This class has been obsoleted in 7.3.0 - please use TabController instead. Scheduled removal in v10.0.0.")] public class TestableTabController : ServiceLocator, ITabController { - protected override Func GetFactory() - { - return () => new TestableTabController(); - } - public void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) { TabController.Instance.DeleteTabUrl(tabUrl, portalId, clearCache); @@ -29,6 +24,11 @@ public TabInfo GetTab(int tabId, int portalId) { return TabController.Instance.GetTab(tabId, portalId); } + + protected override Func GetFactory() + { + return () => new TestableTabController(); + } public Dictionary GetCustomAliases(int tabId, int portalId) { diff --git a/DNN Platform/Library/Obsolete/TestableUserController.cs b/DNN Platform/Library/Obsolete/TestableUserController.cs index 25c6d80d120..d0ed78714e8 100644 --- a/DNN Platform/Library/Obsolete/TestableUserController.cs +++ b/DNN Platform/Library/Obsolete/TestableUserController.cs @@ -13,11 +13,6 @@ namespace DotNetNuke.Entities.Users.Internal [Obsolete("This class has been obsoleted in 7.3.0 - please use UserController instead. Scheduled removal in v10.0.0.")] public class TestableUserController : ServiceLocator, IUserController { - protected override Func GetFactory() - { - return () => new TestableUserController(); - } - public UserInfo GetUserByDisplayname(int portalId, string displayName) { return UserController.Instance.GetUserByDisplayname(portalId, displayName); @@ -27,6 +22,11 @@ public UserInfo GetUserById(int portalId, int userId) { return UserController.Instance.GetUserById(portalId, userId); } + + protected override Func GetFactory() + { + return () => new TestableUserController(); + } public IList GetUsersAdvancedSearch(int portalId, int userId, int filterUserId, int filterRoleId, int relationTypeId, bool isAdmin, int pageIndex, int pageSize, string sortColumn, bool sortAscending, string propertyNames, diff --git a/DNN Platform/Library/Security/Cookies/AuthCookieController.cs b/DNN Platform/Library/Security/Cookies/AuthCookieController.cs index d1c78d09129..4c99f73016d 100644 --- a/DNN Platform/Library/Security/Cookies/AuthCookieController.cs +++ b/DNN Platform/Library/Security/Cookies/AuthCookieController.cs @@ -16,11 +16,6 @@ public class AuthCookieController : ServiceLocator GetFactory() - { - return () => new AuthCookieController(); - } - public void Update(string cookieValue, DateTime utcExpiry, int userId) { if (string.IsNullOrEmpty(cookieValue)) @@ -44,6 +39,11 @@ public PersistedAuthCookie Find(string cookieValue) _ => CBO.Instance.FillObject(this._dataProvider.FindAuthCookie(cookieValue)), false); } + protected override Func GetFactory() + { + return () => new AuthCookieController(); + } + public void DeleteByValue(string cookieValue) { if (string.IsNullOrEmpty(cookieValue)) diff --git a/DNN Platform/Library/Security/FIPSCompliant.cs b/DNN Platform/Library/Security/FIPSCompliant.cs index 40dd26254db..448b502365f 100644 --- a/DNN Platform/Library/Security/FIPSCompliant.cs +++ b/DNN Platform/Library/Security/FIPSCompliant.cs @@ -68,23 +68,6 @@ public static string EncryptAES(string plainText, string passPhrase, string salt } } - private static void VerifyAesSettings(string passPhrase, string salt) - { - Requires.PropertyNotNull("passPhrase", passPhrase); - Requires.PropertyNotNull("salt", salt); - - // Throw exception if the password or salt are too short - if (passPhrase.Length < 8) - { - throw new CryptographicException("Passphrase must be at least 8 characters long."); - } - - if (salt.Length < 8) - { - throw new CryptographicException("Salt must be at least 8 characters long."); - } - } - /// /// uses the AES FIPS-140 compliant algorithm to encrypt a string. /// @@ -120,5 +103,22 @@ public static string DecryptAES(string encryptedText, string passPhrase, string return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount); } } + + private static void VerifyAesSettings(string passPhrase, string salt) + { + Requires.PropertyNotNull("passPhrase", passPhrase); + Requires.PropertyNotNull("salt", salt); + + // Throw exception if the password or salt are too short + if (passPhrase.Length < 8) + { + throw new CryptographicException("Passphrase must be at least 8 characters long."); + } + + if (salt.Length < 8) + { + throw new CryptographicException("Salt must be at least 8 characters long."); + } + } } } diff --git a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs index 19f6de45960..fc055df9930 100644 --- a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs +++ b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs @@ -43,6 +43,8 @@ namespace DotNetNuke.Security.Membership public class AspNetMembershipProvider : MembershipProvider { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AspNetMembershipProvider)); + private static Random random = new Random(); + private readonly DataProvider _dataProvider = DataProvider.Instance(); private readonly IEnumerable _socialAuthProviders = new List() { "Facebook", "Google", "Twitter", "LiveID" }; @@ -172,68 +174,129 @@ public override bool RequiresUniqueEmail } } - private static bool AutoUnlockUser(MembershipUser aspNetUser) + public static ArrayList FillUserCollection(int portalId, IDataReader dr) { - if (Host.AutoAccountUnlockDuration != 0) + // Note: the DataReader returned from this method should contain 2 result sets. The first set + // contains the TotalRecords, that satisfy the filter, the second contains the page + // of data + var arrUsers = new ArrayList(); + try { - if (aspNetUser.LastLockoutDate < DateTime.Now.AddMinutes(-1 * Host.AutoAccountUnlockDuration)) + while (dr.Read()) { - // Unlock user in Data Store - if (aspNetUser.UnlockUser()) - { - return true; - } + // fill business object + UserInfo user = FillUserInfo(portalId, dr, false); + + // add to collection + arrUsers.Add(user); } } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); + } - return false; + return arrUsers; + } + + public override UserInfo GetUserByAuthToken(int portalId, string userToken, string authType) + { + IDataReader dr = this._dataProvider.GetUserByAuthToken(portalId, userToken, authType); + UserInfo objUserInfo = FillUserInfo(portalId, dr, true); + return objUserInfo; + } + + /// + /// add new userportal record (used for creating sites with existing user). + /// + /// portalid. + /// userid. + public override void AddUserPortal(int portalId, int userId) + { + Requires.NotNullOrEmpty("portalId", portalId.ToString()); + Requires.NotNullOrEmpty("userId", userId.ToString()); + this._dataProvider.AddUserPortal(portalId, userId); } - private UserCreateStatus CreateDNNUser(ref UserInfo user) + /// + /// function supports the ability change username. + /// + /// user id. + /// updated username. + public override void ChangeUsername(int userId, string newUsername) { - var objSecurity = PortalSecurity.Instance; - var filterFlags = PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup; - user.Username = objSecurity.InputFilter(user.Username, filterFlags); - user.Email = objSecurity.InputFilter(user.Email, filterFlags); - user.LastName = objSecurity.InputFilter(user.LastName, filterFlags); - user.FirstName = objSecurity.InputFilter(user.FirstName, filterFlags); - user.DisplayName = objSecurity.InputFilter(user.DisplayName, filterFlags); - if (user.DisplayName.Contains("<") || user.DisplayName.Contains(">")) + Requires.NotNull("userId", userId); + Requires.NotNullOrEmpty("newUsername", newUsername); + + var userName = PortalSecurity.Instance.InputFilter( + newUsername, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + + if (!userName.Equals(newUsername)) { - user.DisplayName = HttpUtility.HtmlEncode(user.DisplayName); + throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); } - - var updatePassword = user.Membership.UpdatePassword; - var isApproved = user.Membership.Approved; - var createStatus = UserCreateStatus.Success; - try + + var valid = UserController.Instance.IsValidUserName(userName); + + if (!valid) { - user.UserID = - Convert.ToInt32(this._dataProvider.AddUser( - user.PortalID, - user.Username, - user.FirstName, - user.LastName, - user.AffiliateID, - user.IsSuperUser, - user.Email, - user.DisplayName, - updatePassword, - isApproved, - UserController.Instance.GetCurrentUserInfo().UserID)); + throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); + } - // Save the user password history - new MembershipPasswordController().IsPasswordInHistory(user.UserID, user.PortalID, user.Membership.Password); + // read all the user account settings + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (portalSettings != null) + { + var settings = UserController.GetUserSettings(portalSettings.PortalId); + + // User Name Validation + var userNameValidator = this.GetStringSetting(settings, "Security_UserNameValidation"); + if (!string.IsNullOrEmpty(userNameValidator)) + { + var regExp = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline); + var matches = regExp.Matches(userName); + if (matches.Count == 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); + } + } } - catch (Exception ex) + + this._dataProvider.ChangeUsername(userId, userName); + + EventLogController.Instance.AddLog( + "userId", + userId.ToString(), + portalSettings, + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.USERNAME_UPDATED); + + DataCache.ClearCache(); + } + + private static bool AutoUnlockUser(MembershipUser aspNetUser) + { + if (Host.AutoAccountUnlockDuration != 0) { - // Clear User (duplicate User information) - Exceptions.LogException(ex); - user = null; - createStatus = UserCreateStatus.ProviderError; + if (aspNetUser.LastLockoutDate < DateTime.Now.AddMinutes(-1 * Host.AutoAccountUnlockDuration)) + { + // Unlock user in Data Store + if (aspNetUser.UnlockUser()) + { + return true; + } + } } - return createStatus; + return false; } private static UserCreateStatus CreateMemberhipUser(UserInfo user) @@ -326,6 +389,53 @@ private static void DeleteMembershipUser(UserInfo user) } } + private UserCreateStatus CreateDNNUser(ref UserInfo user) + { + var objSecurity = PortalSecurity.Instance; + var filterFlags = PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup; + user.Username = objSecurity.InputFilter(user.Username, filterFlags); + user.Email = objSecurity.InputFilter(user.Email, filterFlags); + user.LastName = objSecurity.InputFilter(user.LastName, filterFlags); + user.FirstName = objSecurity.InputFilter(user.FirstName, filterFlags); + user.DisplayName = objSecurity.InputFilter(user.DisplayName, filterFlags); + if (user.DisplayName.Contains("<") || user.DisplayName.Contains(">")) + { + user.DisplayName = HttpUtility.HtmlEncode(user.DisplayName); + } + + var updatePassword = user.Membership.UpdatePassword; + var isApproved = user.Membership.Approved; + var createStatus = UserCreateStatus.Success; + try + { + user.UserID = + Convert.ToInt32(this._dataProvider.AddUser( + user.PortalID, + user.Username, + user.FirstName, + user.LastName, + user.AffiliateID, + user.IsSuperUser, + user.Email, + user.DisplayName, + updatePassword, + isApproved, + UserController.Instance.GetCurrentUserInfo().UserID)); + + // Save the user password history + new MembershipPasswordController().IsPasswordInHistory(user.UserID, user.PortalID, user.Membership.Password); + } + catch (Exception ex) + { + // Clear User (duplicate User information) + Exceptions.LogException(ex); + user = null; + createStatus = UserCreateStatus.ProviderError; + } + + return createStatus; + } + private static ArrayList FillUserCollection(int portalId, IDataReader dr, ref int totalRecords) { // Note: the DataReader returned from this method should contain 2 result sets. The first set @@ -631,13 +741,6 @@ private static object GetMembershipUserByUserKeyCallBack(CacheItemArgs cacheItem return System.Web.Security.Membership.GetUser(new Guid(userKey)); } - - public override UserInfo GetUserByAuthToken(int portalId, string userToken, string authType) - { - IDataReader dr = this._dataProvider.GetUserByAuthToken(portalId, userToken, authType); - UserInfo objUserInfo = FillUserInfo(portalId, dr, true); - return objUserInfo; - } private static void UpdateUserMembership(UserInfo user) { @@ -722,77 +825,6 @@ private string GetStringSetting(Hashtable settings, string settingKey) { return settings[settingKey] == null ? string.Empty : settings[settingKey].ToString(); } - - /// - /// add new userportal record (used for creating sites with existing user). - /// - /// portalid. - /// userid. - public override void AddUserPortal(int portalId, int userId) - { - Requires.NotNullOrEmpty("portalId", portalId.ToString()); - Requires.NotNullOrEmpty("userId", userId.ToString()); - this._dataProvider.AddUserPortal(portalId, userId); - } - - /// - /// function supports the ability change username. - /// - /// user id. - /// updated username. - public override void ChangeUsername(int userId, string newUsername) - { - Requires.NotNull("userId", userId); - Requires.NotNullOrEmpty("newUsername", newUsername); - - var userName = PortalSecurity.Instance.InputFilter( - newUsername, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - - if (!userName.Equals(newUsername)) - { - throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); - } - - var valid = UserController.Instance.IsValidUserName(userName); - - if (!valid) - { - throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); - } - - // read all the user account settings - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (portalSettings != null) - { - var settings = UserController.GetUserSettings(portalSettings.PortalId); - - // User Name Validation - var userNameValidator = this.GetStringSetting(settings, "Security_UserNameValidation"); - if (!string.IsNullOrEmpty(userNameValidator)) - { - var regExp = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline); - var matches = regExp.Matches(userName); - if (matches.Count == 0) - { - throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); - } - } - } - - this._dataProvider.ChangeUsername(userId, userName); - - EventLogController.Instance.AddLog( - "userId", - userId.ToString(), - portalSettings, - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.USERNAME_UPDATED); - - DataCache.ClearCache(); - } /// ----------------------------------------------------------------------------- /// @@ -863,49 +895,6 @@ public override bool ChangePasswordQuestionAndAnswer(UserInfo user, string passw return aspnetUser.ChangePasswordQuestionAndAnswer(password, passwordQuestion, passwordAnswer); } - private UserCreateStatus ValidateForProfanity(UserInfo user) - { - var portalSecurity = PortalSecurity.Instance; - var createStatus = UserCreateStatus.AddUser; - - Hashtable settings = UserController.GetUserSettings(user.PortalID); - bool useProfanityFilter = Convert.ToBoolean(settings["Registration_UseProfanityFilter"]); - - // Validate Profanity - if (useProfanityFilter) - { - if (!portalSecurity.ValidateInput(user.Username, PortalSecurity.FilterFlag.NoProfanity)) - { - createStatus = UserCreateStatus.InvalidUserName; - } - - if (!string.IsNullOrEmpty(user.DisplayName)) - { - if (!portalSecurity.ValidateInput(user.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) - { - createStatus = UserCreateStatus.InvalidDisplayName; - } - } - } - - return createStatus; - } - - private void ValidateForDuplicateDisplayName(UserInfo user, ref UserCreateStatus createStatus) - { - Hashtable settings = UserController.GetUserSettings(user.PortalID); - bool requireUniqueDisplayName = Convert.ToBoolean(settings["Registration_RequireUniqueDisplayName"]); - - if (requireUniqueDisplayName) - { - UserInfo duplicateUser = this.GetUserByDisplayName(user.PortalID, user.DisplayName); - if (duplicateUser != null) - { - createStatus = UserCreateStatus.DuplicateDisplayName; - } - } - } - /// ----------------------------------------------------------------------------- /// /// CreateUser persists a User to the Data Store. @@ -1022,6 +1011,49 @@ public override bool DeleteUser(UserInfo user) return retValue; } + private UserCreateStatus ValidateForProfanity(UserInfo user) + { + var portalSecurity = PortalSecurity.Instance; + var createStatus = UserCreateStatus.AddUser; + + Hashtable settings = UserController.GetUserSettings(user.PortalID); + bool useProfanityFilter = Convert.ToBoolean(settings["Registration_UseProfanityFilter"]); + + // Validate Profanity + if (useProfanityFilter) + { + if (!portalSecurity.ValidateInput(user.Username, PortalSecurity.FilterFlag.NoProfanity)) + { + createStatus = UserCreateStatus.InvalidUserName; + } + + if (!string.IsNullOrEmpty(user.DisplayName)) + { + if (!portalSecurity.ValidateInput(user.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) + { + createStatus = UserCreateStatus.InvalidDisplayName; + } + } + } + + return createStatus; + } + + private void ValidateForDuplicateDisplayName(UserInfo user, ref UserCreateStatus createStatus) + { + Hashtable settings = UserController.GetUserSettings(user.PortalID); + bool requireUniqueDisplayName = Convert.ToBoolean(settings["Registration_RequireUniqueDisplayName"]); + + if (requireUniqueDisplayName) + { + UserInfo duplicateUser = this.GetUserByDisplayName(user.PortalID, user.DisplayName); + if (duplicateUser != null) + { + createStatus = UserCreateStatus.DuplicateDisplayName; + } + } + } + /// ----------------------------------------------------------------------------- /// /// Deletes all UserOnline inof from the database that has activity outside of the @@ -1720,15 +1752,6 @@ public override void ResetTermsAgreement(int portalId) this._dataProvider.ResetTermsAgreement(portalId); } - private static Random random = new Random(); - - private string RandomString(int length) - { - const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - return new string(Enumerable.Repeat(chars, length) - .Select(s => s[random.Next(s.Length)]).ToArray()); - } - /// /// Sets a boolean on the user portal to indicate this user has requested that their account be deleted. /// @@ -1817,6 +1840,13 @@ public override void UpdateUser(UserInfo user) // Persist the Profile to the Data Store ProfileController.UpdateUserProfile(user); } + + private string RandomString(int length) + { + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + return new string(Enumerable.Repeat(chars, length) + .Select(s => s[random.Next(s.Length)]).ToArray()); + } /// ----------------------------------------------------------------------------- /// @@ -1964,36 +1994,6 @@ public override UserInfo UserLogin(int portalId, string username, string passwor return user; } - - public static ArrayList FillUserCollection(int portalId, IDataReader dr) - { - // Note: the DataReader returned from this method should contain 2 result sets. The first set - // contains the TotalRecords, that satisfy the filter, the second contains the page - // of data - var arrUsers = new ArrayList(); - try - { - while (dr.Read()) - { - // fill business object - UserInfo user = FillUserInfo(portalId, dr, false); - - // add to collection - arrUsers.Add(user); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); - } - - return arrUsers; - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs index 6400fe1f51a..1884d249a53 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs @@ -20,19 +20,6 @@ public class DesktopModulePermissionsGrid : PermissionsGrid private List _PermissionsList; private int _PortalDesktopModuleID = -1; - protected override List PermissionsList - { - get - { - if (this._PermissionsList == null && this._DesktopModulePermissions != null) - { - this._PermissionsList = this._DesktopModulePermissions.ToList(); - } - - return this._PermissionsList; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets the Permissions Collection. @@ -73,39 +60,27 @@ public int PortalDesktopModuleID } } - /// ----------------------------------------------------------------------------- - /// - /// Gets the DesktopModulePermissions from the Data Store. - /// - /// ----------------------------------------------------------------------------- - private void GetDesktopModulePermissions() - { - this._DesktopModulePermissions = new DesktopModulePermissionCollection(DesktopModulePermissionController.GetDesktopModulePermissions(this.PortalDesktopModuleID)); - } - - /// ----------------------------------------------------------------------------- - /// - /// Parse the Permission Keys used to persist the Permissions in the ViewState. - /// - /// A string array of settings. - /// ----------------------------------------------------------------------------- - private DesktopModulePermissionInfo ParseKeys(string[] Settings) + protected override List PermissionsList { - var objDesktopModulePermission = new DesktopModulePermissionInfo(); - - // Call base class to load base properties - this.ParsePermissionKeys(objDesktopModulePermission, Settings); - if (string.IsNullOrEmpty(Settings[2])) - { - objDesktopModulePermission.DesktopModulePermissionID = -1; - } - else + get { - objDesktopModulePermission.DesktopModulePermissionID = Convert.ToInt32(Settings[2]); + if (this._PermissionsList == null && this._DesktopModulePermissions != null) + { + this._PermissionsList = this._DesktopModulePermissions.ToList(); + } + + return this._PermissionsList; } + } - objDesktopModulePermission.PortalDesktopModuleID = this.PortalDesktopModuleID; - return objDesktopModulePermission; + public void ResetPermissions() + { + this.GetDesktopModulePermissions(); + this._PermissionsList = null; + } + + public override void GenerateDataGrid() + { } protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) @@ -155,6 +130,41 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) } } } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the DesktopModulePermissions from the Data Store. + /// + /// ----------------------------------------------------------------------------- + private void GetDesktopModulePermissions() + { + this._DesktopModulePermissions = new DesktopModulePermissionCollection(DesktopModulePermissionController.GetDesktopModulePermissions(this.PortalDesktopModuleID)); + } + + /// ----------------------------------------------------------------------------- + /// + /// Parse the Permission Keys used to persist the Permissions in the ViewState. + /// + /// A string array of settings. + /// ----------------------------------------------------------------------------- + private DesktopModulePermissionInfo ParseKeys(string[] Settings) + { + var objDesktopModulePermission = new DesktopModulePermissionInfo(); + + // Call base class to load base properties + this.ParsePermissionKeys(objDesktopModulePermission, Settings); + if (string.IsNullOrEmpty(Settings[2])) + { + objDesktopModulePermission.DesktopModulePermissionID = -1; + } + else + { + objDesktopModulePermission.DesktopModulePermissionID = Convert.ToInt32(Settings[2]); + } + + objDesktopModulePermission.PortalDesktopModuleID = this.PortalDesktopModuleID; + return objDesktopModulePermission; + } /// ----------------------------------------------------------------------------- /// @@ -301,15 +311,5 @@ protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; } - - public void ResetPermissions() - { - this.GetDesktopModulePermissions(); - this._PermissionsList = null; - } - - public override void GenerateDataGrid() - { - } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs index d6703a7774d..34008a0b45e 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs @@ -20,33 +20,12 @@ namespace DotNetNuke.Security.Permissions.Controls public class FolderPermissionsGrid : PermissionsGrid { - private string _folderPath = string.Empty; protected FolderPermissionCollection FolderPermissions; + private string _folderPath = string.Empty; private List _permissionsList; private bool _refreshGrid; private IList _systemFolderPermissions; - protected override List PermissionsList - { - get - { - if (this._permissionsList == null && this.FolderPermissions != null) - { - this._permissionsList = this.FolderPermissions.ToList(); - } - - return this._permissionsList; - } - } - - protected override bool RefreshGrid - { - get - { - return this._refreshGrid; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and Sets the path of the Folder. @@ -84,6 +63,36 @@ public FolderPermissionCollection Permissions } } + protected override List PermissionsList + { + get + { + if (this._permissionsList == null && this.FolderPermissions != null) + { + this._permissionsList = this.FolderPermissions.ToList(); + } + + return this._permissionsList; + } + } + + protected override bool RefreshGrid + { + get + { + return this._refreshGrid; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Overrides the Base method to Generate the Data Grid. + /// + /// ----------------------------------------------------------------------------- + public override void GenerateDataGrid() + { + } + /// ----------------------------------------------------------------------------- /// /// Gets the TabPermissions from the Data Store. @@ -94,6 +103,29 @@ protected virtual void GetFolderPermissions() this.FolderPermissions = new FolderPermissionCollection(FolderPermissionController.GetFolderPermissionsCollectionByFolder(this.PortalId, this.FolderPath)); this._permissionsList = null; } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; + } + + protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) + { + var objPermission = new FolderPermissionInfo(permission) + { + FolderPath = this.FolderPath, + RoleID = roleId, + RoleName = roleName, + AllowAccess = allowAccess, + UserID = userId, + DisplayName = displayName, + }; + this.FolderPermissions.Add(objPermission, true); + + // Clear Permission List + this._permissionsList = null; + } /// ----------------------------------------------------------------------------- /// @@ -137,29 +169,6 @@ private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventA } } } - - protected override void CreateChildControls() - { - base.CreateChildControls(); - this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; - } - - protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) - { - var objPermission = new FolderPermissionInfo(permission) - { - FolderPath = this.FolderPath, - RoleID = roleId, - RoleName = roleName, - AllowAccess = allowAccess, - UserID = userId, - DisplayName = displayName, - }; - this.FolderPermissions.Add(objPermission, true); - - // Clear Permission List - this._permissionsList = null; - } /// ----------------------------------------------------------------------------- /// @@ -268,21 +277,6 @@ protected override bool IsViewPermisison(PermissionInfo permissionInfo) return permissionInfo.PermissionKey == "READ"; } - private bool IsPermissionAlwaysGrantedToAdmin(PermissionInfo permissionInfo) - { - return this.IsSystemFolderPermission(permissionInfo); - } - - private bool IsSystemFolderPermission(PermissionInfo permissionInfo) - { - return this._systemFolderPermissions.Any(pi => pi.PermissionID == permissionInfo.PermissionID); - } - - private bool IsImplicitRole(int portalId, int roleId) - { - return FolderPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); - } - /// ----------------------------------------------------------------------------- /// /// Gets the permissions from the Database. @@ -340,6 +334,21 @@ protected override void LoadViewState(object savedState) } } + private bool IsPermissionAlwaysGrantedToAdmin(PermissionInfo permissionInfo) + { + return this.IsSystemFolderPermission(permissionInfo); + } + + private bool IsSystemFolderPermission(PermissionInfo permissionInfo) + { + return this._systemFolderPermissions.Any(pi => pi.PermissionID == permissionInfo.PermissionID); + } + + private bool IsImplicitRole(int portalId, int roleId) + { + return FolderPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); + } + protected override void RemovePermission(int permissionID, int roleID, int userID) { this.FolderPermissions.Remove(permissionID, roleID, userID); @@ -405,14 +414,5 @@ protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return this.IsSystemFolderPermission(permissionInfo); } - - /// ----------------------------------------------------------------------------- - /// - /// Overrides the Base method to Generate the Data Grid. - /// - /// ----------------------------------------------------------------------------- - public override void GenerateDataGrid() - { - } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs index d69a06925cd..62d6e10b4da 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs @@ -32,19 +32,6 @@ public ModulePermissionsGrid() this.TabId = -1; } - protected override List PermissionsList - { - get - { - if (this._PermissionsList == null && this._ModulePermissions != null) - { - this._PermissionsList = this._ModulePermissions.ToList(); - } - - return this._PermissionsList; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets and Sets whether the Module inherits the Page's(Tab's) permissions. @@ -85,6 +72,19 @@ public int ModuleID } } } + + protected override List PermissionsList + { + get + { + if (this._PermissionsList == null && this._ModulePermissions != null) + { + this._PermissionsList = this._ModulePermissions.ToList(); + } + + return this._PermissionsList; + } + } /// ----------------------------------------------------------------------------- /// @@ -109,6 +109,46 @@ public ModulePermissionCollection Permissions return this._ModulePermissions; } } + + /// ----------------------------------------------------------------------------- + /// + /// Overrides the Base method to Generate the Data Grid. + /// + /// ----------------------------------------------------------------------------- + public override void GenerateDataGrid() + { + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; + } + + /// ----------------------------------------------------------------------------- + /// + /// Updates a Permission. + /// + /// The permissions collection. + /// The user to add. + /// ----------------------------------------------------------------------------- + protected override void AddPermission(ArrayList permissions, UserInfo user) + { + bool isMatch = this._ModulePermissions.Cast() + .Any(objModulePermission => objModulePermission.UserID == user.UserID); + + // user not found so add new + if (!isMatch) + { + foreach (PermissionInfo objPermission in permissions) + { + if (objPermission.PermissionKey == "VIEW") + { + this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); + } + } + } + } /// ----------------------------------------------------------------------------- /// @@ -173,37 +213,6 @@ private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventA } } } - - protected override void CreateChildControls() - { - base.CreateChildControls(); - this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; - } - - /// ----------------------------------------------------------------------------- - /// - /// Updates a Permission. - /// - /// The permissions collection. - /// The user to add. - /// ----------------------------------------------------------------------------- - protected override void AddPermission(ArrayList permissions, UserInfo user) - { - bool isMatch = this._ModulePermissions.Cast() - .Any(objModulePermission => objModulePermission.UserID == user.UserID); - - // user not found so add new - if (!isMatch) - { - foreach (PermissionInfo objPermission in permissions) - { - if (objPermission.PermissionKey == "VIEW") - { - this.AddPermission(objPermission, int.Parse(Globals.glbRoleNothing), Null.NullString, user.UserID, user.DisplayName, true); - } - } - } - } /// ----------------------------------------------------------------------------- /// @@ -233,15 +242,15 @@ protected override void AddPermission(ArrayList permissions, RoleInfo role) protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) { - var objPermission = new ModulePermissionInfo(permission) - { - ModuleID = this.ModuleID, - RoleID = roleId, - RoleName = roleName, - AllowAccess = allowAccess, - UserID = userId, - DisplayName = displayName, - }; + var objPermission = new ModulePermissionInfo(permission) + { + ModuleID = this.ModuleID, + RoleID = roleId, + RoleName = roleName, + AllowAccess = allowAccess, + UserID = userId, + DisplayName = displayName, + }; this._ModulePermissions.Add(objPermission, true); // Clear Permission List @@ -540,14 +549,5 @@ protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; } - - /// ----------------------------------------------------------------------------- - /// - /// Overrides the Base method to Generate the Data Grid. - /// - /// ----------------------------------------------------------------------------- - public override void GenerateDataGrid() - { - } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs index b0bc3fb897e..33b514b4950 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs @@ -30,6 +30,8 @@ public abstract class PermissionsGrid : Control, INamingContainer protected const string PermissionTypeGrant = "True"; protected const string PermissionTypeDeny = "False"; protected const string PermissionTypeNull = "Null"; + protected DataGrid rolePermissionsGrid; + protected DataGrid userPermissionsGrid; private ArrayList _permissions; private ArrayList _users; private DropDownList cboRoleGroups; @@ -43,58 +45,15 @@ public abstract class PermissionsGrid : Control, INamingContainer private TextBox txtUser; private HiddenField hiddenUserIds; private HiddenField roleField; - protected DataGrid rolePermissionsGrid; - protected DataGrid userPermissionsGrid; - - public PermissionsGrid() - { - this.dtUserPermissions = new DataTable(); - this.dtRolePermissions = new DataTable(); - } private int unAuthUsersRoleId = int.Parse(Globals.glbRoleUnauthUser); - - private int UnAuthUsersRoleId - { - get { return this.unAuthUsersRoleId; } - } private int allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); - private int AllUsersRoleId - { - get - { - return this.allUsersRoleId; - } - } - - protected virtual List PermissionsList - { - get - { - return null; - } - } - - protected virtual bool RefreshGrid - { - get - { - return false; - } - } - - /// - /// Registers the scripts neccesary to make the tri-state controls work inside a RadAjaxPanel. - /// - /// - /// No need to call this unless using the PermissionGrid inside an ajax control that omits scripts on postback - /// See DesktopModules/Admin/Tabs.ascx.cs for an example of usage. - /// - public void RegisterScriptsForAjaxPanel() + public PermissionsGrid() { - PermissionTriState.RegisterScripts(this.Page, this); + this.dtUserPermissions = new DataTable(); + this.dtRolePermissions = new DataTable(); } public TableItemStyle AlternatingItemStyle @@ -132,6 +91,47 @@ public int CellSpacing this.userPermissionsGrid.CellSpacing = value; } } + + protected virtual List PermissionsList + { + get + { + return null; + } + } + + protected virtual bool RefreshGrid + { + get + { + return false; + } + } + + private int UnAuthUsersRoleId + { + get { return this.unAuthUsersRoleId; } + } + + private int AllUsersRoleId + { + get + { + return this.allUsersRoleId; + } + } + + /// + /// Registers the scripts neccesary to make the tri-state controls work inside a RadAjaxPanel. + /// + /// + /// No need to call this unless using the PermissionGrid inside an ajax control that omits scripts on postback + /// See DesktopModules/Admin/Tabs.ascx.cs for an example of usage. + /// + public void RegisterScriptsForAjaxPanel() + { + PermissionTriState.RegisterScripts(this.Page, this); + } public DataGridColumnCollection Columns { @@ -281,6 +281,19 @@ public int PortalId /// public abstract void GenerateDataGrid(); + protected virtual void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) + { + } + + /// + /// Updates a Permission. + /// + /// The permissions collection. + /// The user to add. + protected virtual void AddPermission(ArrayList permissions, UserInfo user) + { + } + private void BindData() { this.EnsureChildControls(); @@ -477,32 +490,32 @@ private IEnumerable GetCheckedRoles() private void SetUpGrid(DataGrid grid, string nameColumnDataField, string idColumnDataField, string permissionHeaderText) { grid.Columns.Clear(); - var nameColumn = new BoundColumn - { - HeaderText = permissionHeaderText, - DataField = nameColumnDataField, - }; + var nameColumn = new BoundColumn + { + HeaderText = permissionHeaderText, + DataField = nameColumnDataField, + }; nameColumn.ItemStyle.CssClass = "permissionHeader"; nameColumn.HeaderStyle.CssClass = "permissionHeader"; grid.Columns.Add(nameColumn); - var idColumn = new BoundColumn - { - HeaderText = string.Empty, - DataField = idColumnDataField, - Visible = false, - }; + var idColumn = new BoundColumn + { + HeaderText = string.Empty, + DataField = idColumnDataField, + Visible = false, + }; grid.Columns.Add(idColumn); foreach (PermissionInfo permission in this._permissions) { var templateCol = new TemplateColumn(); - var columnTemplate = new PermissionTriStateTemplate(permission) - { - IsFullControl = this.IsFullControl(permission), - IsView = this.IsViewPermisison(permission), - SupportDenyMode = this.SupportsDenyPermissions(permission), - }; + var columnTemplate = new PermissionTriStateTemplate(permission) + { + IsFullControl = this.IsFullControl(permission), + IsView = this.IsViewPermisison(permission), + SupportDenyMode = this.SupportsDenyPermissions(permission), + }; templateCol.ItemTemplate = columnTemplate; var locName = (permission.ModuleDefID <= 0) ? Localization.GetString(permission.PermissionName + ".Permission", PermissionProvider.Instance().LocalResourceFile) // system permission @@ -638,19 +651,6 @@ private void SetErrorMessage(string errorKey) }; this.pnlPermissions.Controls.Add(this.lblErrorMessage); } - - protected virtual void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) - { - } - - /// - /// Updates a Permission. - /// - /// The permissions collection. - /// The user to add. - protected virtual void AddPermission(ArrayList permissions, UserInfo user) - { - } /// /// Updates a Permission. @@ -781,6 +781,30 @@ protected override void CreateChildControls() this.Controls.Add(this.pnlPermissions); } + /// + /// Gets the Enabled status of the permission. + /// + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// + protected virtual bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) + { + return true; + } + + /// + /// Gets the Enabled status of the permission. + /// + /// The permission being loaded. + /// The user. + /// The column of the Grid. + /// + protected virtual bool GetEnabled(PermissionInfo objPerm, UserInfo user, int column) + { + return true; + } + private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) { var item = e.Item; @@ -844,30 +868,6 @@ private void CreateAddRoleControls() this.pnlPermissions.Controls.Add(addRoleControls); } - /// - /// Gets the Enabled status of the permission. - /// - /// The permission being loaded. - /// The role. - /// The column of the Grid. - /// - protected virtual bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) - { - return true; - } - - /// - /// Gets the Enabled status of the permission. - /// - /// The permission being loaded. - /// The user. - /// The column of the Grid. - /// - protected virtual bool GetEnabled(PermissionInfo objPerm, UserInfo user, int column) - { - return true; - } - /// /// Gets the Value of the permission. /// diff --git a/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs index ee482cdfb46..7254464461e 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs @@ -24,29 +24,6 @@ public class TabPermissionsGrid : PermissionsGrid private List _PermissionsList; private int _TabID = -1; private TabPermissionCollection _TabPermissions; - - protected override bool IsFullControl(PermissionInfo permissionInfo) - { - return (permissionInfo.PermissionKey == "EDIT") && PermissionProvider.Instance().SupportsFullControl(); - } - - protected override bool IsViewPermisison(PermissionInfo permissionInfo) - { - return permissionInfo.PermissionKey == "VIEW"; - } - - protected override List PermissionsList - { - get - { - if (this._PermissionsList == null && this._TabPermissions != null) - { - this._PermissionsList = this._TabPermissions.ToList(); - } - - return this._PermissionsList; - } - } /// ----------------------------------------------------------------------------- /// @@ -87,6 +64,60 @@ public int TabID } } + protected override List PermissionsList + { + get + { + if (this._PermissionsList == null && this._TabPermissions != null) + { + this._PermissionsList = this._TabPermissions.ToList(); + } + + return this._PermissionsList; + } + } + + protected override bool IsFullControl(PermissionInfo permissionInfo) + { + return (permissionInfo.PermissionKey == "EDIT") && PermissionProvider.Instance().SupportsFullControl(); + } + + protected override bool IsViewPermisison(PermissionInfo permissionInfo) + { + return permissionInfo.PermissionKey == "VIEW"; + } + + public override void DataBind() + { + this.GetTabPermissions(); + base.DataBind(); + } + + public override void GenerateDataGrid() + { + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; + } + + protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) + { + var objPermission = new TabPermissionInfo(permission); + objPermission.TabID = this.TabID; + objPermission.RoleID = roleId; + objPermission.RoleName = roleName; + objPermission.AllowAccess = allowAccess; + objPermission.UserID = userId; + objPermission.DisplayName = displayName; + this._TabPermissions.Add(objPermission, true); + + // Clear Permission List + this._PermissionsList = null; + } + /// ----------------------------------------------------------------------------- /// /// Gets the TabPermissions from the Data Store. @@ -98,12 +129,6 @@ private void GetTabPermissions() this._PermissionsList = null; } - public override void DataBind() - { - this.GetTabPermissions(); - base.DataBind(); - } - /// ----------------------------------------------------------------------------- /// /// Parse the Permission Keys used to persist the Permissions in the ViewState. @@ -153,27 +178,6 @@ private bool IsImplicitRole(int portalId, int roleId) return TabPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); } - protected override void CreateChildControls() - { - base.CreateChildControls(); - this.rolePermissionsGrid.ItemDataBound += this.rolePermissionsGrid_ItemDataBound; - } - - protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) - { - var objPermission = new TabPermissionInfo(permission); - objPermission.TabID = this.TabID; - objPermission.RoleID = roleId; - objPermission.RoleName = roleName; - objPermission.AllowAccess = allowAccess; - objPermission.UserID = userId; - objPermission.DisplayName = displayName; - this._TabPermissions.Add(objPermission, true); - - // Clear Permission List - this._PermissionsList = null; - } - /// ----------------------------------------------------------------------------- /// /// Updates a Permission. @@ -393,9 +397,5 @@ protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; } - - public override void GenerateDataGrid() - { - } } } diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs index f77429f106b..1daa26576e3 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs @@ -28,16 +28,6 @@ namespace DotNetNuke.Security.Permissions public class DesktopModulePermissionController { private static readonly PermissionProvider _provider = PermissionProvider.Instance(); - - /// ----------------------------------------------------------------------------- - /// - /// ClearPermissionCache clears the DesktopModule Permission Cache. - /// - /// ----------------------------------------------------------------------------- - private static void ClearPermissionCache() - { - DataCache.ClearDesktopModulePermissionsCache(); - } /// ----------------------------------------------------------------------------- /// @@ -83,6 +73,16 @@ public static void DeleteDesktopModulePermission(int DesktopModulePermissionID) ClearPermissionCache(); } + /// ----------------------------------------------------------------------------- + /// + /// ClearPermissionCache clears the DesktopModule Permission Cache. + /// + /// ----------------------------------------------------------------------------- + private static void ClearPermissionCache() + { + DataCache.ClearDesktopModulePermissionsCache(); + } + /// ----------------------------------------------------------------------------- /// /// DeleteDesktopModulePermissionsByPortalDesktopModuleID deletes a DesktopModule's diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs index d3b4f657eb4..5a8cab91ec0 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs @@ -92,19 +92,6 @@ public int PortalDesktopModuleID this._portalDesktopModuleID = value; } } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a DesktopModulePermissionInfo from a Data Reader. - /// - /// The Data Reader to use. - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - this.FillInternal(dr); - this.DesktopModulePermissionID = Null.SetNullInteger(dr["DesktopModulePermissionID"]); - this.PortalDesktopModuleID = Null.SetNullInteger(dr["PortalDesktopModuleID"]); - } /// ----------------------------------------------------------------------------- /// @@ -125,6 +112,19 @@ public int KeyID } } + /// ----------------------------------------------------------------------------- + /// + /// Fills a DesktopModulePermissionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.FillInternal(dr); + this.DesktopModulePermissionID = Null.SetNullInteger(dr["DesktopModulePermissionID"]); + this.PortalDesktopModuleID = Null.SetNullInteger(dr["PortalDesktopModuleID"]); + } + /// ----------------------------------------------------------------------------- /// /// Compares if two DesktopModulePermissionInfo objects are equivalent/equal. diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs index 5e20cef9fd7..b3db7f2d3b4 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs @@ -16,10 +16,25 @@ public partial class FolderPermissionController : ServiceLocator GetFactory() + /// + /// Returns a list with all roles with implicit permissions on Folders. + /// + /// The Portal Id where the Roles are. + /// A List with the implicit roles. + public static IEnumerable ImplicitRoles(int portalId) { - return () => new FolderPermissionController(); - } + return provider.ImplicitRolesForPages(portalId); + } + + /// + /// Returns a flag indicating whether the current user can add a folder or file. + /// + /// The page. + /// A flag indicating whether the user has permission. + public static bool CanAddFolder(FolderInfo folder) + { + return provider.CanAddFolder(folder); + } /// /// Returns a flag indicating whether the current user can add a folder or file. @@ -41,6 +56,11 @@ bool IFolderPermissionController.CanAdminFolder(IFolderInfo folder) return provider.CanAdminFolder((FolderInfo)folder); } + protected override Func GetFactory() + { + return () => new FolderPermissionController(); + } + /// /// Returns a flag indicating whether the current user can view a folder or file. /// @@ -58,26 +78,6 @@ private static void ClearPermissionCache(int PortalID) DataCache.ClearFolderCache(PortalID); } - /// - /// Returns a list with all roles with implicit permissions on Folders. - /// - /// The Portal Id where the Roles are. - /// A List with the implicit roles. - public static IEnumerable ImplicitRoles(int portalId) - { - return provider.ImplicitRolesForPages(portalId); - } - - /// - /// Returns a flag indicating whether the current user can add a folder or file. - /// - /// The page. - /// A flag indicating whether the user has permission. - public static bool CanAddFolder(FolderInfo folder) - { - return provider.CanAddFolder(folder); - } - /// /// Returns a flag indicating whether the current user can addmister a folder. /// @@ -193,26 +193,6 @@ public static void CopyPermissionsToSubfolders(IFolderInfo folder, FolderPermiss } } - private static bool CopyPermissionsToSubfoldersRecursive(IFolderInfo folder, FolderPermissionCollection newPermissions) - { - bool clearCache = Null.NullBoolean; - IEnumerable childFolders = FolderManager.Instance.GetFolders(folder); - foreach (var f in childFolders) - { - if (CanAdminFolder((FolderInfo)f)) - { - f.FolderPermissions.Clear(); - f.FolderPermissions.AddRange(newPermissions); - SaveFolderPermissions(f); - clearCache = true; - } - - clearCache = CopyPermissionsToSubfoldersRecursive(f, newPermissions) || clearCache; - } - - return clearCache; - } - /// ----------------------------------------------------------------------------- /// /// SaveFolderPermissions updates a Folder's permissions. @@ -233,5 +213,25 @@ public static void SaveFolderPermissions(IFolderInfo folder) provider.SaveFolderPermissions(folder); ClearPermissionCache(folder.PortalID); } + + private static bool CopyPermissionsToSubfoldersRecursive(IFolderInfo folder, FolderPermissionCollection newPermissions) + { + bool clearCache = Null.NullBoolean; + IEnumerable childFolders = FolderManager.Instance.GetFolders(folder); + foreach (var f in childFolders) + { + if (CanAdminFolder((FolderInfo)f)) + { + f.FolderPermissions.Clear(); + f.FolderPermissions.AddRange(newPermissions); + SaveFolderPermissions(f); + clearCache = true; + } + + clearCache = CopyPermissionsToSubfoldersRecursive(f, newPermissions) || clearCache; + } + + return clearCache; + } } } diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs index 6b0486b157e..bb5db6d1ba1 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs @@ -105,21 +105,6 @@ public string FolderPath this._folderPath = value; } } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a FolderPermissionInfo from a Data Reader. - /// - /// The Data Reader to use. - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - this.FillInternal(dr); - this.FolderPermissionID = Null.SetNullInteger(dr["FolderPermissionID"]); - this.FolderID = Null.SetNullInteger(dr["FolderID"]); - this.PortalID = Null.SetNullInteger(dr["PortalID"]); - this.FolderPath = Null.SetNullString(dr["FolderPath"]); - } /// ----------------------------------------------------------------------------- /// @@ -140,5 +125,20 @@ public int KeyID this.FolderPermissionID = value; } } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a FolderPermissionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.FillInternal(dr); + this.FolderPermissionID = Null.SetNullInteger(dr["FolderPermissionID"]); + this.FolderID = Null.SetNullInteger(dr["FolderID"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.FolderPath = Null.SetNullString(dr["FolderPath"]); + } } } diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs index a6123980b79..1f283bdc93e 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs @@ -28,12 +28,6 @@ public class ModulePermissionController { private static readonly PermissionProvider _provider = PermissionProvider.Instance(); - private static void ClearPermissionCache(int moduleId) - { - ModuleInfo objModule = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); - DataCache.ClearModulePermissionsCache(objModule.TabID); - } - /// /// Returns a list with all roles with implicit permissions on Modules. /// @@ -53,6 +47,12 @@ public static bool CanAdminModule(ModuleInfo module) { return _provider.CanAdminModule(module); } + + private static void ClearPermissionCache(int moduleId) + { + ModuleInfo objModule = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); + DataCache.ClearModulePermissionsCache(objModule.TabID); + } /// /// Returns a flag indicating whether the current user can delete a module. diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs index b488d7b9fa8..c4a650b033c 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs @@ -95,19 +95,6 @@ public int ModuleID this._moduleID = value; } } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a ModulePermissionInfo from a Data Reader. - /// - /// The Data Reader to use. - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - this.FillInternal(dr); - this.ModulePermissionID = Null.SetNullInteger(dr["ModulePermissionID"]); - this.ModuleID = Null.SetNullInteger(dr["ModuleID"]); - } /// ----------------------------------------------------------------------------- /// @@ -129,6 +116,19 @@ public int KeyID } } + /// ----------------------------------------------------------------------------- + /// + /// Fills a ModulePermissionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.FillInternal(dr); + this.ModulePermissionID = Null.SetNullInteger(dr["ModulePermissionID"]); + this.ModuleID = Null.SetNullInteger(dr["ModuleID"]); + } + /// ----------------------------------------------------------------------------- /// /// Compares if two ModulePermissionInfo objects are equivalent/equal. diff --git a/DNN Platform/Library/Security/Permissions/PermissionController.cs b/DNN Platform/Library/Security/Permissions/PermissionController.cs index bec0747f3fc..e021dee2301 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionController.cs @@ -22,21 +22,56 @@ namespace DotNetNuke.Security.Permissions public class PermissionController { private static readonly DataProvider provider = DataProvider.Instance(); - - private static IEnumerable GetPermissions() + + public static string BuildPermissions(IList Permissions, string PermissionKey) { - return CBO.GetCachedObject>( - new CacheItemArgs( - DataCache.PermissionsCacheKey, - DataCache.PermissionsCacheTimeout, - DataCache.PermissionsCachePriority), - c => CBO.FillCollection(provider.ExecuteReader("GetPermissions"))); + var permissionsBuilder = new StringBuilder(); + foreach (PermissionInfoBase permission in Permissions) + { + if (PermissionKey.Equals(permission.PermissionKey, StringComparison.InvariantCultureIgnoreCase)) + { + // Deny permissions are prefixed with a "!" + string prefix = !permission.AllowAccess ? "!" : string.Empty; + + // encode permission + string permissionString; + if (Null.IsNull(permission.UserID)) + { + permissionString = prefix + permission.RoleName + ";"; + } + else + { + permissionString = prefix + "[" + permission.UserID + "];"; + } + + // build permissions string ensuring that Deny permissions are inserted at the beginning and Grant permissions at the end + if (prefix == "!") + { + permissionsBuilder.Insert(0, permissionString); + } + else + { + permissionsBuilder.Append(permissionString); + } + } + } + + // get string + string permissionsString = permissionsBuilder.ToString(); + + // ensure leading delimiter + if (!permissionsString.StartsWith(";")) + { + permissionsString.Insert(0, ";"); + } + + return permissionsString; } - private void ClearCache() + public static ArrayList GetPermissionsByFolder() { - DataCache.RemoveCache(DataCache.PermissionsCacheKey); - } + return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_FOLDER").ToArray()); + } public int AddPermission(PermissionInfo permission) { @@ -64,6 +99,21 @@ public void DeletePermission(int permissionID) this.ClearCache(); } + private static IEnumerable GetPermissions() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PermissionsCacheKey, + DataCache.PermissionsCacheTimeout, + DataCache.PermissionsCachePriority), + c => CBO.FillCollection(provider.ExecuteReader("GetPermissions"))); + } + + private void ClearCache() + { + DataCache.RemoveCache(DataCache.PermissionsCacheKey); + } + public PermissionInfo GetPermission(int permissionID) { return GetPermissions().SingleOrDefault(p => p.PermissionID == permissionID); @@ -99,56 +149,6 @@ public void UpdatePermission(PermissionInfo permission) UserController.Instance.GetCurrentUserInfo().UserID); this.ClearCache(); } - - public static string BuildPermissions(IList Permissions, string PermissionKey) - { - var permissionsBuilder = new StringBuilder(); - foreach (PermissionInfoBase permission in Permissions) - { - if (PermissionKey.Equals(permission.PermissionKey, StringComparison.InvariantCultureIgnoreCase)) - { - // Deny permissions are prefixed with a "!" - string prefix = !permission.AllowAccess ? "!" : string.Empty; - - // encode permission - string permissionString; - if (Null.IsNull(permission.UserID)) - { - permissionString = prefix + permission.RoleName + ";"; - } - else - { - permissionString = prefix + "[" + permission.UserID + "];"; - } - - // build permissions string ensuring that Deny permissions are inserted at the beginning and Grant permissions at the end - if (prefix == "!") - { - permissionsBuilder.Insert(0, permissionString); - } - else - { - permissionsBuilder.Append(permissionString); - } - } - } - - // get string - string permissionsString = permissionsBuilder.ToString(); - - // ensure leading delimiter - if (!permissionsString.StartsWith(";")) - { - permissionsString.Insert(0, ";"); - } - - return permissionsString; - } - - public static ArrayList GetPermissionsByFolder() - { - return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_FOLDER").ToArray()); - } public static ArrayList GetPermissionsByPortalDesktopModule() { diff --git a/DNN Platform/Library/Security/Permissions/PermissionProvider.cs b/DNN Platform/Library/Security/Permissions/PermissionProvider.cs index 47dbd321b79..34f530af235 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionProvider.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionProvider.cs @@ -54,6 +54,8 @@ public class PermissionProvider private const string ManagePagePermissionKey = "EDIT"; private const string NavigatePagePermissionKey = "VIEW"; private const string ViewPagePermissionKey = "VIEW"; + private static SharedDictionary _cacheDependencyDict = new SharedDictionary(); + private readonly DataProvider dataProvider = DataProvider.Instance(); // return the provider @@ -69,52 +71,104 @@ public static PermissionProvider Instance() { return ComponentFactory.GetComponent(); } + + public virtual bool SupportsFullControl() + { + return true; + } - private static SharedDictionary _cacheDependencyDict = new SharedDictionary(); + /// + /// The portal editor can edit whole site's content, it should be only administrators by default. + /// + /// + public virtual bool IsPortalEditor() + { + var settings = PortalController.Instance.GetCurrentPortalSettings(); + return settings != null && PortalSecurity.IsInRole(settings.AdministratorRoleName); + } - private static DNNCacheDependency GetCacheDependency(int portalId) + internal static void ResetCacheDependency(int portalId, Action cacehClearAction) { + // first execute the cache clear action then check the dependency change + cacehClearAction.Invoke(); DNNCacheDependency dependency; using (_cacheDependencyDict.GetReadLock()) { _cacheDependencyDict.TryGetValue(portalId, out dependency); } - - if (dependency == null) + + if (dependency != null) { - var startAt = DateTime.UtcNow; - var cacheKey = string.Format(DataCache.FolderPermissionCacheKey, portalId); - DataCache.SetCache(cacheKey, portalId); // no expiration set for this - dependency = new DNNCacheDependency(null, new[] { cacheKey }, startAt); using (_cacheDependencyDict.GetWriteLock()) { - _cacheDependencyDict[portalId] = dependency; + _cacheDependencyDict.Remove(portalId); } + + dependency.Dispose(); } + } - return dependency; + protected bool HasModulePermission(ModuleInfo moduleConfiguration, string permissionKey) + { + return this.CanViewModule(moduleConfiguration) && + (this.HasModulePermission(moduleConfiguration.ModulePermissions, permissionKey) + || this.HasModulePermission(moduleConfiguration.ModulePermissions, "EDIT")); } - internal static void ResetCacheDependency(int portalId, Action cacehClearAction) + protected bool IsDeniedModulePermission(ModuleInfo moduleConfiguration, string permissionKey) + { + return this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, "VIEW") + || this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, permissionKey) + || this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, "EDIT"); + } + + private static DNNCacheDependency GetCacheDependency(int portalId) { - // first execute the cache clear action then check the dependency change - cacehClearAction.Invoke(); DNNCacheDependency dependency; using (_cacheDependencyDict.GetReadLock()) { _cacheDependencyDict.TryGetValue(portalId, out dependency); } - - if (dependency != null) + + if (dependency == null) { + var startAt = DateTime.UtcNow; + var cacheKey = string.Format(DataCache.FolderPermissionCacheKey, portalId); + DataCache.SetCache(cacheKey, portalId); // no expiration set for this + dependency = new DNNCacheDependency(null, new[] { cacheKey }, startAt); using (_cacheDependencyDict.GetWriteLock()) { - _cacheDependencyDict.Remove(portalId); + _cacheDependencyDict[portalId] = dependency; } - - dependency.Dispose(); } - } + + return dependency; + } + + /// ----------------------------------------------------------------------------- + /// + /// GetDesktopModulePermissions gets a Dictionary of DesktopModulePermissionCollections by + /// DesktopModule. + /// + /// ----------------------------------------------------------------------------- + private static Dictionary GetDesktopModulePermissions() + { + return CBO.GetCachedObject>( + new CacheItemArgs(DataCache.DesktopModulePermissionCacheKey, DataCache.DesktopModulePermissionCachePriority), GetDesktopModulePermissionsCallBack); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetDesktopModulePermissionsCallBack gets a Dictionary of DesktopModulePermissionCollections by + /// DesktopModule from the the Database. + /// + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. + /// ----------------------------------------------------------------------------- + private static object GetDesktopModulePermissionsCallBack(CacheItemArgs cacheItemArgs) + { + return FillDesktopModulePermissionDictionary(DataProvider.Instance().GetDesktopModulePermissions()); + } #if false private object GetFolderPermissionsCallBack(CacheItemArgs cacheItemArgs) @@ -373,31 +427,6 @@ private bool IsDeniedTabPermission(TabPermissionCollection tabPermissions, strin return isDenied; } - /// ----------------------------------------------------------------------------- - /// - /// GetDesktopModulePermissions gets a Dictionary of DesktopModulePermissionCollections by - /// DesktopModule. - /// - /// ----------------------------------------------------------------------------- - private static Dictionary GetDesktopModulePermissions() - { - return CBO.GetCachedObject>( - new CacheItemArgs(DataCache.DesktopModulePermissionCacheKey, DataCache.DesktopModulePermissionCachePriority), GetDesktopModulePermissionsCallBack); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetDesktopModulePermissionsCallBack gets a Dictionary of DesktopModulePermissionCollections by - /// DesktopModule from the the Database. - /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call. - /// ----------------------------------------------------------------------------- - private static object GetDesktopModulePermissionsCallBack(CacheItemArgs cacheItemArgs) - { - return FillDesktopModulePermissionDictionary(DataProvider.Instance().GetDesktopModulePermissions()); - } - /// ----------------------------------------------------------------------------- /// /// FillDesktopModulePermissionDictionary fills a Dictionary of DesktopModulePermissions from a @@ -453,20 +482,6 @@ private IEnumerable DefaultImplicitRoles(int portalId) PortalController.Instance.GetPortal(portalId).AdministratorRoleId), }; } - - protected bool HasModulePermission(ModuleInfo moduleConfiguration, string permissionKey) - { - return this.CanViewModule(moduleConfiguration) && - (this.HasModulePermission(moduleConfiguration.ModulePermissions, permissionKey) - || this.HasModulePermission(moduleConfiguration.ModulePermissions, "EDIT")); - } - - protected bool IsDeniedModulePermission(ModuleInfo moduleConfiguration, string permissionKey) - { - return this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, "VIEW") - || this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, permissionKey) - || this.IsDeniedModulePermission(moduleConfiguration.ModulePermissions, "EDIT"); - } protected bool IsDeniedTabPermission(TabInfo tab, string permissionKey) { @@ -475,21 +490,6 @@ protected bool IsDeniedTabPermission(TabInfo tab, string permissionKey) || this.IsDeniedTabPermission(tab.TabPermissions, "EDIT"); } - public virtual bool SupportsFullControl() - { - return true; - } - - /// - /// The portal editor can edit whole site's content, it should be only administrators by default. - /// - /// - public virtual bool IsPortalEditor() - { - var settings = PortalController.Instance.GetCurrentPortalSettings(); - return settings != null && PortalSecurity.IsInRole(settings.AdministratorRoleName); - } - /// /// Returns a flag indicating whether the current user can add a folder or file. /// @@ -674,24 +674,24 @@ public virtual void SaveFolderPermissions(IFolderInfo folder) if (folderPermission.PermissionKey != "BROWSE" && folderPermission.PermissionKey != "READ" && folderPermission.AllowAccess) { // Try to add Read permission - var newFolderPerm = new FolderPermissionInfo(readPerm) - { - FolderID = folderPermission.FolderID, - RoleID = folderPermission.RoleID, - UserID = folderPermission.UserID, - AllowAccess = true, - }; + var newFolderPerm = new FolderPermissionInfo(readPerm) + { + FolderID = folderPermission.FolderID, + RoleID = folderPermission.RoleID, + UserID = folderPermission.UserID, + AllowAccess = true, + }; additionalPermissions.Add(newFolderPerm); // Try to add Browse permission - newFolderPerm = new FolderPermissionInfo(browsePerm) - { - FolderID = folderPermission.FolderID, - RoleID = folderPermission.RoleID, - UserID = folderPermission.UserID, - AllowAccess = true, - }; + newFolderPerm = new FolderPermissionInfo(browsePerm) + { + FolderID = folderPermission.FolderID, + RoleID = folderPermission.RoleID, + UserID = folderPermission.UserID, + AllowAccess = true, + }; additionalPermissions.Add(newFolderPerm); } diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionController.cs b/DNN Platform/Library/Security/Permissions/TabPermissionController.cs index 1cb2b1702b1..161178e85f9 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionController.cs @@ -26,12 +26,6 @@ namespace DotNetNuke.Security.Permissions /// ----------------------------------------------------------------------------- public class TabPermissionController { - private static void ClearPermissionCache(int tabId) - { - var objTab = TabController.Instance.GetTab(tabId, Null.NullInteger, false); - DataCache.ClearTabPermissionsCache(objTab.PortalID); - } - private static readonly PermissionProvider _provider = PermissionProvider.Instance(); /// @@ -52,6 +46,12 @@ public static bool CanAddContentToPage() { return CanAddContentToPage(TabController.CurrentPage); } + + private static void ClearPermissionCache(int tabId) + { + var objTab = TabController.Instance.GetTab(tabId, Null.NullInteger, false); + DataCache.ClearTabPermissionsCache(objTab.PortalID); + } /// /// Returns a flag indicating whether the current user can add content to a page. diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs b/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs index 9d187349577..2b09229797d 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs @@ -96,20 +96,6 @@ public int TabID this._TabID = value; } } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a TabPermissionInfo from a Data Reader. - /// - /// The Data Reader to use. - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - // Call the base classes fill method to ppoulate base class proeprties - this.FillInternal(dr); - this.TabPermissionID = Null.SetNullInteger(dr["TabPermissionID"]); - this.TabID = Null.SetNullInteger(dr["TabID"]); - } /// ----------------------------------------------------------------------------- /// @@ -130,5 +116,19 @@ public int KeyID this.TabPermissionID = value; } } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a TabPermissionInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + // Call the base classes fill method to ppoulate base class proeprties + this.FillInternal(dr); + this.TabPermissionID = Null.SetNullInteger(dr["TabPermissionID"]); + this.TabID = Null.SetNullInteger(dr["TabID"]); + } } } diff --git a/DNN Platform/Library/Security/PortalSecurity.cs b/DNN Platform/Library/Security/PortalSecurity.cs index 155a1641459..ae44808f205 100644 --- a/DNN Platform/Library/Security/PortalSecurity.cs +++ b/DNN Platform/Library/Security/PortalSecurity.cs @@ -31,14 +31,14 @@ public class PortalSecurity private const string RoleFollowerPrefix = "FOLLOWER:"; private const string RoleOwnerPrefix = "OWNER:"; + private const string BadStatementExpression = ";|--|\bcreate\b|\bdrop\b|\bselect\b|\binsert\b|\bdelete\b|\bupdate\b|\bunion\b|sp_|xp_|\bexec\b|\bexecute\b|/\\*.*\\*/|\bdeclare\b|\bwaitfor\b|%|&"; + + private const RegexOptions RxOptions = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled; + private static readonly DateTime OldExpiryTime = new DateTime(1999, 1, 1); private static readonly Regex StripTagsRegex = new Regex("<[^<>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); - - private const string BadStatementExpression = ";|--|\bcreate\b|\bdrop\b|\bselect\b|\binsert\b|\bdelete\b|\bupdate\b|\bunion\b|sp_|xp_|\bexec\b|\bexecute\b|/\\*.*\\*/|\bdeclare\b|\bwaitfor\b|%|&"; private static readonly Regex BadStatementRegex = new Regex(BadStatementExpression, RegexOptions.IgnoreCase | RegexOptions.Compiled); - - private const RegexOptions RxOptions = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled; private static readonly Regex[] RxListStrings = new[] { new Regex("]*>.*?<]*>", RxOptions), @@ -134,6 +134,86 @@ private enum RoleType Owner, } + public static void ForceSecureConnection() + { + // get current url + var url = HttpContext.Current.Request.Url.ToString(); + + // if unsecure connection + if (url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) + { + // switch to secure connection + url = "https://" + url.Substring("http://".Length); + + // append ssl parameter to querystring to indicate secure connection processing has already occurred + if (url.IndexOf("?", StringComparison.Ordinal) == -1) + { + url = url + "?ssl=1"; + } + else + { + url = url + "&ssl=1"; + } + + // redirect to secure connection + HttpContext.Current.Response.Redirect(url, true); + } + } + + public static string GetCookieDomain(int portalId) + { + string cookieDomain = string.Empty; + if (PortalController.IsMemberOfPortalGroup(portalId)) + { + // set cookie domain for portal group + var groupController = new PortalGroupController(); + var group = groupController.GetPortalGroups().SingleOrDefault(p => p.MasterPortalId == PortalController.GetEffectivePortalId(portalId)); + + if (@group != null + && !string.IsNullOrEmpty(@group.AuthenticationDomain) + && PortalSettings.Current.PortalAlias.HTTPAlias.Contains(@group.AuthenticationDomain)) + { + cookieDomain = @group.AuthenticationDomain; + } + + if (string.IsNullOrEmpty(cookieDomain)) + { + cookieDomain = FormsAuthentication.CookieDomain; + } + } + else + { + // set cookie domain to be consistent with domain specification in web.config + cookieDomain = FormsAuthentication.CookieDomain; + } + + return cookieDomain; + } + + /// ----------------------------------------------------------------------------- + /// + /// This function creates a random key. + /// + /// This is the number of bytes for the key. + /// A random string. + /// + /// This is a public function used for generating SHA1 keys. + /// + public string CreateKey(int numBytes) + { + using (var rng = new RNGCryptoServiceProvider()) + { + var buff = new byte[numBytes]; + rng.GetBytes(buff); + return BytesToHexString(buff); + } + } + + public string Decrypt(string strKey, string strData) + { + return CryptographyProvider.Instance().DecryptParameter(strData, strKey); + } + private static void ProcessRole(UserInfo user, PortalSettings settings, string roleName, out bool? roleAllowed) { var roleType = GetRoleType(roleName); @@ -311,9 +391,7 @@ private static string FilterStrings(string strInput) /// ----------------------------------------------------------------------------- /// - /// This function uses Regex search strings to remove HTML tags which are - /// targeted in Cross-site scripting (XSS) attacks. This function will evolve - /// to provide more robust checking as additional holes are found. + /// This filter removes angle brackets i.e. /// /// This is the string to be filtered. /// Filtered UserInput. @@ -321,16 +399,15 @@ private static string FilterStrings(string strInput) /// This is a private function that is used internally by the InputFilter function. /// /// ----------------------------------------------------------------------------- - private string FormatDisableScripting(string strInput) + private static string FormatAngleBrackets(string strInput) { - return string.IsNullOrWhiteSpace(strInput) - ? strInput - : FilterStrings(strInput); + var tempInput = new StringBuilder(strInput).Replace("<", string.Empty).Replace(">", string.Empty); + return tempInput.ToString(); } /// ----------------------------------------------------------------------------- /// - /// This filter removes angle brackets i.e. + /// This filter removes CrLf characters and inserts br. /// /// This is the string to be filtered. /// Filtered UserInput. @@ -338,15 +415,18 @@ private string FormatDisableScripting(string strInput) /// This is a private function that is used internally by the InputFilter function. /// /// ----------------------------------------------------------------------------- - private static string FormatAngleBrackets(string strInput) + private static string FormatMultiLine(string strInput) { - var tempInput = new StringBuilder(strInput).Replace("<", string.Empty).Replace(">", string.Empty); + const string lbreak = "
"; + var tempInput = new StringBuilder(strInput).Replace("\r\n", lbreak).Replace("\n", lbreak).Replace("\r", lbreak); return tempInput.ToString(); } /// ----------------------------------------------------------------------------- /// - /// This filter removes CrLf characters and inserts br. + /// This function uses Regex search strings to remove HTML tags which are + /// targeted in Cross-site scripting (XSS) attacks. This function will evolve + /// to provide more robust checking as additional holes are found. /// /// This is the string to be filtered. /// Filtered UserInput. @@ -354,11 +434,11 @@ private static string FormatAngleBrackets(string strInput) /// This is a private function that is used internally by the InputFilter function. /// /// ----------------------------------------------------------------------------- - private static string FormatMultiLine(string strInput) + private string FormatDisableScripting(string strInput) { - const string lbreak = "
"; - var tempInput = new StringBuilder(strInput).Replace("\r\n", lbreak).Replace("\n", lbreak).Replace("\r", lbreak); - return tempInput.ToString(); + return string.IsNullOrWhiteSpace(strInput) + ? strInput + : FilterStrings(strInput); } /// ----------------------------------------------------------------------------- @@ -392,30 +472,6 @@ private static bool IncludesMarkup(string strInput) { return StripTagsRegex.IsMatch(strInput); } - - /// ----------------------------------------------------------------------------- - /// - /// This function creates a random key. - /// - /// This is the number of bytes for the key. - /// A random string. - /// - /// This is a public function used for generating SHA1 keys. - /// - public string CreateKey(int numBytes) - { - using (var rng = new RNGCryptoServiceProvider()) - { - var buff = new byte[numBytes]; - rng.GetBytes(buff); - return BytesToHexString(buff); - } - } - - public string Decrypt(string strKey, string strData) - { - return CryptographyProvider.Instance().DecryptParameter(strData, strKey); - } public string DecryptString(string message, string passphrase) { @@ -785,16 +841,6 @@ public void SignOut() } } - private static void InvalidateAspNetSession(HttpContext context) - { - if (context.Session != null && !context.Session.IsNewSession) - { - // invalidate existing session so a new one is created - context.Session.Clear(); - context.Session.Abandon(); - } - } - /// ----------------------------------------------------------------------------- /// /// This function applies security filtering to the UserInput string, and reports @@ -835,61 +881,15 @@ public void CheckAllPortalFileExtensionWhitelists(string newMasterList) } } } - - public static void ForceSecureConnection() - { - // get current url - var url = HttpContext.Current.Request.Url.ToString(); - - // if unsecure connection - if (url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) - { - // switch to secure connection - url = "https://" + url.Substring("http://".Length); - - // append ssl parameter to querystring to indicate secure connection processing has already occurred - if (url.IndexOf("?", StringComparison.Ordinal) == -1) - { - url = url + "?ssl=1"; - } - else - { - url = url + "&ssl=1"; - } - - // redirect to secure connection - HttpContext.Current.Response.Redirect(url, true); - } - } - public static string GetCookieDomain(int portalId) + private static void InvalidateAspNetSession(HttpContext context) { - string cookieDomain = string.Empty; - if (PortalController.IsMemberOfPortalGroup(portalId)) - { - // set cookie domain for portal group - var groupController = new PortalGroupController(); - var group = groupController.GetPortalGroups().SingleOrDefault(p => p.MasterPortalId == PortalController.GetEffectivePortalId(portalId)); - - if (@group != null - && !string.IsNullOrEmpty(@group.AuthenticationDomain) - && PortalSettings.Current.PortalAlias.HTTPAlias.Contains(@group.AuthenticationDomain)) - { - cookieDomain = @group.AuthenticationDomain; - } - - if (string.IsNullOrEmpty(cookieDomain)) - { - cookieDomain = FormsAuthentication.CookieDomain; - } - } - else + if (context.Session != null && !context.Session.IsNewSession) { - // set cookie domain to be consistent with domain specification in web.config - cookieDomain = FormsAuthentication.CookieDomain; + // invalidate existing session so a new one is created + context.Session.Clear(); + context.Session.Abandon(); } - - return cookieDomain; } public static bool IsDenied(string roles) diff --git a/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs b/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs index 66dde717246..b60d41b4d1c 100644 --- a/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs +++ b/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs @@ -35,34 +35,6 @@ public class DNNProfileProvider : ProfileProvider { private readonly DataProvider _dataProvider = DataProvider.Instance(); - private void UpdateTimeZoneInfo(UserInfo user, ProfilePropertyDefinitionCollection properties) - { - ProfilePropertyDefinition newTimeZone = properties["PreferredTimeZone"]; - ProfilePropertyDefinition oldTimeZone = properties["TimeZone"]; - if (newTimeZone != null && oldTimeZone != null) - { - // Old timezone is present but new is not...we will set that up. - if (!string.IsNullOrEmpty(oldTimeZone.PropertyValue) && string.IsNullOrEmpty(newTimeZone.PropertyValue)) - { - int oldOffset; - int.TryParse(oldTimeZone.PropertyValue, out oldOffset); - TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(oldOffset); - newTimeZone.PropertyValue = timeZoneInfo.Id; - this.UpdateUserProfile(user); - } - - // It's also possible that the new value is set but not the old value. We need to make them backwards compatible - else if (!string.IsNullOrEmpty(newTimeZone.PropertyValue) && string.IsNullOrEmpty(oldTimeZone.PropertyValue)) - { - TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(newTimeZone.PropertyValue); - if (timeZoneInfo != null) - { - oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); - } - } - } - } - /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether the Provider Properties can be edited. @@ -214,6 +186,34 @@ public override void UpdateUserProfile(UserInfo user) } } + private void UpdateTimeZoneInfo(UserInfo user, ProfilePropertyDefinitionCollection properties) + { + ProfilePropertyDefinition newTimeZone = properties["PreferredTimeZone"]; + ProfilePropertyDefinition oldTimeZone = properties["TimeZone"]; + if (newTimeZone != null && oldTimeZone != null) + { + // Old timezone is present but new is not...we will set that up. + if (!string.IsNullOrEmpty(oldTimeZone.PropertyValue) && string.IsNullOrEmpty(newTimeZone.PropertyValue)) + { + int oldOffset; + int.TryParse(oldTimeZone.PropertyValue, out oldOffset); + TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(oldOffset); + newTimeZone.PropertyValue = timeZoneInfo.Id; + this.UpdateUserProfile(user); + } + + // It's also possible that the new value is set but not the old value. We need to make them backwards compatible + else if (!string.IsNullOrEmpty(newTimeZone.PropertyValue) && string.IsNullOrEmpty(oldTimeZone.PropertyValue)) + { + TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(newTimeZone.PropertyValue); + if (timeZoneInfo != null) + { + oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); + } + } + } + } + private string GetProfileCacheKey(UserInfo user) { return string.Format(DataCache.UserProfileCacheKey, user.PortalID, user.Username); diff --git a/DNN Platform/Library/Security/RegistrationSettings.cs b/DNN Platform/Library/Security/RegistrationSettings.cs index 489397214f1..40a0e848878 100644 --- a/DNN Platform/Library/Security/RegistrationSettings.cs +++ b/DNN Platform/Library/Security/RegistrationSettings.cs @@ -12,44 +12,6 @@ namespace DotNetNuke.Security public class RegistrationSettings { - public bool RandomPassword { get; set; } - - public int RedirectAfterRegistration { get; set; } - - public int RedirectAfterLogout { get; set; } - - public int RedirectAfterLogin { get; set; } - - public string RegistrationFields { get; set; } - - public string ExcludeTerms { get; set; } - - public string ExcludeTermsRegex { get; set; } - - public int RegistrationFormType { get; set; } - - public bool RequirePasswordConfirm { get; set; } - - public bool RequireUniqueDisplayName { get; set; } - - public bool UseAuthProviders { get; set; } - - public bool UseEmailAsUserName { get; set; } - - public bool UseProfanityFilter { get; set; } - - public bool RequireValidProfile { get; set; } - - public bool RequireValidProfileAtLogin { get; set; } - - public bool UseCaptcha { get; set; } - - public string UserNameValidator { get; set; } - - public string DisplayNameFormat { get; set; } - - public string EmailValidator { get; set; } - public RegistrationSettings() { this.RandomPassword = false; @@ -97,5 +59,43 @@ public RegistrationSettings(Dictionary settings) this.ExcludeTermsRegex = "^(?:(?!" + this.ExcludeTerms.Replace(" ", string.Empty).Replace(",", "|") + ").)*$\\r?\\n?"; } + + public bool RandomPassword { get; set; } + + public int RedirectAfterRegistration { get; set; } + + public int RedirectAfterLogout { get; set; } + + public int RedirectAfterLogin { get; set; } + + public string RegistrationFields { get; set; } + + public string ExcludeTerms { get; set; } + + public string ExcludeTermsRegex { get; set; } + + public int RegistrationFormType { get; set; } + + public bool RequirePasswordConfirm { get; set; } + + public bool RequireUniqueDisplayName { get; set; } + + public bool UseAuthProviders { get; set; } + + public bool UseEmailAsUserName { get; set; } + + public bool UseProfanityFilter { get; set; } + + public bool RequireValidProfile { get; set; } + + public bool RequireValidProfileAtLogin { get; set; } + + public bool UseCaptcha { get; set; } + + public string UserNameValidator { get; set; } + + public string DisplayNameFormat { get; set; } + + public string EmailValidator { get; set; } } } diff --git a/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs b/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs index 4fd0b6a8a41..80f2a252687 100644 --- a/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs +++ b/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs @@ -35,15 +35,6 @@ public class DNNRoleProvider : RoleProvider private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DNNRoleProvider)); private readonly DataProvider dataProvider = DataProvider.Instance(); - private void AddDNNUserRole(UserRoleInfo userRole) - { - // Add UserRole to DNN - userRole.UserRoleID = Convert.ToInt32(this.dataProvider.AddUserRole(userRole.PortalID, userRole.UserID, userRole.RoleID, - (int)userRole.Status, userRole.IsOwner, - userRole.EffectiveDate, userRole.ExpiryDate, - UserController.Instance.GetCurrentUserInfo().UserID)); - } - /// ----------------------------------------------------------------------------- /// /// CreateRole persists a Role to the Data Store. @@ -98,6 +89,15 @@ public override void DeleteRole(RoleInfo role) { this.dataProvider.DeleteRole(role.RoleID); } + + private void AddDNNUserRole(UserRoleInfo userRole) + { + // Add UserRole to DNN + userRole.UserRoleID = Convert.ToInt32(this.dataProvider.AddUserRole(userRole.PortalID, userRole.UserID, userRole.RoleID, + (int)userRole.Status, userRole.IsOwner, + userRole.EffectiveDate, userRole.ExpiryDate, + UserController.Instance.GetCurrentUserInfo().UserID)); + } /// ----------------------------------------------------------------------------- /// @@ -305,16 +305,6 @@ public override void UpdateUserRole(UserRoleInfo userRole) userRole.EffectiveDate, userRole.ExpiryDate, UserController.Instance.GetCurrentUserInfo().UserID); } - - private void ClearRoleGroupCache(int portalId) - { - DataCache.ClearCache(this.GetRoleGroupsCacheKey(portalId)); - } - - private string GetRoleGroupsCacheKey(int portalId) - { - return string.Format(DataCache.RoleGroupsCacheKey, portalId); - } /// ----------------------------------------------------------------------------- /// @@ -345,6 +335,16 @@ public override void DeleteRoleGroup(RoleGroupInfo roleGroup) this.dataProvider.DeleteRoleGroup(roleGroup.RoleGroupID); this.ClearRoleGroupCache(roleGroup.PortalID); } + + private void ClearRoleGroupCache(int portalId) + { + DataCache.ClearCache(this.GetRoleGroupsCacheKey(portalId)); + } + + private string GetRoleGroupsCacheKey(int portalId) + { + return string.Format(DataCache.RoleGroupsCacheKey, portalId); + } /// ----------------------------------------------------------------------------- /// @@ -378,17 +378,6 @@ public override ArrayList GetRoleGroups(int portalId) return new ArrayList(this.GetRoleGroupsInternal(portalId).ToList()); } - private IEnumerable GetRoleGroupsInternal(int portalId) - { - var cacheArgs = new CacheItemArgs( - this.GetRoleGroupsCacheKey(portalId), - DataCache.RoleGroupsCacheTimeOut, - DataCache.RoleGroupsCachePriority); - - return CBO.GetCachedObject>(cacheArgs, c => - CBO.FillCollection(this.dataProvider.GetRoleGroups(portalId))); - } - /// ----------------------------------------------------------------------------- /// /// Update a RoleGroup. @@ -401,5 +390,16 @@ public override void UpdateRoleGroup(RoleGroupInfo roleGroup) (roleGroup.Description ?? string.Empty).Trim(), UserController.Instance.GetCurrentUserInfo().UserID); this.ClearRoleGroupCache(roleGroup.PortalID); } + + private IEnumerable GetRoleGroupsInternal(int portalId) + { + var cacheArgs = new CacheItemArgs( + this.GetRoleGroupsCacheKey(portalId), + DataCache.RoleGroupsCacheTimeOut, + DataCache.RoleGroupsCachePriority); + + return CBO.GetCachedObject>(cacheArgs, c => + CBO.FillCollection(this.dataProvider.GetRoleGroups(portalId))); + } } } diff --git a/DNN Platform/Library/Security/Roles/RoleController.cs b/DNN Platform/Library/Security/Roles/RoleController.cs index dfba33df3cc..20a86ec9aff 100644 --- a/DNN Platform/Library/Security/Roles/RoleController.cs +++ b/DNN Platform/Library/Security/Roles/RoleController.cs @@ -44,43 +44,98 @@ private enum UserRoleActions update = 1, delete = 2, } + + /// ----------------------------------------------------------------------------- + /// + /// Adds a Role Group. + /// + /// The RoleGroup to Add. + /// The Id of the new role. + /// ----------------------------------------------------------------------------- + public static int AddRoleGroup(RoleGroupInfo objRoleGroupInfo) + { + var id = provider.CreateRoleGroup(objRoleGroupInfo); + EventLogController.Instance.AddLog(objRoleGroupInfo, PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_CREATED); + return id; + } - protected override Func GetFactory() + /// + /// Adds a User to a Role. + /// + /// The user to assign. + /// The role to add. + /// The PortalSettings of the Portal. + /// RoleStatus. + /// The expiry Date of the Role membership. + /// The expiry Date of the Role membership. + /// A flag that indicates whether the user should be notified. + /// A flag that indicates whether this user should be one of the group owners. + public static void AddUserRole(UserInfo user, RoleInfo role, PortalSettings portalSettings, RoleStatus status, DateTime effectiveDate, DateTime expiryDate, bool notifyUser, bool isOwner) { - return () => new RoleController(); - } + var userRole = Instance.GetUserRole(portalSettings.PortalId, user.UserID, role.RoleID); + + // update assignment + Instance.AddUserRole(portalSettings.PortalId, user.UserID, role.RoleID, status, isOwner, effectiveDate, expiryDate); + + UserController.UpdateUser(portalSettings.PortalId, user); + if (userRole == null) + { + EventLogController.Instance.AddLog("Role", role.RoleName, portalSettings, user.UserID, EventLogController.EventLogType.USER_ROLE_CREATED); + + // send notification + if (notifyUser) + { + SendNotification(user, role, portalSettings, UserRoleActions.@add); + } + } + else + { + EventLogController.Instance.AddLog("Role", role.RoleName, portalSettings, user.UserID, EventLogController.EventLogType.USER_ROLE_UPDATED); + if (notifyUser) + { + RoleController.Instance.GetUserRole(portalSettings.PortalId, user.UserID, role.RoleID); + SendNotification(user, role, portalSettings, UserRoleActions.update); + } + } + + // Remove the UserInfo from the Cache, as it has been modified + DataCache.ClearUserCache(portalSettings.PortalId, user.Username); + } - private void AddMessage(RoleInfo roleInfo, EventLogController.EventLogType logType) + public int AddRole(RoleInfo role) { - EventLogController.Instance.AddLog( - roleInfo, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - string.Empty, - logType); + return Instance.AddRole(role, true); } - private void AutoAssignUsers(RoleInfo role) + int IRoleController.AddRole(RoleInfo role, bool addToExistUsers) { - if (role.AutoAssignment) + Requires.NotNull("role", role); + + var roleId = -1; + if (provider.CreateRole(role)) { - // loop through users for portal and add to role - var arrUsers = UserController.GetUsers(role.PortalID); - foreach (UserInfo objUser in arrUsers) + this.AddMessage(role, EventLogController.EventLogType.ROLE_CREATED); + if (addToExistUsers) { - try - { - this.AddUserRole(role.PortalID, objUser.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); - } - catch (Exception exc) - { - // user already belongs to role - Logger.Error(exc); - } + this.AutoAssignUsers(role); } + + roleId = role.RoleID; + + this.ClearRoleCache(role.PortalID); + + EventManager.Instance.OnRoleCreated(new RoleEventArgs() { Role = role }); } + + return roleId; } + protected override Func GetFactory() + { + return () => new RoleController(); + } + private static bool DeleteUserRoleInternal(int portalId, int userId, int roleId) { var user = UserController.GetUserById(portalId, userId); @@ -158,32 +213,35 @@ private static void SendNotification(UserInfo objUser, RoleInfo objRole, PortalS Mail.SendEmail(PortalSettings.Email, objUser.Email, _message.Subject, _message.Body); } - public int AddRole(RoleInfo role) + private void AddMessage(RoleInfo roleInfo, EventLogController.EventLogType logType) { - return Instance.AddRole(role, true); + EventLogController.Instance.AddLog( + roleInfo, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + logType); } - int IRoleController.AddRole(RoleInfo role, bool addToExistUsers) + private void AutoAssignUsers(RoleInfo role) { - Requires.NotNull("role", role); - - var roleId = -1; - if (provider.CreateRole(role)) + if (role.AutoAssignment) { - this.AddMessage(role, EventLogController.EventLogType.ROLE_CREATED); - if (addToExistUsers) + // loop through users for portal and add to role + var arrUsers = UserController.GetUsers(role.PortalID); + foreach (UserInfo objUser in arrUsers) { - this.AutoAssignUsers(role); + try + { + this.AddUserRole(role.PortalID, objUser.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + } + catch (Exception exc) + { + // user already belongs to role + Logger.Error(exc); + } } - - roleId = role.RoleID; - - this.ClearRoleCache(role.PortalID); - - EventManager.Instance.OnRoleCreated(new RoleEventArgs() { Role = role }); } - - return roleId; } public void AddUserRole(int portalId, int userId, int roleId, RoleStatus status, bool isOwner, DateTime effectiveDate, DateTime expiryDate) @@ -498,64 +556,6 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat DataCache.ClearUserCache(portalId, user.Username); Instance.ClearRoleCache(portalId); } - - /// ----------------------------------------------------------------------------- - /// - /// Adds a Role Group. - /// - /// The RoleGroup to Add. - /// The Id of the new role. - /// ----------------------------------------------------------------------------- - public static int AddRoleGroup(RoleGroupInfo objRoleGroupInfo) - { - var id = provider.CreateRoleGroup(objRoleGroupInfo); - EventLogController.Instance.AddLog(objRoleGroupInfo, PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_CREATED); - return id; - } - - /// - /// Adds a User to a Role. - /// - /// The user to assign. - /// The role to add. - /// The PortalSettings of the Portal. - /// RoleStatus. - /// The expiry Date of the Role membership. - /// The expiry Date of the Role membership. - /// A flag that indicates whether the user should be notified. - /// A flag that indicates whether this user should be one of the group owners. - public static void AddUserRole(UserInfo user, RoleInfo role, PortalSettings portalSettings, RoleStatus status, DateTime effectiveDate, DateTime expiryDate, bool notifyUser, bool isOwner) - { - var userRole = Instance.GetUserRole(portalSettings.PortalId, user.UserID, role.RoleID); - - // update assignment - Instance.AddUserRole(portalSettings.PortalId, user.UserID, role.RoleID, status, isOwner, effectiveDate, expiryDate); - - UserController.UpdateUser(portalSettings.PortalId, user); - if (userRole == null) - { - EventLogController.Instance.AddLog("Role", role.RoleName, portalSettings, user.UserID, EventLogController.EventLogType.USER_ROLE_CREATED); - - // send notification - if (notifyUser) - { - SendNotification(user, role, portalSettings, UserRoleActions.@add); - } - } - else - { - EventLogController.Instance.AddLog("Role", role.RoleName, portalSettings, user.UserID, EventLogController.EventLogType.USER_ROLE_UPDATED); - if (notifyUser) - { - RoleController.Instance.GetUserRole(portalSettings.PortalId, user.UserID, role.RoleID); - SendNotification(user, role, portalSettings, UserRoleActions.update); - } - } - - // Remove the UserInfo from the Cache, as it has been modified - DataCache.ClearUserCache(portalSettings.PortalId, user.Username); - } /// ----------------------------------------------------------------------------- /// @@ -643,22 +643,6 @@ public static bool DeleteUserRole(UserInfo objUser, RoleInfo role, PortalSetting return canDelete; } - /// - /// Completely remove all a user's roles for a specific portal. This method is used when - /// anonymizing a user. - /// - /// User for which all roles must be deleted. The PortalId property - /// is used to determine for which portal roles must be removed. - internal static void DeleteUserRoles(UserInfo user) - { - var ctrl = new RoleController(); - var userRoles = ctrl.GetUserRoles(user, true); - foreach (var ur in userRoles.Where(r => r.PortalID == user.PortalID)) - { - provider.RemoveUserFromRole(user.PortalID, user, ur); - } - } - /// ----------------------------------------------------------------------------- /// /// Fetch a single RoleGroup. @@ -687,6 +671,22 @@ public static RoleGroupInfo GetRoleGroupByName(int portalId, string roleGroupNam return provider.GetRoleGroupByName(portalId, roleGroupName); } + /// + /// Completely remove all a user's roles for a specific portal. This method is used when + /// anonymizing a user. + /// + /// User for which all roles must be deleted. The PortalId property + /// is used to determine for which portal roles must be removed. + internal static void DeleteUserRoles(UserInfo user) + { + var ctrl = new RoleController(); + var userRoles = ctrl.GetUserRoles(user, true); + foreach (var ur in userRoles.Where(r => r.PortalID == user.PortalID)) + { + provider.RemoveUserFromRole(user.PortalID, user, ur); + } + } + /// ----------------------------------------------------------------------------- /// /// Gets an ArrayList of RoleGroups. diff --git a/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs b/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs index 950e5bb8782..551db984134 100644 --- a/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs +++ b/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs @@ -141,23 +141,6 @@ public Dictionary Roles return this._Roles; } } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a RoleGroupInfo from a Data Reader. - /// - /// The Data Reader to use. - /// ----------------------------------------------------------------------------- - public void Fill(IDataReader dr) - { - this.RoleGroupID = Null.SetNullInteger(dr["RoleGroupId"]); - this.PortalID = Null.SetNullInteger(dr["PortalID"]); - this.RoleGroupName = Null.SetNullString(dr["RoleGroupName"]); - this.Description = Null.SetNullString(dr["Description"]); - - // Fill base class fields - this.FillInternal(dr); - } /// ----------------------------------------------------------------------------- /// @@ -178,6 +161,23 @@ public int KeyID } } + /// ----------------------------------------------------------------------------- + /// + /// Fills a RoleGroupInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public void Fill(IDataReader dr) + { + this.RoleGroupID = Null.SetNullInteger(dr["RoleGroupId"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.RoleGroupName = Null.SetNullString(dr["RoleGroupName"]); + this.Description = Null.SetNullString(dr["Description"]); + + // Fill base class fields + this.FillInternal(dr); + } + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the RoleGroupInfo. diff --git a/DNN Platform/Library/Security/Roles/RoleInfo.cs b/DNN Platform/Library/Security/Roles/RoleInfo.cs index 0f4402dcff3..21d3fd8717d 100644 --- a/DNN Platform/Library/Security/Roles/RoleInfo.cs +++ b/DNN Platform/Library/Security/Roles/RoleInfo.cs @@ -277,28 +277,24 @@ public string PhotoURL return photoURL; } } - - private void GetRoleType() + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public virtual int KeyID { - var portal = PortalController.Instance.GetPortal(this.PortalID); - if (this.RoleID == portal.AdministratorRoleId) - { - this._RoleType = RoleType.Administrator; - } - else if (this.RoleID == portal.RegisteredRoleId) - { - this._RoleType = RoleType.RegisteredUser; - } - else if (this.RoleName == "Subscribers") - { - this._RoleType = RoleType.Subscriber; - } - else if (this.RoleName == "Unverified Users") - { - this._RoleType = RoleType.UnverifiedUser; - } + get { return this.RoleID; } + set { this.RoleID = value; } } + public CacheLevel Cacheability + { + get { return CacheLevel.fullyCacheable; } + } + /// ----------------------------------------------------------------------------- /// /// Fills a RoleInfo from a Data Reader. @@ -378,23 +374,6 @@ public virtual void Fill(IDataReader dr) this.FillInternal(dr); } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Key ID. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - public virtual int KeyID - { - get { return this.RoleID; } - set { this.RoleID = value; } - } - - public CacheLevel Cacheability - { - get { return CacheLevel.fullyCacheable; } - } - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { @@ -468,6 +447,27 @@ public string GetProperty(string propertyName, string format, CultureInfo format } } + private void GetRoleType() + { + var portal = PortalController.Instance.GetPortal(this.PortalID); + if (this.RoleID == portal.AdministratorRoleId) + { + this._RoleType = RoleType.Administrator; + } + else if (this.RoleID == portal.RegisteredRoleId) + { + this._RoleType = RoleType.RegisteredUser; + } + else if (this.RoleName == "Subscribers") + { + this._RoleType = RoleType.Subscriber; + } + else if (this.RoleName == "Unverified Users") + { + this._RoleType = RoleType.UnverifiedUser; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the RoleInfo. diff --git a/DNN Platform/Library/Security/Roles/RoleProvider.cs b/DNN Platform/Library/Security/Roles/RoleProvider.cs index 332e4e3af1e..00aa1d7ded3 100644 --- a/DNN Platform/Library/Security/Roles/RoleProvider.cs +++ b/DNN Platform/Library/Security/Roles/RoleProvider.cs @@ -35,8 +35,8 @@ public virtual void DeleteRole(RoleInfo role) public abstract IList GetRolesBasicSearch(int portalID, int pageSize, string filterBy); public virtual IDictionary GetRoleSettings(int roleId) - { - return new Dictionary(); + { + return new Dictionary(); } public abstract void UpdateRole(RoleInfo role); diff --git a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs index 6735f2e9c96..04d43895743 100644 --- a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs +++ b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs @@ -93,17 +93,17 @@ public override string RenderCustomScript(AnalyticsConfiguration config) { switch (setting.SettingName.ToLowerInvariant()) { - case "anonymizeip": - { - bool.TryParse(setting.SettingValue, out anonymize); - break; - } + case "anonymizeip": + { + bool.TryParse(setting.SettingValue, out anonymize); + break; + } - case "trackinguser": - { - bool.TryParse(setting.SettingValue, out trackingUserId); - break; - } + case "trackinguser": + { + bool.TryParse(setting.SettingValue, out trackingUserId); + break; + } } } diff --git a/DNN Platform/Library/Services/Assets/AssetManager.cs b/DNN Platform/Library/Services/Assets/AssetManager.cs index 40e41380a6a..3ecb6251fbb 100644 --- a/DNN Platform/Library/Services/Assets/AssetManager.cs +++ b/DNN Platform/Library/Services/Assets/AssetManager.cs @@ -36,6 +36,47 @@ public class AssetManager : ComponentBase, IAssetMa private const string DefaultMessageDefaultMessage = "The folder does not exist"; private static readonly Regex MappedPathRegex = new Regex(@"^(?!\s*[\\/]).*$", RegexOptions.Compiled); + public static IOrderedQueryable ApplyOrder(IQueryable source, string propertyName, bool asc) + { + var methodName = asc ? "OrderBy" : "OrderByDescending"; + var arg = Expression.Parameter(typeof(T), "x"); + + // Use reflection to mirror LINQ + var property = typeof(T).GetProperty(propertyName); + + // If property is undefined returns the original source + if (property == null) + { + return (IOrderedQueryable)source; + } + + Expression expr = Expression.Property(arg, property); + + var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), property.PropertyType); + var lambda = Expression.Lambda(delegateType, expr, arg); + + var result = typeof(Queryable).GetMethods().Single( + method => method.Name == methodName + && method.IsGenericMethodDefinition + && method.GetGenericArguments().Length == 2 + && method.GetParameters().Length == 2) + .MakeGenericMethod(typeof(T), property.PropertyType) + .Invoke(null, new object[] { source, lambda }); + return (IOrderedQueryable)result; + } + + public static bool HasPermission(IFolderInfo folder, string permissionKey) + { + var hasPermision = PortalSettings.Current.UserInfo.IsSuperUser; + + if (!hasPermision && folder != null) + { + hasPermision = FolderPermissionController.HasFolderPermission(folder.FolderPermissions, permissionKey); + } + + return hasPermision; + } + public ContentPage GetFolderContent(int folderId, int startIndex, int numItems, string sortExpression = null, SubfolderFilter subfolderFilter = SubfolderFilter.IncludeSubfoldersFolderStructure) { var folder = this.GetFolderInfo(folderId); @@ -116,76 +157,6 @@ public IEnumerable GetFolders(IFolderInfo parentFolder, string orde return ApplyOrder(folders.AsQueryable(), field, asc); } - private IEnumerable GetFiles(IFolderInfo folder, SortProperties sortProperties, int startIndex, bool recursive) - { - Requires.NotNull("folder", folder); - - if (Host.EnableFileAutoSync && startIndex == 0) - { - FolderManager.Instance.Synchronize(folder.PortalID, folder.FolderPath, false, true); - } - - return SortFiles(FolderManager.Instance.GetFiles(folder, recursive, true), sortProperties); - } - - private static IEnumerable SortFiles(IEnumerable files, SortProperties sortProperties) - { - switch (sortProperties.Column) - { - case "ItemName": - return OrderBy(files, f => f.FileName, sortProperties.Ascending); - case "LastModifiedOnDate": - return OrderBy(files, f => f.LastModifiedOnDate, sortProperties.Ascending); - case "Size": - return OrderBy(files, f => f.Size, sortProperties.Ascending); - case "ParentFolder": - return OrderBy(files, f => f.FolderId, new FolderPathComparer(), sortProperties.Ascending); - case "CreatedOnDate": - return OrderBy(files, f => f.CreatedOnDate, sortProperties.Ascending); - default: - return files; - } - } - - public static IOrderedQueryable ApplyOrder(IQueryable source, string propertyName, bool asc) - { - var methodName = asc ? "OrderBy" : "OrderByDescending"; - var arg = Expression.Parameter(typeof(T), "x"); - - // Use reflection to mirror LINQ - var property = typeof(T).GetProperty(propertyName); - - // If property is undefined returns the original source - if (property == null) - { - return (IOrderedQueryable)source; - } - - Expression expr = Expression.Property(arg, property); - - var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), property.PropertyType); - var lambda = Expression.Lambda(delegateType, expr, arg); - - var result = typeof(Queryable).GetMethods().Single( - method => method.Name == methodName - && method.IsGenericMethodDefinition - && method.GetGenericArguments().Length == 2 - && method.GetParameters().Length == 2) - .MakeGenericMethod(typeof(T), property.PropertyType) - .Invoke(null, new object[] { source, lambda }); - return (IOrderedQueryable)result; - } - - private static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, bool ascending) - { - return ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector); - } - - private static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, IComparer comparer, bool ascending) - { - return ascending ? source.OrderBy(keySelector, comparer) : source.OrderByDescending(keySelector, comparer); - } - public IFileInfo RenameFile(int fileId, string newFileName) { Requires.NotNullOrEmpty("newFileName", newFileName); @@ -277,6 +248,47 @@ public IFolderInfo RenameFolder(int folderId, string newFolderName) return folder; } + private static IEnumerable SortFiles(IEnumerable files, SortProperties sortProperties) + { + switch (sortProperties.Column) + { + case "ItemName": + return OrderBy(files, f => f.FileName, sortProperties.Ascending); + case "LastModifiedOnDate": + return OrderBy(files, f => f.LastModifiedOnDate, sortProperties.Ascending); + case "Size": + return OrderBy(files, f => f.Size, sortProperties.Ascending); + case "ParentFolder": + return OrderBy(files, f => f.FolderId, new FolderPathComparer(), sortProperties.Ascending); + case "CreatedOnDate": + return OrderBy(files, f => f.CreatedOnDate, sortProperties.Ascending); + default: + return files; + } + } + + private static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, bool ascending) + { + return ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector); + } + + private IEnumerable GetFiles(IFolderInfo folder, SortProperties sortProperties, int startIndex, bool recursive) + { + Requires.NotNull("folder", folder); + + if (Host.EnableFileAutoSync && startIndex == 0) + { + FolderManager.Instance.Synchronize(folder.PortalID, folder.FolderPath, false, true); + } + + return SortFiles(FolderManager.Instance.GetFiles(folder, recursive, true), sortProperties); + } + + private static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, IComparer comparer, bool ascending) + { + return ascending ? source.OrderBy(keySelector, comparer) : source.OrderByDescending(keySelector, comparer); + } + public IFolderInfo CreateFolder(string folderName, int folderParentId, int folderMappingId, string mappedPath) { Requires.NotNullOrEmpty("folderName", folderName); @@ -350,21 +362,6 @@ public bool DeleteFolder(int folderId, bool onlyUnlink, ICollection return true; } - private void DeleteFolder(IFolderInfo folder, ICollection nonDeletedItems) - { - var nonDeletedSubfolders = new List(); - FolderManager.Instance.DeleteFolder(folder, nonDeletedSubfolders); - if (!nonDeletedSubfolders.Any()) - { - return; - } - - foreach (var nonDeletedSubfolder in nonDeletedSubfolders) - { - nonDeletedItems.Add(nonDeletedSubfolder); - } - } - public bool DeleteFile(int fileId) { var fileInfo = FileManager.Instance.GetFile(fileId, true); @@ -389,6 +386,21 @@ private static string CleanDotsAtTheEndOfTheName(string name) return name.Trim().TrimEnd('.', ' '); } + private void DeleteFolder(IFolderInfo folder, ICollection nonDeletedItems) + { + var nonDeletedSubfolders = new List(); + FolderManager.Instance.DeleteFolder(folder, nonDeletedSubfolders); + if (!nonDeletedSubfolders.Any()) + { + return; + } + + foreach (var nonDeletedSubfolder in nonDeletedSubfolders) + { + nonDeletedItems.Add(nonDeletedSubfolder); + } + } + private bool IsInvalidName(string itemName) { var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(this.GetInvalidChars()) + "]"); @@ -424,18 +436,6 @@ private string GetInvalidCharsErrorText() FolderFileNameHasInvalidcharactersDefaultMessage, "\\:/*?\"<>|")); } - public static bool HasPermission(IFolderInfo folder, string permissionKey) - { - var hasPermision = PortalSettings.Current.UserInfo.IsSuperUser; - - if (!hasPermision && folder != null) - { - hasPermision = FolderPermissionController.HasFolderPermission(folder.FolderPermissions, permissionKey); - } - - return hasPermision; - } - private IFolderInfo GetFolderInfo(int folderId) { var folder = FolderManager.Instance.GetFolder(folderId); diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs b/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs index b11592c634d..24a0316dd7d 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs @@ -18,8 +18,8 @@ namespace DotNetNuke.Services.Authentication [Serializable] public class AuthenticationConfig : AuthenticationConfigBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthenticationConfig)); private const string CACHEKEY = "Authentication.DNN"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthenticationConfig)); protected AuthenticationConfig(int portalID) : base(portalID) diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs index b07a92fdb6e..49afae67766 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs @@ -18,15 +18,6 @@ namespace DotNetNuke.Services.Authentication [Serializable] public abstract class AuthenticationConfigBase { - /// - /// Gets the Dependency Provider to resolve registered - /// services with the container. - /// - /// - /// The Dependency Service. - /// - protected IServiceProvider DependencyProvider { get; } - public AuthenticationConfigBase() { this.DependencyProvider = Globals.DependencyProvider; @@ -40,5 +31,14 @@ protected AuthenticationConfigBase(int portalID) [Browsable(false)] public int PortalID { get; set; } + + /// + /// Gets the Dependency Provider to resolve registered + /// services with the container. + /// + /// + /// The Dependency Service. + /// + protected IServiceProvider DependencyProvider { get; } } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationController.cs b/DNN Platform/Library/Services/Authentication/AuthenticationController.cs index fee2f243ba2..fcb0e4cde23 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationController.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationController.cs @@ -32,11 +32,6 @@ public class AuthenticationController private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthenticationController)); private static readonly DataProvider provider = DataProvider.Instance(); - private static object GetAuthenticationServicesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillCollection(provider.GetAuthenticationServices()); - } - /// ----------------------------------------------------------------------------- /// /// AddAuthentication adds a new Authentication System to the Data Store. @@ -93,6 +88,11 @@ public static int AddUserAuthentication(int userID, string authenticationType, s } } + private static object GetAuthenticationServicesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillCollection(provider.GetAuthenticationServices()); + } + /// /// Retrieves authentication information for an user. /// diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs b/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs index 7f9c3fad3f6..0d6cdaf242d 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs @@ -76,6 +76,25 @@ public AuthenticationInfo() /// /// ----------------------------------------------------------------------------- public string LogoffControlSrc { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public virtual int KeyID + { + get + { + return this.AuthenticationID; + } + + set + { + this.AuthenticationID = value; + } + } /// ----------------------------------------------------------------------------- /// @@ -96,24 +115,5 @@ public virtual void Fill(IDataReader dr) // Fill base class fields this.FillInternal(dr); } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Key ID. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - public virtual int KeyID - { - get - { - return this.AuthenticationID; - } - - set - { - this.AuthenticationID = value; - } - } } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs index f800cd9018c..3a07044a872 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs @@ -18,14 +18,16 @@ namespace DotNetNuke.Services.Authentication /// ----------------------------------------------------------------------------- public abstract class AuthenticationLoginBase : UserModuleBase { - public delegate void UserAuthenticatedEventHandler(object sender, UserAuthenticatedEventArgs e); - protected AuthenticationLoginBase() { this.RedirectURL = Null.NullString; this.AuthenticationType = Null.NullString; this.Mode = AuthMode.Login; } + + public delegate void UserAuthenticatedEventHandler(object sender, UserAuthenticatedEventArgs e); + + public event UserAuthenticatedEventHandler UserAuthenticated; /// ----------------------------------------------------------------------------- /// @@ -83,7 +85,11 @@ public virtual bool SupportsRegistration get { return false; } } - public event UserAuthenticatedEventHandler UserAuthenticated; + [Obsolete("Deprecated in 9.2.0. Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress. Scheduled removal in v11.0.0.")] + public static string GetIPAddress() + { + return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request)); + } protected virtual void OnUserAuthenticated(UserAuthenticatedEventArgs ea) { @@ -92,11 +98,5 @@ protected virtual void OnUserAuthenticated(UserAuthenticatedEventArgs ea) this.UserAuthenticated(null, ea); } } - - [Obsolete("Deprecated in 9.2.0. Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress. Scheduled removal in v11.0.0.")] - public static string GetIPAddress() - { - return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request)); - } } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs index 6a27afa3b15..4aefc9dae38 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs @@ -20,20 +20,15 @@ public abstract class AuthenticationLogoffBase : UserModuleBase private string _AuthenticationType = Null.NullString; private string _RedirectURL = Null.NullString; - /// - /// Gets the Dependency Provider to resolve registered - /// services with the container. - /// - /// - /// The Dependency Service. - /// - protected IServiceProvider DependencyProvider { get; } - public AuthenticationLogoffBase() { this.DependencyProvider = Globals.DependencyProvider; } + public event EventHandler LogOff; + + public event EventHandler Redirect; + /// ----------------------------------------------------------------------------- /// /// Gets or sets and Sets the Type of Authentication associated with this control. @@ -52,9 +47,14 @@ public string AuthenticationType } } - public event EventHandler LogOff; - - public event EventHandler Redirect; + /// + /// Gets the Dependency Provider to resolve registered + /// services with the container. + /// + /// + /// The Dependency Service. + /// + protected IServiceProvider DependencyProvider { get; } protected virtual void OnLogOff(EventArgs a) { diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs index 3748ce2093e..a84a04b8c37 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs @@ -25,11 +25,13 @@ namespace DotNetNuke.Services.Authentication.OAuth public abstract class OAuthClientBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OAuthClientBase)); + protected const string OAuthTokenKey = "oauth_token"; private const string HMACSHA1SignatureType = "HMAC-SHA1"; // oAuth 1 private const string OAuthParameterPrefix = "oauth_"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OAuthClientBase)); private const string OAuthConsumerKeyKey = "oauth_consumer_key"; private const string OAuthCallbackKey = "oauth_callback"; private const string OAuthVersionKey = "oauth_version"; @@ -48,13 +50,13 @@ public abstract class OAuthClientBase private const string OAuthGrantTyepKey = "grant_type"; private const string OAuthCodeKey = "code"; - private readonly Random random = new Random(); - private const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; // DNN-6265 - Support OAuth V2 optional parameter resource, which is required by Microsoft Azure Active // Directory implementation of OAuth V2 private const string OAuthResourceKey = "resource"; + + private readonly Random random = new Random(); protected OAuthClientBase(int portalId, AuthMode mode, string service) { @@ -73,7 +75,9 @@ protected OAuthClientBase(int portalId, AuthMode mode, string service) : new Uri(Globals.RegisterURL(string.Empty, string.Empty)); } - protected const string OAuthTokenKey = "oauth_token"; + public Uri CallbackUri { get; set; } + + public string Service { get; set; } protected virtual string UserGuidKey { @@ -131,10 +135,6 @@ protected string VerificationCode // DNN-6265 Support "Optional" Resource Parameter required by Azure AD Oauth V2 Solution protected string APIResource { get; set; } - - public Uri CallbackUri { get; set; } - - public string Service { get; set; } public virtual bool PrefixServiceToUserName { @@ -145,6 +145,171 @@ public virtual bool AutoMatchExistingUsers { get { return false; } } + + /// + /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case. + /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth. + /// + /// The value to Url encode. + /// Returns a Url encoded string. + public static string UrlEncode(string value) + { + var result = new StringBuilder(); + + foreach (char symbol in value) + { + if (UnreservedChars.IndexOf(symbol) != -1) + { + result.Append(symbol); + } + else + { + result.Append('%' + string.Format("{0:X2}", (int)symbol)); + } + } + + return result.ToString(); + } + + public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action addCustomProperties, Action onAuthenticated) + { + var loginStatus = UserLoginStatus.LOGIN_FAILURE; + + string userName = this.PrefixServiceToUserName ? this.Service + "-" + user.Id : user.Id; + string token = this.Service + "-" + user.Id; + + UserInfo objUserInfo; + + if (this.AutoMatchExistingUsers) + { + objUserInfo = MembershipProvider.Instance().GetUserByUserName(settings.PortalId, userName); + if (objUserInfo != null) + { + // user already exists... lets check for a token next... + var dnnAuthToken = MembershipProvider.Instance().GetUserByAuthToken(settings.PortalId, token, this.Service); + if (dnnAuthToken == null) + { + DataProvider.Instance().AddUserAuthentication(objUserInfo.UserID, this.Service, token, objUserInfo.UserID); + } + } + } + + objUserInfo = UserController.ValidateUser(settings.PortalId, userName, string.Empty, + this.Service, token, + settings.PortalName, IPAddress, + ref loginStatus); + + // Raise UserAuthenticated Event + var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, token, loginStatus, this.Service) + { + AutoRegister = true, + UserName = userName, + }; + + var profileProperties = new NameValueCollection(); + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.FirstName) && !string.IsNullOrEmpty(user.FirstName))) + { + profileProperties.Add("FirstName", user.FirstName); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.LastName) && !string.IsNullOrEmpty(user.LastName))) + { + profileProperties.Add("LastName", user.LastName); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Email) && !string.IsNullOrEmpty(user.Email))) + { + profileProperties.Add("Email", user.PreferredEmail); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.DisplayName) && !string.IsNullOrEmpty(user.DisplayName))) + { + profileProperties.Add("DisplayName", user.DisplayName); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("ProfileImage")) && !string.IsNullOrEmpty(user.ProfileImage))) + { + profileProperties.Add("ProfileImage", user.ProfileImage); + } + + if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website))) + { + profileProperties.Add("Website", user.Website); + } + + if ((objUserInfo == null || string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredLocale"))) && !string.IsNullOrEmpty(user.Locale)) + { + if (LocaleController.IsValidCultureName(user.Locale.Replace('_', '-'))) + { + profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-')); + } + else + { + profileProperties.Add("PreferredLocale", settings.CultureCode); + } + } + + if (objUserInfo == null || string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone"))) + { + if (string.IsNullOrEmpty(user.TimeZoneInfo)) + { + int timeZone; + if (int.TryParse(user.Timezone, out timeZone)) + { + var timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone); + + profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id); + } + } + else + { + profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo); + } + } + + addCustomProperties(profileProperties); + + eventArgs.Profile = profileProperties; + + if (this.Mode == AuthMode.Login) + { + this.SaveTokenCookie(string.Empty); + } + + onAuthenticated(eventArgs); + } + + public virtual AuthorisationResult Authorize() + { + if (this.OAuthVersion == "1.0") + { + return this.AuthorizeV1(); + } + + return this.AuthorizeV2(); + } + + /// + /// Generate the timestamp for the signature. + /// + /// + protected virtual string GenerateTimeStamp() + { + // Default implementation of UNIX time of the current UTC time + TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalSeconds).ToString(CultureInfo.InvariantCulture); + } + + /// + /// Generate a nonce. + /// + /// + protected virtual string GenerateNonce() + { + // Just a simple implementation of a random number between 123400 and 9999999 + return this.random.Next(123400, 9999999).ToString(CultureInfo.InvariantCulture); + } private AuthorisationResult AuthorizeV1() { @@ -554,27 +719,6 @@ private Uri GenerateRequestUri(string url, string parameters) return new Uri(string.Format("{0}{1}{2}", url, url.Contains("?") ? "&" : "?", parameters)); } - - /// - /// Generate the timestamp for the signature. - /// - /// - protected virtual string GenerateTimeStamp() - { - // Default implementation of UNIX time of the current UTC time - TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); - return Convert.ToInt64(ts.TotalSeconds).ToString(CultureInfo.InvariantCulture); - } - - /// - /// Generate a nonce. - /// - /// - protected virtual string GenerateNonce() - { - // Just a simple implementation of a random number between 123400 and 9999999 - return this.random.Next(123400, 9999999).ToString(CultureInfo.InvariantCulture); - } protected virtual TimeSpan GetExpiry(string responseText) { @@ -599,125 +743,6 @@ protected void LoadTokenCookie(string suffix) } } } - - public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action addCustomProperties, Action onAuthenticated) - { - var loginStatus = UserLoginStatus.LOGIN_FAILURE; - - string userName = this.PrefixServiceToUserName ? this.Service + "-" + user.Id : user.Id; - string token = this.Service + "-" + user.Id; - - UserInfo objUserInfo; - - if (this.AutoMatchExistingUsers) - { - objUserInfo = MembershipProvider.Instance().GetUserByUserName(settings.PortalId, userName); - if (objUserInfo != null) - { - // user already exists... lets check for a token next... - var dnnAuthToken = MembershipProvider.Instance().GetUserByAuthToken(settings.PortalId, token, this.Service); - if (dnnAuthToken == null) - { - DataProvider.Instance().AddUserAuthentication(objUserInfo.UserID, this.Service, token, objUserInfo.UserID); - } - } - } - - objUserInfo = UserController.ValidateUser(settings.PortalId, userName, string.Empty, - this.Service, token, - settings.PortalName, IPAddress, - ref loginStatus); - - // Raise UserAuthenticated Event - var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, token, loginStatus, this.Service) - { - AutoRegister = true, - UserName = userName, - }; - - var profileProperties = new NameValueCollection(); - - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.FirstName) && !string.IsNullOrEmpty(user.FirstName))) - { - profileProperties.Add("FirstName", user.FirstName); - } - - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.LastName) && !string.IsNullOrEmpty(user.LastName))) - { - profileProperties.Add("LastName", user.LastName); - } - - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Email) && !string.IsNullOrEmpty(user.Email))) - { - profileProperties.Add("Email", user.PreferredEmail); - } - - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.DisplayName) && !string.IsNullOrEmpty(user.DisplayName))) - { - profileProperties.Add("DisplayName", user.DisplayName); - } - - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("ProfileImage")) && !string.IsNullOrEmpty(user.ProfileImage))) - { - profileProperties.Add("ProfileImage", user.ProfileImage); - } - - if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website))) - { - profileProperties.Add("Website", user.Website); - } - - if ((objUserInfo == null || string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredLocale"))) && !string.IsNullOrEmpty(user.Locale)) - { - if (LocaleController.IsValidCultureName(user.Locale.Replace('_', '-'))) - { - profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-')); - } - else - { - profileProperties.Add("PreferredLocale", settings.CultureCode); - } - } - - if (objUserInfo == null || string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone"))) - { - if (string.IsNullOrEmpty(user.TimeZoneInfo)) - { - int timeZone; - if (int.TryParse(user.Timezone, out timeZone)) - { - var timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone); - - profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id); - } - } - else - { - profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo); - } - } - - addCustomProperties(profileProperties); - - eventArgs.Profile = profileProperties; - - if (this.Mode == AuthMode.Login) - { - this.SaveTokenCookie(string.Empty); - } - - onAuthenticated(eventArgs); - } - - public virtual AuthorisationResult Authorize() - { - if (this.OAuthVersion == "1.0") - { - return this.AuthorizeV1(); - } - - return this.AuthorizeV2(); - } /// /// Generates a signature using the HMAC-SHA1 algorithm. @@ -737,13 +762,13 @@ public string GenerateSignature(Uri url, string token, string tokenSecret, strin { string signatureBase = this.GenerateSignatureBase(url, token, callbackurl, oauthVerifier, httpMethod, timeStamp, nonce, out normalizedUrl, out requestParameters); - var hmacsha1 = new HMACSHA1 - { - Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(this.APISecret), + var hmacsha1 = new HMACSHA1 + { + Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(this.APISecret), string.IsNullOrEmpty(tokenSecret) ? string.Empty - : UrlEncode(tokenSecret))), - }; + : UrlEncode(tokenSecret))), + }; return this.GenerateSignatureUsingHash(signatureBase, hmacsha1); } @@ -791,30 +816,5 @@ public void RemoveToken() }; HttpContext.Current.Response.SetCookie(authTokenCookie); } - - /// - /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case. - /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth. - /// - /// The value to Url encode. - /// Returns a Url encoded string. - public static string UrlEncode(string value) - { - var result = new StringBuilder(); - - foreach (char symbol in value) - { - if (UnreservedChars.IndexOf(symbol) != -1) - { - result.Append(symbol); - } - else - { - result.Append('%' + string.Format("{0:X2}", (int)symbol)); - } - } - - return result.ToString(); - } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs index 6ca806ced11..4b651264932 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs @@ -51,21 +51,16 @@ protected OAuthConfigBase(string service, int portalId) } } - protected string Service { get; set; } - public string APIKey { get; set; } public string APISecret { get; set; } + protected string Service { get; set; } + public bool Enabled { get; set; } public bool HostConfig { get; set; } - private static string GetCacheKey(string service, int portalId) - { - return _cacheKey + "." + service + "_" + portalId; - } - public static void ClearConfig(string service, int portalId) { DataCache.RemoveCache(GetCacheKey(service, portalId)); @@ -84,6 +79,11 @@ public static OAuthConfigBase GetConfig(string service, int portalId) return config; } + private static string GetCacheKey(string service, int portalId) + { + return _cacheKey + "." + service + "_" + portalId; + } + public static void UpdateConfig(OAuthConfigBase config) { if (config.HostConfig) diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs index 081ed72491f..b026e4d8830 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs @@ -11,6 +11,11 @@ namespace DotNetNuke.Services.Authentication.OAuth public abstract class OAuthLoginBase : AuthenticationLoginBase { + public override bool Enabled + { + get { return OAuthConfigBase.GetConfig(this.AuthSystemApplicationName, this.PortalId).Enabled; } + } + protected virtual string AuthSystemApplicationName { get { return string.Empty; } @@ -52,10 +57,5 @@ protected override void OnLoad(EventArgs e) } } } - - public override bool Enabled - { - get { return OAuthConfigBase.GetConfig(this.AuthSystemApplicationName, this.PortalId).Enabled; } - } } } diff --git a/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs b/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs index db3f629e3cb..297602667a6 100644 --- a/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs +++ b/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs @@ -52,23 +52,6 @@ public UserAuthenticationInfo() /// /// ----------------------------------------------------------------------------- public string AuthenticationToken { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Fills a UserAuthenticationInfo from a Data Reader. - /// - /// The Data Reader to use. - /// ----------------------------------------------------------------------------- - public virtual void Fill(IDataReader dr) - { - this.UserAuthenticationID = Null.SetNullInteger(dr["UserAuthenticationID"]); - this.UserID = Null.SetNullInteger(dr["UserID"]); - this.AuthenticationType = Null.SetNullString(dr["AuthenticationType"]); - this.AuthenticationToken = Null.SetNullString(dr["AuthenticationToken"]); - - // Fill base class fields - this.FillInternal(dr); - } /// ----------------------------------------------------------------------------- /// @@ -88,5 +71,22 @@ public virtual int KeyID this.UserAuthenticationID = value; } } + + /// ----------------------------------------------------------------------------- + /// + /// Fills a UserAuthenticationInfo from a Data Reader. + /// + /// The Data Reader to use. + /// ----------------------------------------------------------------------------- + public virtual void Fill(IDataReader dr) + { + this.UserAuthenticationID = Null.SetNullInteger(dr["UserAuthenticationID"]); + this.UserID = Null.SetNullInteger(dr["UserID"]); + this.AuthenticationType = Null.SetNullString(dr["AuthenticationType"]); + this.AuthenticationToken = Null.SetNullString(dr["AuthenticationToken"]); + + // Fill base class fields + this.FillInternal(dr); + } } } diff --git a/DNN Platform/Library/Services/Cache/CachingProvider.cs b/DNN Platform/Library/Services/Cache/CachingProvider.cs index b191ee3e570..621dd4fcb65 100644 --- a/DNN Platform/Library/Services/Cache/CachingProvider.cs +++ b/DNN Platform/Library/Services/Cache/CachingProvider.cs @@ -41,10 +41,10 @@ namespace DotNetNuke.Services.Cache /// public abstract class CachingProvider { + private const string CachePrefix = "DNN_"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CachingProvider)); private static System.Web.Caching.Cache _cache; - private const string CachePrefix = "DNN_"; /// /// Gets the default cache provider. @@ -105,6 +105,21 @@ public static CachingProvider Instance() return ComponentFactory.GetComponent(); } + /// + /// Clears the specified type. + /// + /// The type. + /// The data. + public virtual void Clear(string type, string data) + { + this.ClearCacheInternal(type, data, false); + } + + public virtual IDictionaryEnumerator GetEnumerator() + { + return Cache.GetEnumerator(); + } + /// /// Disable Cache Expirataion. This control won't affect core caching provider, its behavior determined by extended caching provider. /// This property designed for when process long time action, extended caching provider should not sync cache between web servers to improve performance. @@ -128,6 +143,62 @@ internal static void EnableCacheExpiration() Logger.Warn("Enable cache expiration."); } + /// + /// Clears the cache internal. + /// + /// Type of the cache. + /// The data. + /// if set to true clear runtime cache. + protected void ClearCacheInternal(string cacheType, string data, bool clearRuntime) + { + switch (cacheType) + { + case "Prefix": + this.ClearCacheInternal(data, clearRuntime); + break; + case "Host": + this.ClearHostCacheInternal(clearRuntime); + break; + case "Folder": + this.ClearFolderCacheInternal(int.Parse(data), clearRuntime); + break; + case "Module": + this.ClearModuleCacheInternal(int.Parse(data), clearRuntime); + break; + case "ModulePermissionsByPortal": + this.ClearModulePermissionsCachesByPortalInternal(int.Parse(data), clearRuntime); + break; + case "Portal": + this.ClearPortalCacheInternal(int.Parse(data), false, clearRuntime); + break; + case "PortalCascade": + this.ClearPortalCacheInternal(int.Parse(data), true, clearRuntime); + break; + case "Tab": + this.ClearTabCacheInternal(int.Parse(data), clearRuntime); + break; + case "ServiceFrameworkRoutes": + this.ReloadServicesFrameworkRoutes(); + break; + } + } + + /// + /// Removes the internal. + /// + /// The cache key. + protected void RemoveInternal(string cacheKey) + { + // attempt remove from private dictionary + DataCache.RemoveFromPrivateDictionary(cacheKey); + + // remove item from memory + if (Cache[cacheKey] != null) + { + Cache.Remove(cacheKey); + } + } + private void ClearCacheInternal(string prefix, bool clearRuntime) { foreach (DictionaryEntry objDictionaryEntry in HttpRuntime.Cache) @@ -342,46 +413,6 @@ private void RemoveFormattedCacheKey(string CacheKeyBase, bool clearRuntime, par this.Remove(string.Format(GetCacheKey(CacheKeyBase), parameters)); } } - - /// - /// Clears the cache internal. - /// - /// Type of the cache. - /// The data. - /// if set to true clear runtime cache. - protected void ClearCacheInternal(string cacheType, string data, bool clearRuntime) - { - switch (cacheType) - { - case "Prefix": - this.ClearCacheInternal(data, clearRuntime); - break; - case "Host": - this.ClearHostCacheInternal(clearRuntime); - break; - case "Folder": - this.ClearFolderCacheInternal(int.Parse(data), clearRuntime); - break; - case "Module": - this.ClearModuleCacheInternal(int.Parse(data), clearRuntime); - break; - case "ModulePermissionsByPortal": - this.ClearModulePermissionsCachesByPortalInternal(int.Parse(data), clearRuntime); - break; - case "Portal": - this.ClearPortalCacheInternal(int.Parse(data), false, clearRuntime); - break; - case "PortalCascade": - this.ClearPortalCacheInternal(int.Parse(data), true, clearRuntime); - break; - case "Tab": - this.ClearTabCacheInternal(int.Parse(data), clearRuntime); - break; - case "ServiceFrameworkRoutes": - this.ReloadServicesFrameworkRoutes(); - break; - } - } private void ReloadServicesFrameworkRoutes() { @@ -391,37 +422,6 @@ private void ReloadServicesFrameworkRoutes() ServicesRoutingManager.RegisterServiceRoutes(); } - /// - /// Removes the internal. - /// - /// The cache key. - protected void RemoveInternal(string cacheKey) - { - // attempt remove from private dictionary - DataCache.RemoveFromPrivateDictionary(cacheKey); - - // remove item from memory - if (Cache[cacheKey] != null) - { - Cache.Remove(cacheKey); - } - } - - /// - /// Clears the specified type. - /// - /// The type. - /// The data. - public virtual void Clear(string type, string data) - { - this.ClearCacheInternal(type, data, false); - } - - public virtual IDictionaryEnumerator GetEnumerator() - { - return Cache.GetEnumerator(); - } - /// /// Gets the item. /// diff --git a/DNN Platform/Library/Services/Cache/FBCachingProvider.cs b/DNN Platform/Library/Services/Cache/FBCachingProvider.cs index 23b01c75fdd..252e42a862f 100644 --- a/DNN Platform/Library/Services/Cache/FBCachingProvider.cs +++ b/DNN Platform/Library/Services/Cache/FBCachingProvider.cs @@ -15,9 +15,9 @@ namespace DotNetNuke.Services.Cache public class FBCachingProvider : CachingProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FBCachingProvider)); internal const string CacheFileExtension = ".resources"; internal static string CachingDirectory = "Cache\\"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FBCachingProvider)); public override void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) diff --git a/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs b/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs index c254f9917b6..5cb0c4d78a9 100644 --- a/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs +++ b/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs @@ -11,6 +11,14 @@ namespace DotNetNuke.Services.ClientCapability public abstract class ClientCapabilityProvider : IClientCapabilityProvider { + public static IClientCapability CurrentClientCapability + { + get + { + return Instance().GetClientCapability(HttpContext.Current.Request); + } + } + /// /// Gets a value indicating whether support detect the device whether is a tablet. /// @@ -22,6 +30,11 @@ public virtual bool SupportsTabletDetection } } + public static ClientCapabilityProvider Instance() + { + return ComponentFactory.GetComponent(); + } + /// /// Returns ClientCapability based on userAgent. /// @@ -62,18 +75,5 @@ public virtual IClientCapability GetClientCapability(HttpRequest httpRequest) return clientCapability; } - - public static ClientCapabilityProvider Instance() - { - return ComponentFactory.GetComponent(); - } - - public static IClientCapability CurrentClientCapability - { - get - { - return Instance().GetClientCapability(HttpContext.Current.Request); - } - } } } diff --git a/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs b/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs index f43f1d1df2d..943f0c1de1f 100644 --- a/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs +++ b/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs @@ -12,6 +12,31 @@ namespace DotNetNuke.Services.ClientCapability using System.Web; using DotNetNuke.Common.Utilities; + + internal struct Page + { + public string id { get; set; } + + public bool liked { get; set; } + + public bool admin { get; set; } + } + + internal struct Age + { + public long min { get; set; } + + public long max { get; set; } + } + + internal struct User + { + public string locale { get; set; } + + public string country { get; set; } + + public Age age { get; set; } + } /// /// Make modules that are aware of Facebook’s signed_request – a parameter that is POSTed to the web page being loaded in the iFrame, @@ -20,6 +45,12 @@ namespace DotNetNuke.Services.ClientCapability /// public class FacebookRequestController { + private const string SignedRequestParameter = "signed_request"; + + public static string API_SECRET { get; set; } + + public static string APP_ID { get; set; } + public string AccessToken { get; set; } public DateTime Expires { get; set; } @@ -28,14 +59,8 @@ public class FacebookRequestController public long ProfileId { get; set; } - public static string API_SECRET { get; set; } - - public static string APP_ID { get; set; } - public string RawSignedRequest { get; set; } - private const string SignedRequestParameter = "signed_request"; - public bool IsValid { get; set; } public static FacebookRequest GetFacebookDetailsFromRequest(HttpRequest Request) @@ -174,31 +199,6 @@ private static DateTime ConvertToTimestamp(long value) } } - internal struct Page - { - public string id { get; set; } - - public bool liked { get; set; } - - public bool admin { get; set; } - } - - internal struct Age - { - public long min { get; set; } - - public long max { get; set; } - } - - internal struct User - { - public string locale { get; set; } - - public string country { get; set; } - - public Age age { get; set; } - } - internal struct FaceBookData { public User user { get; set; } diff --git a/DNN Platform/Library/Services/Connections/ConnectionsController.cs b/DNN Platform/Library/Services/Connections/ConnectionsController.cs index 6fbd5900687..223a088cb5c 100644 --- a/DNN Platform/Library/Services/Connections/ConnectionsController.cs +++ b/DNN Platform/Library/Services/Connections/ConnectionsController.cs @@ -14,11 +14,6 @@ namespace DotNetNuke.Services.Connections public class ConnectionsController : ServiceLocator, IConnectionsController { - protected override Func GetFactory() - { - return () => new ConnectionsController(); - } - public IList GetConnections(int portalId) { var connectors = ConnectionsManager.Instance.GetConnectors().Where(c => c.HasConfig(portalId)).ToList(); @@ -42,5 +37,10 @@ public IDictionary GetConnectionConfigs(int portalId, string nam return null; } + + protected override Func GetFactory() + { + return () => new ConnectionsController(); + } } } diff --git a/DNN Platform/Library/Services/Connections/ConnectionsManager.cs b/DNN Platform/Library/Services/Connections/ConnectionsManager.cs index ac98234212a..40293627678 100644 --- a/DNN Platform/Library/Services/Connections/ConnectionsManager.cs +++ b/DNN Platform/Library/Services/Connections/ConnectionsManager.cs @@ -16,15 +16,15 @@ namespace DotNetNuke.Services.Connections public sealed class ConnectionsManager : ServiceLocator, IConnectionsManager { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ConnectionsManager)); + private static readonly object LockerObject = new object(); + private static IDictionary _processors; + protected override Func GetFactory() { return () => new ConnectionsManager(); } - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ConnectionsManager)); - private static readonly object LockerObject = new object(); - private static IDictionary _processors; - public void RegisterConnections() { if (_processors == null) diff --git a/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs b/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs index 3ddc5bd1901..a65ef91e137 100644 --- a/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs +++ b/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs @@ -15,6 +15,11 @@ namespace DotNetNuke.Services.Connections public sealed class DynamicJsonConverter : JavaScriptConverter { + public override IEnumerable SupportedTypes + { + get { return new ReadOnlyCollection(new List(new[] { typeof(object) })); } + } + public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) @@ -29,11 +34,6 @@ public override IDictionary Serialize(object obj, JavaScriptSeri { throw new NotImplementedException(); } - - public override IEnumerable SupportedTypes - { - get { return new ReadOnlyCollection(new List(new[] { typeof(object) })); } - } private sealed class DynamicJsonObject : DynamicObject { @@ -56,6 +56,37 @@ public override string ToString() return sb.ToString(); } + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + if (!this._dictionary.TryGetValue(binder.Name, out result)) + { + // return null to avoid exception. caller can check for null this way... + result = null; + return true; + } + + result = WrapResultObject(result); + return true; + } + + public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) + { + if (indexes.Length == 1 && indexes[0] != null) + { + if (!this._dictionary.TryGetValue(indexes[0].ToString(), out result)) + { + // return null to avoid exception. caller can check for null this way... + result = null; + return true; + } + + result = WrapResultObject(result); + return true; + } + + return base.TryGetIndex(binder, indexes, out result); + } + private void ToString(StringBuilder sb) { var firstInDictionary = true; @@ -115,37 +146,6 @@ private void ToString(StringBuilder sb) sb.Append("}"); } - public override bool TryGetMember(GetMemberBinder binder, out object result) - { - if (!this._dictionary.TryGetValue(binder.Name, out result)) - { - // return null to avoid exception. caller can check for null this way... - result = null; - return true; - } - - result = WrapResultObject(result); - return true; - } - - public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) - { - if (indexes.Length == 1 && indexes[0] != null) - { - if (!this._dictionary.TryGetValue(indexes[0].ToString(), out result)) - { - // return null to avoid exception. caller can check for null this way... - result = null; - return true; - } - - result = WrapResultObject(result); - return true; - } - - return base.TryGetIndex(binder, indexes, out result); - } - private static object WrapResultObject(object result) { var dictionary = result as IDictionary; diff --git a/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs b/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs index 00b3ec3b9ba..26911bbf067 100644 --- a/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs +++ b/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs @@ -8,6 +8,11 @@ namespace DotNetNuke.Services.Cryptography public abstract class CryptographyProvider : ICryptographyProvider { + public static CryptographyProvider Instance() + { + return ComponentFactory.GetComponent(); + } + /// /// simple method that uses basic encryption to safely encode parameters. /// @@ -39,10 +44,5 @@ public abstract class CryptographyProvider : ICryptographyProvider /// the key to perform the decryption. /// decrypted string. public abstract string DecryptString(string message, string passphrase); - - public static CryptographyProvider Instance() - { - return ComponentFactory.GetComponent(); - } } } diff --git a/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs b/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs index 45002ddbcfc..0348de3d6e0 100644 --- a/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs +++ b/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs @@ -25,6 +25,60 @@ internal EventQueueConfiguration() internal Dictionary EventQueueSubscribers { get; set; } internal Dictionary PublishedEvents { get; set; } + + public static void RegisterEventSubscription(EventQueueConfiguration config, string eventname, SubscriberInfo subscriber) + { + var e = new PublishedEvent(); + e.EventName = eventname; + e.Subscribers = subscriber.ID; + config.PublishedEvents.Add(e.EventName, e); + if (!config.EventQueueSubscribers.ContainsKey(subscriber.ID)) + { + config.EventQueueSubscribers.Add(subscriber.ID, subscriber); + } + } + + internal static EventQueueConfiguration GetConfig() + { + var config = (EventQueueConfiguration)DataCache.GetCache("EventQueueConfig"); + if (config == null) + { + string filePath = Globals.HostMapPath + "EventQueue\\EventQueue.config"; + if (File.Exists(filePath)) + { + config = new EventQueueConfiguration(); + + // Deserialize into EventQueueConfiguration + config.Deserialize(FileSystemUtils.ReadFile(filePath)); + + // Set back into Cache + DataCache.SetCache("EventQueueConfig", config, new DNNCacheDependency(filePath)); + } + else + { + // make a default config file + config = new EventQueueConfiguration(); + config.PublishedEvents = new Dictionary(); + config.EventQueueSubscribers = new Dictionary(); + var subscriber = new SubscriberInfo("DNN Core"); + RegisterEventSubscription(config, "Application_Start", subscriber); + RegisterEventSubscription(config, "Application_Start_FirstRequest", subscriber); + SaveConfig(config, filePath); + } + } + + return config; + } + + internal static void SaveConfig(EventQueueConfiguration config, string filePath) + { + StreamWriter oStream = File.CreateText(filePath); + oStream.WriteLine(config.Serialize()); + oStream.Close(); + + // Set back into Cache + DataCache.SetCache("EventQueueConfig", config, new DNNCacheDependency(filePath)); + } private void Deserialize(string configXml) { @@ -53,18 +107,6 @@ private void Deserialize(string configXml) } } - public static void RegisterEventSubscription(EventQueueConfiguration config, string eventname, SubscriberInfo subscriber) - { - var e = new PublishedEvent(); - e.EventName = eventname; - e.Subscribers = subscriber.ID; - config.PublishedEvents.Add(e.EventName, e); - if (!config.EventQueueSubscribers.ContainsKey(subscriber.ID)) - { - config.EventQueueSubscribers.Add(subscriber.ID, subscriber); - } - } - private string Serialize() { var settings = new XmlWriterSettings(); @@ -114,47 +156,5 @@ private string Serialize() return sb.ToString(); } } - - internal static EventQueueConfiguration GetConfig() - { - var config = (EventQueueConfiguration)DataCache.GetCache("EventQueueConfig"); - if (config == null) - { - string filePath = Globals.HostMapPath + "EventQueue\\EventQueue.config"; - if (File.Exists(filePath)) - { - config = new EventQueueConfiguration(); - - // Deserialize into EventQueueConfiguration - config.Deserialize(FileSystemUtils.ReadFile(filePath)); - - // Set back into Cache - DataCache.SetCache("EventQueueConfig", config, new DNNCacheDependency(filePath)); - } - else - { - // make a default config file - config = new EventQueueConfiguration(); - config.PublishedEvents = new Dictionary(); - config.EventQueueSubscribers = new Dictionary(); - var subscriber = new SubscriberInfo("DNN Core"); - RegisterEventSubscription(config, "Application_Start", subscriber); - RegisterEventSubscription(config, "Application_Start_FirstRequest", subscriber); - SaveConfig(config, filePath); - } - } - - return config; - } - - internal static void SaveConfig(EventQueueConfiguration config, string filePath) - { - StreamWriter oStream = File.CreateText(filePath); - oStream.WriteLine(config.Serialize()); - oStream.Close(); - - // Set back into Cache - DataCache.SetCache("EventQueueConfig", config, new DNNCacheDependency(filePath)); - } } } diff --git a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs index 5d5a7d031d6..af907dd412b 100644 --- a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs +++ b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs @@ -43,6 +43,27 @@ namespace DotNetNuke.Services.EventQueue /// public class EventQueueController { + /// + /// Gets the messages. + /// + /// Name of the event. + /// event message collection. + public static EventMessageCollection GetMessages(string eventName) + { + return FillMessageCollection(DataProvider.Instance().GetEventMessages(eventName)); + } + + /// + /// Gets the messages. + /// + /// Name of the event. + /// The subscriber id. + /// + public static EventMessageCollection GetMessages(string eventName, string subscriberId) + { + return FillMessageCollection(DataProvider.Instance().GetEventMessagesBySubscriber(eventName, subscriberId)); + } + private static EventMessage FillMessage(IDataReader dr, bool CheckForOpenDataReader) { EventMessage message; @@ -130,27 +151,6 @@ private static string[] GetSubscribers(string eventName) return subscribers; } - - /// - /// Gets the messages. - /// - /// Name of the event. - /// event message collection. - public static EventMessageCollection GetMessages(string eventName) - { - return FillMessageCollection(DataProvider.Instance().GetEventMessages(eventName)); - } - - /// - /// Gets the messages. - /// - /// Name of the event. - /// The subscriber id. - /// - public static EventMessageCollection GetMessages(string eventName, string subscriberId) - { - return FillMessageCollection(DataProvider.Instance().GetEventMessagesBySubscriber(eventName, subscriberId)); - } /// /// Processes the messages. diff --git a/DNN Platform/Library/Services/Exceptions/Exceptions.cs b/DNN Platform/Library/Services/Exceptions/Exceptions.cs index 5bffc952962..d8b08813b21 100644 --- a/DNN Platform/Library/Services/Exceptions/Exceptions.cs +++ b/DNN Platform/Library/Services/Exceptions/Exceptions.cs @@ -102,6 +102,20 @@ public static ExceptionInfo GetExceptionInfo(Exception e) return objExceptionInfo; } + public static void ProcessHttpException() + { + var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); + var exc = new HttpException(404, notFoundErrorString); + ProcessHttpException(exc, HttpContext.Current.Request.RawUrl); + } + + public static void ProcessHttpException(string URL) + { + var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); + var exc = new HttpException(404, notFoundErrorString); + ProcessHttpException(exc, URL); + } + /// /// Threads the abort check if the exception is a ThreadAbortCheck. /// @@ -120,30 +134,37 @@ private static bool ThreadAbortCheck(Exception exc) } } - public static void ProcessHttpException() + public static void ProcessHttpException(HttpException exc) { - var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); - var exc = new HttpException(404, notFoundErrorString); ProcessHttpException(exc, HttpContext.Current.Request.RawUrl); } - public static void ProcessHttpException(string URL) + public static void ProcessHttpException(HttpRequest request) { var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); var exc = new HttpException(404, notFoundErrorString); - ProcessHttpException(exc, URL); + ProcessHttpException(exc, request.RawUrl); } - public static void ProcessHttpException(HttpException exc) + /// + /// Processes the module load exception. + /// + /// The portal module base. + /// The exc. + public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBase, Exception exc) { - ProcessHttpException(exc, HttpContext.Current.Request.RawUrl); + ProcessModuleLoadException((Control)objPortalModuleBase, exc); } - public static void ProcessHttpException(HttpRequest request) + /// + /// Processes the module load exception. + /// + /// The portal module base. + /// The exc. + /// if set to true display error message. + public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBase, Exception exc, bool DisplayErrorMessage) { - var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); - var exc = new HttpException(404, notFoundErrorString); - ProcessHttpException(exc, request.RawUrl); + ProcessModuleLoadException((Control)objPortalModuleBase, exc, DisplayErrorMessage); } private static void ProcessHttpException(HttpException exc, string URL) @@ -168,27 +189,6 @@ private static void ProcessHttpException(HttpException exc, string URL) throw exc; } - /// - /// Processes the module load exception. - /// - /// The portal module base. - /// The exc. - public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBase, Exception exc) - { - ProcessModuleLoadException((Control)objPortalModuleBase, exc); - } - - /// - /// Processes the module load exception. - /// - /// The portal module base. - /// The exc. - /// if set to true display error message. - public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBase, Exception exc, bool DisplayErrorMessage) - { - ProcessModuleLoadException((Control)objPortalModuleBase, exc, DisplayErrorMessage); - } - /// /// Processes the module load exception. /// @@ -278,8 +278,8 @@ public static void ProcessModuleLoadException(string FriendlyMessage, Control ct /// The exc. /// if set to true display error message. public static void ProcessModuleLoadException(string FriendlyMessage, Control ctrl, Exception exc, bool DisplayErrorMessage) - { - // Exit Early if ThreadAbort Exception + { + // Exit Early if ThreadAbort Exception if (ThreadAbortCheck(exc)) { return; diff --git a/DNN Platform/Library/Services/Exceptions/SearchException.cs b/DNN Platform/Library/Services/Exceptions/SearchException.cs index 7fbf889cd29..6ea75bdf999 100644 --- a/DNN Platform/Library/Services/Exceptions/SearchException.cs +++ b/DNN Platform/Library/Services/Exceptions/SearchException.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Services.Exceptions using DotNetNuke.Services.Search; - #pragma warning disable 0618 +#pragma warning disable 0618 public class SearchException : BasePortalException { private readonly SearchItemInfo m_SearchItem; @@ -30,6 +30,6 @@ public SearchItemInfo SearchItem return this.m_SearchItem; } } - } - #pragma warning restore 0618 + } +#pragma warning restore 0618 } diff --git a/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs b/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs index 3e11e931124..b00259e6fae 100644 --- a/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs @@ -14,8 +14,8 @@ namespace DotNetNuke.Services.FileSystem public class FileContentTypeManager : ComponentBase, IFileContentTypeManager { - private IDictionary _contentTypes; private static readonly object _threadLocker = new object(); + private IDictionary _contentTypes; public virtual IDictionary ContentTypes { diff --git a/DNN Platform/Library/Services/FileSystem/FileInfo.cs b/DNN Platform/Library/Services/FileSystem/FileInfo.cs index a53e5405a99..b5ea750fa37 100644 --- a/DNN Platform/Library/Services/FileSystem/FileInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FileInfo.cs @@ -395,6 +395,20 @@ public bool IsEnabled /// Gets or sets a reference to ContentItem, to use in Workflows. /// public int ContentItemID { get; set; } + + [XmlIgnore] + public int KeyID + { + get + { + return this.FileId; + } + + set + { + this.FileId = value; + } + } public void Fill(IDataReader dr) { @@ -425,20 +439,6 @@ public void Fill(IDataReader dr) this.HasBeenPublished = Convert.ToBoolean(dr["HasBeenPublished"]); this.FillBaseProperties(dr); } - - [XmlIgnore] - public int KeyID - { - get - { - return this.FileId; - } - - set - { - this.FileId = value; - } - } private void LoadImageProperties() { diff --git a/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs b/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs index 9b9944ec55b..55ada41a337 100644 --- a/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs +++ b/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs @@ -16,23 +16,40 @@ namespace DotNetNuke.Services.FileSystem public class FileLinkClickController : ServiceLocator, IFileLinkClickController { + public string GetFileLinkClick(IFileInfo file) + { + Requires.NotNull("file", file); + var portalId = file.PortalId; + var linkClickPortalSettigns = this.GetPortalSettingsForLinkClick(portalId); + + return TestableGlobals.Instance.LinkClick(string.Format("fileid={0}", file.FileId), Null.NullInteger, Null.NullInteger, true, false, portalId, linkClickPortalSettigns.EnableUrlLanguage, linkClickPortalSettigns.PortalGUID); + } + + public int GetFileIdFromLinkClick(NameValueCollection queryParams) + { + var linkClickPortalSettings = this.GetPortalSettingsForLinkClick(this.GetPortalIdFromLinkClick(queryParams)); + var strFileId = UrlUtils.DecryptParameter(queryParams["fileticket"], linkClickPortalSettings.PortalGUID); + int fileId; + return int.TryParse(strFileId, out fileId) ? fileId : -1; + } + private LinkClickPortalSettings GetPortalSettingsForLinkClick(int portalId) { if (portalId == Null.NullInteger) { - return new LinkClickPortalSettings - { - PortalGUID = Host.GUID, - EnableUrlLanguage = Host.EnableUrlLanguage, - }; + return new LinkClickPortalSettings + { + PortalGUID = Host.GUID, + EnableUrlLanguage = Host.EnableUrlLanguage, + }; } var portalSettings = new PortalSettings(portalId); - return new LinkClickPortalSettings - { - PortalGUID = portalSettings.GUID.ToString(), - EnableUrlLanguage = portalSettings.EnableUrlLanguage, - }; + return new LinkClickPortalSettings + { + PortalGUID = portalSettings.GUID.ToString(), + EnableUrlLanguage = portalSettings.EnableUrlLanguage, + }; } private int GetPortalIdFromLinkClick(NameValueCollection queryParams) @@ -54,23 +71,6 @@ private int GetPortalIdFromLinkClick(NameValueCollection queryParams) return PortalSettings.Current.PortalId; } - public string GetFileLinkClick(IFileInfo file) - { - Requires.NotNull("file", file); - var portalId = file.PortalId; - var linkClickPortalSettigns = this.GetPortalSettingsForLinkClick(portalId); - - return TestableGlobals.Instance.LinkClick(string.Format("fileid={0}", file.FileId), Null.NullInteger, Null.NullInteger, true, false, portalId, linkClickPortalSettigns.EnableUrlLanguage, linkClickPortalSettigns.PortalGUID); - } - - public int GetFileIdFromLinkClick(NameValueCollection queryParams) - { - var linkClickPortalSettings = this.GetPortalSettingsForLinkClick(this.GetPortalIdFromLinkClick(queryParams)); - var strFileId = UrlUtils.DecryptParameter(queryParams["fileticket"], linkClickPortalSettings.PortalGUID); - int fileId; - return int.TryParse(strFileId, out fileId) ? fileId : -1; - } - protected override Func GetFactory() { return () => new FileLinkClickController(); diff --git a/DNN Platform/Library/Services/FileSystem/FileManager.cs b/DNN Platform/Library/Services/FileSystem/FileManager.cs index 61270bed796..8c0f807918e 100644 --- a/DNN Platform/Library/Services/FileSystem/FileManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FileManager.cs @@ -46,14 +46,125 @@ namespace DotNetNuke.Services.FileSystem /// public class FileManager : ComponentBase, IFileManager { + private const int BufferSize = 4096; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileManager)); public virtual IDictionary ContentTypes { get { return FileContentTypeManager.Instance.ContentTypes; } } + + private FileExtensionWhitelist WhiteList + { + get + { + var user = UserController.Instance.GetCurrentUserInfo(); + if (user != null) + { + if (user.IsSuperUser) + { + return Host.AllowedExtensionWhitelist; + } - private const int BufferSize = 4096; + if (!user.IsAdmin) + { + var settings = PortalSettings.Current; + if (settings != null) + { + return settings.AllowedExtensionsWhitelist; + } + } + } + + return Host.AllowedExtensionWhitelist; + } + } + + /// + /// Adds a file to the specified folder. + /// + /// The folder where to add the file. + /// The name of the file. + /// The content of the file. + /// A IFileInfo as specified by the parameters. + public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent) + { + return this.AddFile(folder, fileName, fileContent, true, false, false, this.GetContentType(Path.GetExtension(fileName)), this.GetCurrentUserID()); + } + + /// + /// Adds a file to the specified folder. + /// + /// The folder where to add the file. + /// The name of the file. + /// The content of the file. + /// Indicates if the file has to be over-written if it exits. + /// A IFileInfo as specified by the parameters. + public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent, bool overwrite) + { + return this.AddFile(folder, fileName, fileContent, overwrite, false, false, this.GetContentType(Path.GetExtension(fileName)), this.GetCurrentUserID()); + } + + private static ImageFormat GetImageFormat(Image img) + { + if (img.RawFormat.Equals(ImageFormat.Jpeg)) + { + return ImageFormat.Jpeg; + } + + if (img.RawFormat.Equals(ImageFormat.Bmp)) + { + return ImageFormat.Bmp; + } + + if (img.RawFormat.Equals(ImageFormat.Png)) + { + return ImageFormat.Png; + } + + if (img.RawFormat.Equals(ImageFormat.Emf)) + { + return ImageFormat.Emf; + } + + if (img.RawFormat.Equals(ImageFormat.Exif)) + { + return ImageFormat.Exif; + } + + if (img.RawFormat.Equals(ImageFormat.Gif)) + { + return ImageFormat.Gif; + } + + if (img.RawFormat.Equals(ImageFormat.Icon)) + { + return ImageFormat.Icon; + } + + if (img.RawFormat.Equals(ImageFormat.MemoryBmp)) + { + return ImageFormat.Jpeg; + } + + if (img.RawFormat.Equals(ImageFormat.Tiff)) + { + return ImageFormat.Tiff; + } + else + { + return ImageFormat.Wmf; + } + } + + private static Stream ToStream(Image image, ImageFormat formaw) + { + var stream = new MemoryStream(); + image.Save(stream, formaw); + stream.Position = 0; + return stream; + } private void AddFileToFolderProvider(Stream fileContent, string fileName, IFolderInfo destinationFolder, FolderProvider provider) { @@ -191,66 +302,6 @@ private void RotateFlipImage(ref Stream content) Logger.Error(ex); } } - - private static ImageFormat GetImageFormat(Image img) - { - if (img.RawFormat.Equals(ImageFormat.Jpeg)) - { - return ImageFormat.Jpeg; - } - - if (img.RawFormat.Equals(ImageFormat.Bmp)) - { - return ImageFormat.Bmp; - } - - if (img.RawFormat.Equals(ImageFormat.Png)) - { - return ImageFormat.Png; - } - - if (img.RawFormat.Equals(ImageFormat.Emf)) - { - return ImageFormat.Emf; - } - - if (img.RawFormat.Equals(ImageFormat.Exif)) - { - return ImageFormat.Exif; - } - - if (img.RawFormat.Equals(ImageFormat.Gif)) - { - return ImageFormat.Gif; - } - - if (img.RawFormat.Equals(ImageFormat.Icon)) - { - return ImageFormat.Icon; - } - - if (img.RawFormat.Equals(ImageFormat.MemoryBmp)) - { - return ImageFormat.Jpeg; - } - - if (img.RawFormat.Equals(ImageFormat.Tiff)) - { - return ImageFormat.Tiff; - } - else - { - return ImageFormat.Wmf; - } - } - - private static Stream ToStream(Image image, ImageFormat formaw) - { - var stream = new MemoryStream(); - image.Save(stream, formaw); - stream.Position = 0; - return stream; - } // Match the orientation code to the correct rotation: private static RotateFlipType OrientationToFlipType(string orientation) @@ -278,57 +329,6 @@ private static RotateFlipType OrientationToFlipType(string orientation) } } - private FileExtensionWhitelist WhiteList - { - get - { - var user = UserController.Instance.GetCurrentUserInfo(); - if (user != null) - { - if (user.IsSuperUser) - { - return Host.AllowedExtensionWhitelist; - } - - if (!user.IsAdmin) - { - var settings = PortalSettings.Current; - if (settings != null) - { - return settings.AllowedExtensionsWhitelist; - } - } - } - - return Host.AllowedExtensionWhitelist; - } - } - - /// - /// Adds a file to the specified folder. - /// - /// The folder where to add the file. - /// The name of the file. - /// The content of the file. - /// A IFileInfo as specified by the parameters. - public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent) - { - return this.AddFile(folder, fileName, fileContent, true, false, false, this.GetContentType(Path.GetExtension(fileName)), this.GetCurrentUserID()); - } - - /// - /// Adds a file to the specified folder. - /// - /// The folder where to add the file. - /// The name of the file. - /// The content of the file. - /// Indicates if the file has to be over-written if it exits. - /// A IFileInfo as specified by the parameters. - public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fileContent, bool overwrite) - { - return this.AddFile(folder, fileName, fileContent, overwrite, false, false, this.GetContentType(Path.GetExtension(fileName)), this.GetCurrentUserID()); - } - /// /// Adds a file to the specified folder. /// @@ -579,6 +579,111 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil } } + /// + /// Copies the specified file into the specified folder. + /// + /// The file to copy. + /// The folder where to copy the file to. + /// Thrown when file or destinationFolder are null. + /// A IFileInfo with the information of the copied file. + public virtual IFileInfo CopyFile(IFileInfo file, IFolderInfo destinationFolder) + { + Requires.NotNull("file", file); + Requires.NotNull("destinationFolder", destinationFolder); + + if (file.FolderMappingID == destinationFolder.FolderMappingID) + { + if (!FolderPermissionController.Instance.CanAddFolder(destinationFolder)) + { + throw new PermissionsNotMetException(Localization.GetExceptionMessage("CopyFilePermissionsNotMet", "Permissions are not met. The file has not been copied.")); + } + + if (!PortalController.Instance.HasSpaceAvailable(destinationFolder.PortalID, file.Size)) + { + throw new NoSpaceAvailableException(Localization.GetExceptionMessage("CopyFileNoSpaceAvailable", "The portal has no space available to store the specified file. The file has not been copied.")); + } + + var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); + try + { + // check for existing file + var existingFile = this.GetFile(destinationFolder, file.FileName, true); + if (existingFile != null) + { + this.DeleteFile(existingFile); + } + + var folder = FolderManager.Instance.GetFolder(file.FolderId); + FolderProvider.Instance(folderMapping.FolderProviderType).CopyFile(folder.MappedPath, file.FileName, destinationFolder.MappedPath, folderMapping); + } + catch (Exception ex) + { + Logger.Error(ex); + throw new FolderProviderException(Localization.GetExceptionMessage("CopyFileUnderlyingSystemError", "The underlying system throw an exception. The file has not been copied."), ex); + } + + // copy Content Item + var contentItemID = this.CopyContentItem(file.ContentItemID); + + var fileId = DataProvider.Instance().AddFile( + file.PortalId, + Guid.NewGuid(), + Guid.NewGuid(), + file.FileName, + file.Extension, + file.Size, + file.Width, + file.Height, + file.ContentType, + destinationFolder.FolderPath, + destinationFolder.FolderID, + this.GetCurrentUserID(), + file.SHA1Hash, + DateTime.Now, + file.Title, + file.Description, + file.StartDate, + file.EndDate, + file.EnablePublishPeriod, + contentItemID); + + var copiedFile = this.GetFile(fileId, true); + + // Notify added file event + this.OnFileAdded(copiedFile, destinationFolder, this.GetCurrentUserID()); + + return copiedFile; + } + + using (var fileContent = this.GetFileContent(file)) + { + // check for existing file + var existingFile = this.GetFile(destinationFolder, file.FileName, true); + if (existingFile != null) + { + this.DeleteFile(existingFile); + } + + return this.AddFile(destinationFolder, file.FileName, fileContent, true, true, file.ContentType); + } + } + + /// + /// Deletes the specified file. + /// + /// The file to delete. + /// Thrown when file is null. + /// Thrown when the underlying system throw an exception. + public virtual void DeleteFile(IFileInfo file) + { + Requires.NotNull("file", file); + FileDeletionController.Instance.DeleteFile(file); + this.ClearFolderCache(file.PortalId); + + // Notify File Delete Event + this.OnFileDeleted(file, this.GetCurrentUserID()); + } + private void CheckFileAddingRestrictions(IFolderInfo folder, string fileName, bool checkPermissions, bool ignoreWhiteList) { @@ -659,203 +764,98 @@ private void SetImageProperties(IFileInfo file, Stream fileContent) file.Height = image.Height; } } - catch - { - file.ContentType = "application/octet-stream"; - } - finally - { - fileContent.Position = 0; - } - } - - private void CheckFileWritingRestrictions(IFolderInfo folder, string fileName, Stream fileContent, IFileInfo oldFile, int createdByUserId) - { - if (!PortalController.Instance.HasSpaceAvailable(folder.PortalID, fileContent.Length)) - { - throw new NoSpaceAvailableException( - Localization.GetExceptionMessage( - "AddFileNoSpaceAvailable", - "The portal has no space available to store the specified file. The file has not been added.")); - } - - // Publish Period - if (oldFile != null && FileLockingController.Instance.IsFileOutOfPublishPeriod(oldFile, folder.PortalID, createdByUserId)) - { - throw new FileLockedException( - Localization.GetExceptionMessage( - "FileLockedOutOfPublishPeriodError", - "File locked. The file cannot be updated because it is out of Publish Period")); - } - - if (!FileSecurityController.Instance.Validate(fileName, fileContent)) - { - 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)); - } - } - - private void ManageFileAdding(int createdByUserID, Workflow folderWorkflow, bool fileExists, FileInfo file) - { - if (folderWorkflow == null || !fileExists) - { - this.AddFile(file, createdByUserID); - } - else - { - // File Events for updating will not be fired. Only events for adding nust be fired - this.UpdateFile(file, true, false); - } - - if (folderWorkflow != null && this.StartWorkflow(createdByUserID, folderWorkflow, fileExists, file.ContentItemID)) - { - if (!fileExists) // if file exists it could have been published. So We don't have to update the field - { - // Maybe here we can set HasBeenPublished as 0 - DataProvider.Instance().SetFileHasBeenPublished(file.FileId, false); - } - } - } - - private void AddFile(IFileInfo file, int createdByUserID) - { - file.FileId = DataProvider.Instance().AddFile( - file.PortalId, - file.UniqueId, - file.VersionGuid, - file.FileName, - file.Extension, - file.Size, - file.Width, - file.Height, - file.ContentType, - file.Folder, - file.FolderId, - createdByUserID, - file.SHA1Hash, - file.LastModificationTime, - file.Title, - file.Description, - file.StartDate, - file.EndDate, - file.EnablePublishPeriod, - file.ContentItemID); - } - - private string ProcessVersioning(IFolderInfo folder, IFileInfo oldFile, IFileInfo file, int createdByUserID) - { - if (oldFile != null && FileVersionController.Instance.IsFolderVersioned(folder) && oldFile.SHA1Hash != file.SHA1Hash) - { - return FileVersionController.Instance.AddFileVersion(oldFile, createdByUserID); - } - - return file.FileName; - } - - /// - /// Copies the specified file into the specified folder. - /// - /// The file to copy. - /// The folder where to copy the file to. - /// Thrown when file or destinationFolder are null. - /// A IFileInfo with the information of the copied file. - public virtual IFileInfo CopyFile(IFileInfo file, IFolderInfo destinationFolder) - { - Requires.NotNull("file", file); - Requires.NotNull("destinationFolder", destinationFolder); - - if (file.FolderMappingID == destinationFolder.FolderMappingID) - { - if (!FolderPermissionController.Instance.CanAddFolder(destinationFolder)) - { - throw new PermissionsNotMetException(Localization.GetExceptionMessage("CopyFilePermissionsNotMet", "Permissions are not met. The file has not been copied.")); - } - - if (!PortalController.Instance.HasSpaceAvailable(destinationFolder.PortalID, file.Size)) - { - throw new NoSpaceAvailableException(Localization.GetExceptionMessage("CopyFileNoSpaceAvailable", "The portal has no space available to store the specified file. The file has not been copied.")); - } - - var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - try - { - // check for existing file - var existingFile = this.GetFile(destinationFolder, file.FileName, true); - if (existingFile != null) - { - this.DeleteFile(existingFile); - } - - var folder = FolderManager.Instance.GetFolder(file.FolderId); - FolderProvider.Instance(folderMapping.FolderProviderType).CopyFile(folder.MappedPath, file.FileName, destinationFolder.MappedPath, folderMapping); - } - catch (Exception ex) - { - Logger.Error(ex); - throw new FolderProviderException(Localization.GetExceptionMessage("CopyFileUnderlyingSystemError", "The underlying system throw an exception. The file has not been copied."), ex); - } - - // copy Content Item - var contentItemID = this.CopyContentItem(file.ContentItemID); - - var fileId = DataProvider.Instance().AddFile( - file.PortalId, - Guid.NewGuid(), - Guid.NewGuid(), - file.FileName, - file.Extension, - file.Size, - file.Width, - file.Height, - file.ContentType, - destinationFolder.FolderPath, - destinationFolder.FolderID, - this.GetCurrentUserID(), - file.SHA1Hash, - DateTime.Now, - file.Title, - file.Description, - file.StartDate, - file.EndDate, - file.EnablePublishPeriod, - contentItemID); + catch + { + file.ContentType = "application/octet-stream"; + } + finally + { + fileContent.Position = 0; + } + } - var copiedFile = this.GetFile(fileId, true); + private void CheckFileWritingRestrictions(IFolderInfo folder, string fileName, Stream fileContent, IFileInfo oldFile, int createdByUserId) + { + if (!PortalController.Instance.HasSpaceAvailable(folder.PortalID, fileContent.Length)) + { + throw new NoSpaceAvailableException( + Localization.GetExceptionMessage( + "AddFileNoSpaceAvailable", + "The portal has no space available to store the specified file. The file has not been added.")); + } - // Notify added file event - this.OnFileAdded(copiedFile, destinationFolder, this.GetCurrentUserID()); + // Publish Period + if (oldFile != null && FileLockingController.Instance.IsFileOutOfPublishPeriod(oldFile, folder.PortalID, createdByUserId)) + { + throw new FileLockedException( + Localization.GetExceptionMessage( + "FileLockedOutOfPublishPeriodError", + "File locked. The file cannot be updated because it is out of Publish Period")); + } - return copiedFile; + if (!FileSecurityController.Instance.Validate(fileName, fileContent)) + { + 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)); } + } - using (var fileContent = this.GetFileContent(file)) + private void ManageFileAdding(int createdByUserID, Workflow folderWorkflow, bool fileExists, FileInfo file) + { + if (folderWorkflow == null || !fileExists) { - // check for existing file - var existingFile = this.GetFile(destinationFolder, file.FileName, true); - if (existingFile != null) + this.AddFile(file, createdByUserID); + } + else + { + // File Events for updating will not be fired. Only events for adding nust be fired + this.UpdateFile(file, true, false); + } + + if (folderWorkflow != null && this.StartWorkflow(createdByUserID, folderWorkflow, fileExists, file.ContentItemID)) + { + if (!fileExists) // if file exists it could have been published. So We don't have to update the field { - this.DeleteFile(existingFile); + // Maybe here we can set HasBeenPublished as 0 + DataProvider.Instance().SetFileHasBeenPublished(file.FileId, false); } - - return this.AddFile(destinationFolder, file.FileName, fileContent, true, true, file.ContentType); } } - /// - /// Deletes the specified file. - /// - /// The file to delete. - /// Thrown when file is null. - /// Thrown when the underlying system throw an exception. - public virtual void DeleteFile(IFileInfo file) + private void AddFile(IFileInfo file, int createdByUserID) { - Requires.NotNull("file", file); - FileDeletionController.Instance.DeleteFile(file); - this.ClearFolderCache(file.PortalId); + file.FileId = DataProvider.Instance().AddFile( + file.PortalId, + file.UniqueId, + file.VersionGuid, + file.FileName, + file.Extension, + file.Size, + file.Width, + file.Height, + file.ContentType, + file.Folder, + file.FolderId, + createdByUserID, + file.SHA1Hash, + file.LastModificationTime, + file.Title, + file.Description, + file.StartDate, + file.EndDate, + file.EnablePublishPeriod, + file.ContentItemID); + } + + private string ProcessVersioning(IFolderInfo folder, IFileInfo oldFile, IFileInfo file, int createdByUserID) + { + if (oldFile != null && FileVersionController.Instance.IsFolderVersioned(folder) && oldFile.SHA1Hash != file.SHA1Hash) + { + return FileVersionController.Instance.AddFileVersion(oldFile, createdByUserID); + } - // Notify File Delete Event - this.OnFileDeleted(file, this.GetCurrentUserID()); + return file.FileName; } /// @@ -1566,65 +1566,6 @@ internal virtual void MoveVersions(IFileInfo file, IFolderInfo destinationFolder } } - private bool CanUpdateWhenApproving(IFolderInfo folder, ContentItem item, int createdByUserID) - { - if (WorkflowEngine.Instance.IsWorkflowOnDraft(item.ContentItemId)) - { - ////We assume User can add content to folder - return true; - } - - return WorkflowSecurity.Instance.HasStateReviewerPermission(folder.PortalID, createdByUserID, item.StateID); - } - - private bool StartWorkflow(int createdByUserID, Workflow folderWorkflow, bool fileExists, int contentItemID) - { - if (WorkflowEngine.Instance.IsWorkflowCompleted(contentItemID)) - { - WorkflowEngine.Instance.StartWorkflow(folderWorkflow.WorkflowID, contentItemID, createdByUserID); - return true; - } - - return false; - } - - private string UpdateWhileApproving(IFolderInfo folder, int createdByUserID, IFileInfo file, IFileInfo oldFile, Stream content) - { - var contentController = new ContentController(); - bool workflowCompleted = WorkflowEngine.Instance.IsWorkflowCompleted(file.ContentItemID); - - var isDatabaseMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID).MappingName == "Database"; - - // If the file does not exist, then the field would not has value. - // Currently, first upload has not version file - if (oldFile == null || !oldFile.HasBeenPublished) - { - return file.FileName; - } - - if (workflowCompleted) // We assume User can add content to folder - { - return isDatabaseMapping ? FileVersionController.Instance.AddFileVersion(file, createdByUserID, false, false, content) : FileVersionController.Instance.AddFileVersion(file, createdByUserID, false); - } - - if (this.CanUpdateWhenApproving(folder, contentController.GetContentItem(file.ContentItemID), createdByUserID)) - { - // Update the Unpublished version - var versions = FileVersionController.Instance.GetFileVersions(file).ToArray(); - if (versions.Any()) - { - FileVersionController.Instance.DeleteFileVersion(file, versions.OrderByDescending(f => f.Version).FirstOrDefault().Version); - } - - return isDatabaseMapping ? FileVersionController.Instance.AddFileVersion(file, createdByUserID, false, false, content) : FileVersionController.Instance.AddFileVersion(file, createdByUserID, false); - } - - throw new FileLockedException( - Localization.GetExceptionMessage( - "FileLockedRunningWorkflowError", - "File locked. The file cannot be updated because it has a running workflow")); - } - /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void AutoSyncFile(IFileInfo file) { @@ -1648,10 +1589,10 @@ internal virtual void AutoSyncFile(IFileInfo file) { this.DeleteFile(file); } - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual int ExtractFiles(IFileInfo file, IFolderInfo destinationFolder, IList invalidFiles) { var folderManager = FolderManager.Instance; @@ -1732,6 +1673,65 @@ internal virtual int ExtractFiles(IFileInfo file, IFolderInfo destinationFolder, return exactFilesCount; } + + private bool CanUpdateWhenApproving(IFolderInfo folder, ContentItem item, int createdByUserID) + { + if (WorkflowEngine.Instance.IsWorkflowOnDraft(item.ContentItemId)) + { + ////We assume User can add content to folder + return true; + } + + return WorkflowSecurity.Instance.HasStateReviewerPermission(folder.PortalID, createdByUserID, item.StateID); + } + + private bool StartWorkflow(int createdByUserID, Workflow folderWorkflow, bool fileExists, int contentItemID) + { + if (WorkflowEngine.Instance.IsWorkflowCompleted(contentItemID)) + { + WorkflowEngine.Instance.StartWorkflow(folderWorkflow.WorkflowID, contentItemID, createdByUserID); + return true; + } + + return false; + } + + private string UpdateWhileApproving(IFolderInfo folder, int createdByUserID, IFileInfo file, IFileInfo oldFile, Stream content) + { + var contentController = new ContentController(); + bool workflowCompleted = WorkflowEngine.Instance.IsWorkflowCompleted(file.ContentItemID); + + var isDatabaseMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID).MappingName == "Database"; + + // If the file does not exist, then the field would not has value. + // Currently, first upload has not version file + if (oldFile == null || !oldFile.HasBeenPublished) + { + return file.FileName; + } + + if (workflowCompleted) // We assume User can add content to folder + { + return isDatabaseMapping ? FileVersionController.Instance.AddFileVersion(file, createdByUserID, false, false, content) : FileVersionController.Instance.AddFileVersion(file, createdByUserID, false); + } + + if (this.CanUpdateWhenApproving(folder, contentController.GetContentItem(file.ContentItemID), createdByUserID)) + { + // Update the Unpublished version + var versions = FileVersionController.Instance.GetFileVersions(file).ToArray(); + if (versions.Any()) + { + FileVersionController.Instance.DeleteFileVersion(file, versions.OrderByDescending(f => f.Version).FirstOrDefault().Version); + } + + return isDatabaseMapping ? FileVersionController.Instance.AddFileVersion(file, createdByUserID, false, false, content) : FileVersionController.Instance.AddFileVersion(file, createdByUserID, false); + } + + throw new FileLockedException( + Localization.GetExceptionMessage( + "FileLockedRunningWorkflowError", + "File locked. The file cannot be updated because it has a running workflow")); + } /// This member is reserved for internal use and is not intended to be used directly from your code. internal void EnsureZipFolder(string fileName, IFolderInfo destinationFolder) @@ -1775,17 +1775,17 @@ internal void EnsureZipFolder(string fileName, IFolderInfo destinationFolder) parentFolder = folderManager.GetFolder(destinationFolder.PortalID, newFolderPath); } } - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual Stream GetAutoDeleteFileStream(string filePath) { return new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, BufferSize, FileOptions.DeleteOnClose); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual int GetCurrentUserID() { return UserController.Instance.GetCurrentUserInfo().UserID; @@ -1817,31 +1817,31 @@ internal virtual string GetHash(Stream stream) internal virtual string GetHash(IFileInfo fileInfo) { return FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(fileInfo.FolderMappingID).FolderProviderType).GetHashCode(fileInfo); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual string GetHostMapPath() { return TestableGlobals.Instance.HostMapPath; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual Image GetImageFromStream(Stream stream) { return Image.FromStream(stream); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual Globals.PerformanceSettings GetPerformanceSetting() { return Host.PerformanceSetting; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool IsAllowedExtension(string fileName) { var extension = Path.GetExtension(fileName); @@ -1852,18 +1852,18 @@ internal virtual bool IsAllowedExtension(string fileName) return !string.IsNullOrEmpty(extension) && this.WhiteList.IsAllowedExtension(extension) && !Globals.FileExtensionRegex.IsMatch(fileName); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool IsValidFilename(string fileName) { // regex ensures the file is a valid filename and doesn't include illegal characters return Globals.FileValidNameRegex.IsMatch(fileName); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool IsFileAutoSyncEnabled() { return Host.EnableFileAutoSync; diff --git a/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs b/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs index 15c8cf34f43..8d1bf75c243 100644 --- a/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs +++ b/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs @@ -22,6 +22,8 @@ namespace DotNetNuke.Services.FileSystem public class FileServerHandler : IHttpHandler { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileServerHandler)); + + public bool IsReusable => true; /// ----------------------------------------------------------------------------- /// @@ -136,8 +138,8 @@ public void ProcessRequest(HttpContext context) // get optional parameters bool blnForceDownload = false; if ((context.Request.QueryString["forcedownload"] != null) || (context.Request.QueryString["contenttype"] != null)) - { - bool.TryParse(context.Request.QueryString["forcedownload"], out blnForceDownload); + { + bool.TryParse(context.Request.QueryString["forcedownload"], out blnForceDownload); } var contentDisposition = blnForceDownload ? ContentDisposition.Attachment : ContentDisposition.Inline; @@ -264,7 +266,5 @@ private void Handle404Exception(HttpContext context, string url) UrlUtils.Handle404Exception(context.Response, PortalController.Instance.GetCurrentPortalSettings()); } } - - public bool IsReusable => true; } } diff --git a/DNN Platform/Library/Services/FileSystem/FileVersionController.cs b/DNN Platform/Library/Services/FileSystem/FileVersionController.cs index 4b04eca6206..01c2bbd9821 100644 --- a/DNN Platform/Library/Services/FileSystem/FileVersionController.cs +++ b/DNN Platform/Library/Services/FileSystem/FileVersionController.cs @@ -255,14 +255,31 @@ public void RollbackFileVersion(IFileInfo file, int version, int userId) this.RemoveOldestsVersions(file); } + + internal static string GetVersionedFilename(IFileInfo file, int version) + { + return string.Format("{0}_{1}.v.resources", file.FileId, version); + } + + private static void RenameFile(IFileInfo file, string newFileName) + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); + if (folderMapping != null) + { + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); + folderProvider.RenameFile(file, newFileName); + } + + DataCache.RemoveCache("GetFileById" + file.FileId); + } private void OnFileChanged(IFileInfo fileInfo, int userId) { - EventManager.Instance.OnFileChanged(new FileChangedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - }); + EventManager.Instance.OnFileChanged(new FileChangedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + }); } private Stream GetVersionContent(FolderProvider provider, IFolderInfo folder, IFileInfo file, int version) @@ -283,22 +300,5 @@ private void RemoveOldestsVersions(IFileInfo file) } } } - - internal static string GetVersionedFilename(IFileInfo file, int version) - { - return string.Format("{0}_{1}.v.resources", file.FileId, version); - } - - private static void RenameFile(IFileInfo file, string newFileName) - { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping != null) - { - var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); - folderProvider.RenameFile(file, newFileName); - } - - DataCache.RemoveCache("GetFileById" + file.FileId); - } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs index 6affc299e60..ebc5e85ef51 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs @@ -32,6 +32,28 @@ public FolderInfo() : this(false) { } + + [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] + public FolderInfo(int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) + : this(Guid.NewGuid(), portalId, folderpath, storageLocation, isProtected, isCached, lastUpdated) + { + } + + [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] + public FolderInfo(Guid uniqueId, int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) + { + this.FolderID = Null.NullInteger; + this.UniqueId = uniqueId; + this.VersionGuid = Guid.NewGuid(); + this.WorkflowID = Null.NullInteger; + + this.PortalID = portalId; + this.FolderPath = folderpath; + this.StorageLocation = storageLocation; + this.IsProtected = isProtected; + this.IsCached = isCached; + this.LastUpdated = lastUpdated; + } internal FolderInfo(bool initialiseEmptyPermissions) { @@ -245,6 +267,26 @@ public bool IsStorageSecure return FolderProvider.Instance(folderMapping.FolderProviderType).IsStorageSecure; } } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + [XmlIgnore] + public int KeyID + { + get + { + return this.FolderID; + } + + set + { + this.FolderID = value; + } + } /// ----------------------------------------------------------------------------- /// @@ -270,47 +312,5 @@ public void Fill(IDataReader dr) this.ParentID = Null.SetNullInteger(dr["ParentID"]); this.FillBaseProperties(dr); } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Key ID. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - [XmlIgnore] - public int KeyID - { - get - { - return this.FolderID; - } - - set - { - this.FolderID = value; - } - } - - [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] - public FolderInfo(int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) - : this(Guid.NewGuid(), portalId, folderpath, storageLocation, isProtected, isCached, lastUpdated) - { - } - - [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] - public FolderInfo(Guid uniqueId, int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) - { - this.FolderID = Null.NullInteger; - this.UniqueId = uniqueId; - this.VersionGuid = Guid.NewGuid(); - this.WorkflowID = Null.NullInteger; - - this.PortalID = portalId; - this.FolderPath = folderpath; - this.StorageLocation = storageLocation; - this.IsProtected = isProtected; - this.IsCached = isCached; - this.LastUpdated = lastUpdated; - } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderManager.cs b/DNN Platform/Library/Services/FileSystem/FolderManager.cs index e904ed070a1..6153368532d 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderManager.cs @@ -38,10 +38,10 @@ namespace DotNetNuke.Services.FileSystem /// public class FolderManager : ComponentBase, IFolderManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FolderManager)); - private static readonly Dictionary SyncFoldersData = new Dictionary(); private const string DefaultUsersFoldersPath = "Users"; private const string DefaultMappedPathSetting = "DefaultMappedPath"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FolderManager)); + private static readonly Dictionary SyncFoldersData = new Dictionary(); private static readonly object _threadLocker = new object(); public virtual string MyFolderName @@ -52,6 +52,115 @@ public virtual string MyFolderName } } + /// + /// Creates a new folder using the provided folder path. + /// + /// The folder mapping to use. + /// The path of the new folder. + /// Thrown when folderPath or folderMapping are null. + /// Thrown when the underlying system throw an exception. + /// The added folder. + public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath) + { + return this.AddFolder(folderMapping, folderPath, folderPath); + } + + /// + /// Creates a new folder using the provided folder path and mapping. + /// + /// The folder mapping to use. + /// The path of the new folder. + /// The mapped path of the new folder. + /// Thrown when folderPath or folderMapping are null. + /// Thrown when the underlying system throw an exception. + /// The added folder. + public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath, string mappedPath) + { + Requires.PropertyNotNull("folderPath", folderPath); + Requires.NotNull("folderMapping", folderMapping); + + folderPath = folderPath.Trim(); + + if (this.FolderExists(folderMapping.PortalID, folderPath)) + { + throw new FolderAlreadyExistsException(Localization.GetExceptionMessage("AddFolderAlreadyExists", "The provided folder path already exists. The folder has not been added.")); + } + + if (!this.IsValidFolderPath(folderPath)) + { + throw new InvalidFolderPathException(Localization.GetExceptionMessage("AddFolderNotAllowed", "The folder path '{0}' is not allowed. The folder has not been added.", folderPath)); + } + + var parentFolder = this.GetParentFolder(folderMapping.PortalID, folderPath); + if (parentFolder != null) + { + var parentFolderMapping = FolderMappingController.Instance.GetFolderMapping( + parentFolder.PortalID, + parentFolder.FolderMappingID); + if (FolderProvider.Instance(parentFolderMapping.FolderProviderType).SupportsMappedPaths) + { + folderMapping = parentFolderMapping; + mappedPath = string.IsNullOrEmpty(parentFolder.FolderPath) ? PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + folderPath) + : PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + folderPath.Replace(parentFolder.FolderPath, string.Empty)); + } + else if (!FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) + { + mappedPath = folderPath; + } + else + { + // Parent foldermapping DOESN'T support mapped path + // abd current foldermapping YES support mapped path + mappedPath = PathUtils.Instance.FormatFolderPath(this.GetDefaultMappedPath(folderMapping) + mappedPath); + } + } + else if (FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) + { + mappedPath = PathUtils.Instance.FormatFolderPath(this.GetDefaultMappedPath(folderMapping) + mappedPath); + } + + try + { + FolderProvider.Instance(folderMapping.FolderProviderType).AddFolder(folderPath, folderMapping, mappedPath); + } + catch (Exception ex) + { + Logger.Error(ex); + + throw new FolderProviderException(Localization.GetExceptionMessage("AddFolderUnderlyingSystemError", "The underlying system threw an exception. The folder has not been added."), ex); + } + + this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(folderMapping.PortalID, folderPath)); + var folderId = this.CreateFolderInDatabase(folderMapping.PortalID, folderPath, folderMapping.FolderMappingID, mappedPath); + + var folder = this.GetFolder(folderId); + + // Notify add folder event + this.OnFolderAdded(folder, this.GetCurrentUserId()); + + return folder; + } + + private static Regex WildcardToRegex(string pattern) + { + if (!pattern.Contains("*") && !pattern.Contains("?")) + { + pattern = "^" + pattern + ".*$"; + } + else + { + pattern = "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$"; + } + + return RegexUtils.GetCachedRegex(pattern, RegexOptions.IgnoreCase); + } + + private static bool IsStandardFolderProviderType(FolderMappingInfo folderMappingInfo) + { + var compatibleTypes = new[] { "StandardFolderProvider", "SecureFolderProvider", "DatabaseFolderProvider" }; + return compatibleTypes.Contains(folderMappingInfo.FolderProviderType); + } + private int AddFolderInternal(IFolderInfo folder) { // Check this is not a duplicate @@ -244,26 +353,6 @@ private IFolderInfo UpdateFolderInternal(IFolderInfo folder, bool clearCache) return folder; } - private static Regex WildcardToRegex(string pattern) - { - if (!pattern.Contains("*") && !pattern.Contains("?")) - { - pattern = "^" + pattern + ".*$"; - } - else - { - pattern = "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$"; - } - - return RegexUtils.GetCachedRegex(pattern, RegexOptions.IgnoreCase); - } - - private static bool IsStandardFolderProviderType(FolderMappingInfo folderMappingInfo) - { - var compatibleTypes = new[] { "StandardFolderProvider", "SecureFolderProvider", "DatabaseFolderProvider" }; - return compatibleTypes.Contains(folderMappingInfo.FolderProviderType); - } - private int FindFolderMappingId(MergedTreeItem item, int portalId) { if (item.ExistsInFolderMapping) @@ -369,147 +458,52 @@ private IEnumerable GetFolders(IFolderInfo parentFolder, bool allSu private void OnFolderMoved(IFolderInfo folderInfo, int userId, string oldFolderPath) { - EventManager.Instance.OnFolderMoved(new FolderMovedEventArgs - { - FolderInfo = folderInfo, - UserId = userId, - OldFolderPath = oldFolderPath, - }); + EventManager.Instance.OnFolderMoved(new FolderMovedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + OldFolderPath = oldFolderPath, + }); } private void OnFolderRenamed(IFolderInfo folderInfo, int userId, string oldFolderName) { - EventManager.Instance.OnFolderRenamed(new FolderRenamedEventArgs - { - FolderInfo = folderInfo, - UserId = userId, - OldFolderName = oldFolderName, - }); + EventManager.Instance.OnFolderRenamed(new FolderRenamedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + OldFolderName = oldFolderName, + }); } private void OnFolderDeleted(IFolderInfo folderInfo, int userId, bool isCascadeDeleting) { - EventManager.Instance.OnFolderDeleted(new FolderDeletedEventArgs - { - FolderInfo = folderInfo, - UserId = userId, - IsCascadeDeletng = isCascadeDeleting, - }); + EventManager.Instance.OnFolderDeleted(new FolderDeletedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + IsCascadeDeletng = isCascadeDeleting, + }); } private void OnFolderAdded(IFolderInfo folderInfo, int userId) { - EventManager.Instance.OnFolderAdded(new FolderChangedEventArgs - { - FolderInfo = folderInfo, - UserId = userId, - }); + EventManager.Instance.OnFolderAdded(new FolderChangedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + }); } private void OnFileDeleted(IFileInfo fileInfo, int userId, bool isCascadeDeleting) { - EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - IsCascadeDeleting = isCascadeDeleting, - }); + EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + IsCascadeDeleting = isCascadeDeleting, + }); } - - /// - /// Creates a new folder using the provided folder path. - /// - /// The folder mapping to use. - /// The path of the new folder. - /// Thrown when folderPath or folderMapping are null. - /// Thrown when the underlying system throw an exception. - /// The added folder. - public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath) - { - return this.AddFolder(folderMapping, folderPath, folderPath); - } - - /// - /// Creates a new folder using the provided folder path and mapping. - /// - /// The folder mapping to use. - /// The path of the new folder. - /// The mapped path of the new folder. - /// Thrown when folderPath or folderMapping are null. - /// Thrown when the underlying system throw an exception. - /// The added folder. - public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath, string mappedPath) - { - Requires.PropertyNotNull("folderPath", folderPath); - Requires.NotNull("folderMapping", folderMapping); - - folderPath = folderPath.Trim(); - - if (this.FolderExists(folderMapping.PortalID, folderPath)) - { - throw new FolderAlreadyExistsException(Localization.GetExceptionMessage("AddFolderAlreadyExists", "The provided folder path already exists. The folder has not been added.")); - } - - if (!this.IsValidFolderPath(folderPath)) - { - throw new InvalidFolderPathException(Localization.GetExceptionMessage("AddFolderNotAllowed", "The folder path '{0}' is not allowed. The folder has not been added.", folderPath)); - } - - var parentFolder = this.GetParentFolder(folderMapping.PortalID, folderPath); - if (parentFolder != null) - { - var parentFolderMapping = FolderMappingController.Instance.GetFolderMapping( - parentFolder.PortalID, - parentFolder.FolderMappingID); - if (FolderProvider.Instance(parentFolderMapping.FolderProviderType).SupportsMappedPaths) - { - folderMapping = parentFolderMapping; - mappedPath = string.IsNullOrEmpty(parentFolder.FolderPath) ? PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + folderPath) - : PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + folderPath.Replace(parentFolder.FolderPath, string.Empty)); - } - else if (!FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) - { - mappedPath = folderPath; - } - else - { - // Parent foldermapping DOESN'T support mapped path - // abd current foldermapping YES support mapped path - mappedPath = PathUtils.Instance.FormatFolderPath(this.GetDefaultMappedPath(folderMapping) + mappedPath); - } - } - else if (FolderProvider.Instance(folderMapping.FolderProviderType).SupportsMappedPaths) - { - mappedPath = PathUtils.Instance.FormatFolderPath(this.GetDefaultMappedPath(folderMapping) + mappedPath); - } - - try - { - FolderProvider.Instance(folderMapping.FolderProviderType).AddFolder(folderPath, folderMapping, mappedPath); - } - catch (Exception ex) - { - Logger.Error(ex); - - throw new FolderProviderException(Localization.GetExceptionMessage("AddFolderUnderlyingSystemError", "The underlying system threw an exception. The folder has not been added."), ex); - } - - this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(folderMapping.PortalID, folderPath)); - var folderId = this.CreateFolderInDatabase(folderMapping.PortalID, folderPath, folderMapping.FolderMappingID, mappedPath); - - var folder = this.GetFolder(folderId); - - // Notify add folder event - this.OnFolderAdded(folder, this.GetCurrentUserId()); - - return folder; - } - - internal virtual bool IsValidFolderPath(string folderPath) - { - var illegalInFolderPath = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars()))), RegexOptions.Compiled); - return !illegalInFolderPath.IsMatch(folderPath) && !folderPath.TrimEnd('/', '\\').EndsWith("."); - } /// /// Creates a new folder in the given portal using the provided folder path. @@ -544,6 +538,12 @@ public virtual void DeleteFolder(IFolderInfo folder) this.DeleteFolderInternal(folder, false); } + internal virtual bool IsValidFolderPath(string folderPath) + { + var illegalInFolderPath = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars()))), RegexOptions.Compiled); + return !illegalInFolderPath.IsMatch(folderPath) && !folderPath.TrimEnd('/', '\\').EndsWith("."); + } + public virtual void UnlinkFolder(IFolderInfo folder) { this.DeleteFolderRecursive(folder, new Collection(), true, true); @@ -568,9 +568,9 @@ public virtual void DeleteFolder(int folderId) public void DeleteFolder(IFolderInfo folder, ICollection notDeletedSubfolders) { this.DeleteFolderRecursive(folder, notDeletedSubfolders, true, this.GetOnlyUnmap(folder)); - } - - /// + } + + /// /// Checks the existence of the specified folder in the specified portal. /// /// The portal where to check the existence of the folder. @@ -1121,28 +1121,6 @@ public virtual void CopyParentFolderPermissions(IFolderInfo folder) FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); } - private FolderPermissionCollection GetFolderPermissionsFromSyncData(int portalId, string relativePath) - { - var threadId = Thread.CurrentThread.ManagedThreadId; - FolderPermissionCollection permissions = null; - if (SyncFoldersData.ContainsKey(threadId)) - { - if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) - { - return SyncFoldersData[threadId].Permissions; - } - - permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); - SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; - return permissions; - } - - permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); - SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); - - return permissions; - } - /// /// Sets specific folder permissions for the given role to the given folder. /// @@ -1182,6 +1160,28 @@ public virtual void SetFolderPermission(IFolderInfo folder, int permissionId, in FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); } + private FolderPermissionCollection GetFolderPermissionsFromSyncData(int portalId, string relativePath) + { + var threadId = Thread.CurrentThread.ManagedThreadId; + FolderPermissionCollection permissions = null; + if (SyncFoldersData.ContainsKey(threadId)) + { + if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) + { + return SyncFoldersData[threadId].Permissions; + } + + permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; + return permissions; + } + + permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); + + return permissions; + } + /// /// Sets folder permissions for administrator role to the given folder. /// @@ -1205,6 +1205,31 @@ public virtual void SetFolderPermissions(IFolderInfo folder, int administratorRo FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); } + /// + /// Moves the specified folder and its contents to a new location. + /// + /// The folder to move. + /// The new folder path. + /// The moved folder. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in DNN 7.1. It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder) . Scheduled removal in v10.0.0.")] + public virtual IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath) + { + Requires.NotNull("folder", folder); + Requires.NotNullOrEmpty("newFolderPath", newFolderPath); + + var nameCharIndex = newFolderPath.Substring(0, newFolderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1; + var parentFolder = this.GetFolder(folder.PortalID, newFolderPath.Substring(0, nameCharIndex)); + if (parentFolder.FolderID == folder.ParentID) + { + var newFolderName = newFolderPath.Substring(nameCharIndex, newFolderPath.Length - nameCharIndex - 1); + this.RenameFolder(folder, newFolderName); + return folder; + } + + return this.MoveFolder(folder, parentFolder); + } + internal virtual void AddLogEntry(IFolderInfo folder, EventLogController.EventLogType eventLogType) { EventLogController.Instance.AddLog(folder, PortalController.Instance.GetCurrentPortalSettings(), this.GetCurrentUserId(), string.Empty, eventLogType); @@ -1227,10 +1252,10 @@ internal void DeleteFilesFromCache(int portalId, string newFolderPath) DataCache.RemoveCache("GetFileById" + fileId); } } - } + } /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual IFolderInfo AddUserFolder(UserInfo user) { // user _default portal for all super users @@ -1296,10 +1321,10 @@ internal virtual IFolderInfo AddUserFolder(UserInfo user) } return this.GetFolder(portalId, folderPath); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool AreThereFolderMappingsRequiringNetworkConnectivity(int portalId, string relativePath, bool isRecursive) { var folder = this.GetFolder(portalId, relativePath); @@ -1357,10 +1382,10 @@ internal virtual void ClearFolderCache(int portalId) internal virtual int CreateFolderInDatabase(int portalId, string folderPath, int folderMappingId) { return this.CreateFolderInDatabase(portalId, folderPath, folderMappingId, folderPath); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual int CreateFolderInDatabase(int portalId, string folderPath, int folderMappingId, string mappedPath) { var isProtected = PathUtils.Instance.IsDefaultProtectedPath(folderPath); @@ -1382,17 +1407,17 @@ internal virtual int CreateFolderInDatabase(int portalId, string folderPath, int } } - var folder = new FolderInfo(true) - { - PortalID = portalId, - FolderPath = folderPath, - MappedPath = mappedPath, - StorageLocation = storageLocation, - IsProtected = isProtected, - IsCached = false, - FolderMappingID = folderMappingId, - LastUpdated = Null.NullDate, - }; + var folder = new FolderInfo(true) + { + PortalID = portalId, + FolderPath = folderPath, + MappedPath = mappedPath, + StorageLocation = storageLocation, + IsProtected = isProtected, + IsCached = false, + FolderMappingID = folderMappingId, + LastUpdated = Null.NullDate, + }; folder.FolderID = this.AddFolderInternal(folder); @@ -1449,24 +1474,24 @@ internal virtual void DeleteFoldersFromExternalStorageLocations(DictionaryThis member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual int GetCurrentScriptTimeout() { return HttpContext.Current.Server.ScriptTimeout; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual int GetCurrentUserId() { return UserController.Instance.GetCurrentUserInfo().UserID; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual SortedList GetDatabaseFolders(int portalId, string relativePath, bool isRecursive) { var databaseFolders = new SortedList(new IgnoreCaseStringComparer()); @@ -1495,10 +1520,10 @@ internal virtual SortedList GetDatabaseFolders(int porta } return databaseFolders; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual SortedList GetDatabaseFoldersRecursive(IFolderInfo folder) { var result = new SortedList(new IgnoreCaseStringComparer()); @@ -1510,14 +1535,14 @@ internal virtual SortedList GetDatabaseFoldersRecursive( { var folderInfo = stack.Pop(); - var item = new MergedTreeItem - { - FolderID = folderInfo.FolderID, - FolderMappingID = folderInfo.FolderMappingID, - FolderPath = folderInfo.FolderPath, - ExistsInDatabase = true, - MappedPath = folderInfo.MappedPath, - }; + var item = new MergedTreeItem + { + FolderID = folderInfo.FolderID, + FolderMappingID = folderInfo.FolderMappingID, + FolderPath = folderInfo.FolderPath, + ExistsInDatabase = true, + MappedPath = folderInfo.MappedPath, + }; if (!result.ContainsKey(item.FolderPath)) { @@ -1531,10 +1556,10 @@ internal virtual SortedList GetDatabaseFoldersRecursive( } return result; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual SortedList GetFileSystemFolders(int portalId, string relativePath, bool isRecursive) { var fileSystemFolders = new SortedList(new IgnoreCaseStringComparer()); @@ -1569,10 +1594,10 @@ internal virtual SortedList GetFileSystemFolders(int por } return fileSystemFolders; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual SortedList GetFileSystemFoldersRecursive(int portalId, string physicalPath) { var result = new SortedList(new IgnoreCaseStringComparer()); @@ -1616,10 +1641,10 @@ internal virtual SortedList GetFileSystemFoldersRecursiv } return result; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual FolderMappingInfo GetFolderMapping(Dictionary folderMappings, int folderMappingId) { if (!folderMappings.ContainsKey(folderMappingId)) @@ -1628,10 +1653,10 @@ internal virtual FolderMappingInfo GetFolderMapping(DictionaryThis member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual SortedList GetFolderMappingFoldersRecursive(FolderMappingInfo folderMapping, IFolderInfo folder) { var result = new SortedList(new IgnoreCaseStringComparer()); @@ -1681,28 +1706,28 @@ internal virtual SortedList GetFolderMappingFoldersRecur } return result; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual object GetFoldersByPermissionSortedCallBack(CacheItemArgs cacheItemArgs) { var portalId = (int)cacheItemArgs.ParamList[0]; var permissions = (string)cacheItemArgs.ParamList[1]; var userId = (int)cacheItemArgs.ParamList[2]; return CBO.Instance.FillCollection(DataProvider.Instance().GetFoldersByPortalAndPermissions(portalId, permissions, userId)); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual object GetFoldersSortedCallBack(CacheItemArgs cacheItemArgs) { var portalId = (int)cacheItemArgs.ParamList[0]; return CBO.Instance.FillCollection(DataProvider.Instance().GetFoldersByPortal(portalId)); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual SortedList GetMergedTree(int portalId, string relativePath, bool isRecursive) { var fileSystemFolders = this.GetFileSystemFolders(portalId, relativePath, isRecursive); @@ -1753,17 +1778,17 @@ internal virtual SortedList GetMergedTree(int portalId, } return mergedTree; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool IsFolderMappingEditable(FolderMappingInfo folderMapping) { return folderMapping.IsEditable; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, IFolderInfo destinationFolder, string newFolderPath) { // FolderMapping cases @@ -1784,10 +1809,10 @@ internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, IFolderInfo } return this.IsMoveOperationValid(folderToMove, newFolderPath); - } + } /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, string newFolderPath) { // Root folder cannot be moved @@ -1803,17 +1828,17 @@ internal virtual bool IsMoveOperationValid(IFolderInfo folderToMove, string newF } return true; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool IsNetworkAvailable() { return NetworkInterface.GetIsNetworkAvailable(); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual SortedList MergeFolderLists(SortedList list1, SortedList list2) { foreach (var item in list2.Values) @@ -1972,36 +1997,6 @@ internal virtual void ProcessMergedTreeItemInAddMode(MergedTreeItem item, int po Logger.Error(string.Format("Could not create folder {0}. EXCEPTION: {1}", item.FolderPath, ex.Message), ex); } } - - private void InitialiseSyncFoldersData(int portalId, string relativePath) - { - var threadId = Thread.CurrentThread.ManagedThreadId; - var permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); - if (SyncFoldersData.ContainsKey(threadId)) - { - if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) - { - SyncFoldersData[threadId].Permissions = permissions; - } - else - { - SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; - } - } - else - { - SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); - } - } - - private void RemoveSyncFoldersData(string relativePath) - { - var threadId = Thread.CurrentThread.ManagedThreadId; - if (SyncFoldersData.ContainsKey(threadId)) - { - SyncFoldersData.Remove(threadId); - } - } /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void ProcessMergedTreeItemInDeleteMode(MergedTreeItem item, int portalId) @@ -2063,6 +2058,36 @@ internal virtual void RemoveOrphanedFiles(IFolderInfo folder) } } } + + private void InitialiseSyncFoldersData(int portalId, string relativePath) + { + var threadId = Thread.CurrentThread.ManagedThreadId; + var permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + if (SyncFoldersData.ContainsKey(threadId)) + { + if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) + { + SyncFoldersData[threadId].Permissions = permissions; + } + else + { + SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; + } + } + else + { + SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); + } + } + + private void RemoveSyncFoldersData(string relativePath) + { + var threadId = Thread.CurrentThread.ManagedThreadId; + if (SyncFoldersData.ContainsKey(threadId)) + { + SyncFoldersData.Remove(threadId); + } + } /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void RenameFolderInFileSystem(IFolderInfo folder, string newFolderPath) @@ -2217,10 +2242,10 @@ internal virtual void UpdateChildFolders(IFolderInfo folder, string newFolderPat } this.ClearFolderCache(folder.PortalID); - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. -/// + /// internal virtual bool CanMoveBetweenFolderMappings(FolderMappingInfo sourceFolderMapping, FolderMappingInfo destinationFolderMapping) { // If Folder Mappings are exactly the same @@ -2268,40 +2293,15 @@ public int Compare(string x, string y) /// internal class MoveFoldersInfo { - public string Source { get; private set; } - - public string Target { get; private set; } - public MoveFoldersInfo(string source, string target) { this.Source = source; this.Target = target; } - } - /// - /// Moves the specified folder and its contents to a new location. - /// - /// The folder to move. - /// The new folder path. - /// The moved folder. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.1. It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder) . Scheduled removal in v10.0.0.")] - public virtual IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath) - { - Requires.NotNull("folder", folder); - Requires.NotNullOrEmpty("newFolderPath", newFolderPath); - - var nameCharIndex = newFolderPath.Substring(0, newFolderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1; - var parentFolder = this.GetFolder(folder.PortalID, newFolderPath.Substring(0, nameCharIndex)); - if (parentFolder.FolderID == folder.ParentID) - { - var newFolderName = newFolderPath.Substring(nameCharIndex, newFolderPath.Length - nameCharIndex - 1); - this.RenameFolder(folder, newFolderName); - return folder; - } - - return this.MoveFolder(folder, parentFolder); + public string Source { get; private set; } + + public string Target { get; private set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs index eca30ee9401..64df51a8011 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs @@ -19,13 +19,13 @@ namespace DotNetNuke.Services.FileSystem public class FolderMappingController : ComponentBase, IFolderMappingController { + private const string CacheKeyPrefix = "GetFolderMappingSettings"; + private static readonly DataProvider dataProvider = DataProvider.Instance(); + internal FolderMappingController() { } - private static readonly DataProvider dataProvider = DataProvider.Instance(); - private const string CacheKeyPrefix = "GetFolderMappingSettings"; - public FolderMappingInfo GetDefaultFolderMapping(int portalId) { var defaultFolderMapping = Config.GetSection("dotnetnuke/folder") != null ? diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs index ce8a4c1e9b4..9e7f1bd6338 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs @@ -19,6 +19,22 @@ namespace DotNetNuke.Services.FileSystem public class FolderMappingInfo : IHydratable { private Hashtable _folderMappingSettings; + + private string _imageUrl; + + public FolderMappingInfo() + { + this.FolderMappingID = Null.NullInteger; + this.PortalID = Null.NullInteger; + } + + public FolderMappingInfo(int portalID, string mappingName, string folderProviderType) + { + this.FolderMappingID = Null.NullInteger; + this.PortalID = portalID; + this.MappingName = mappingName; + this.FolderProviderType = folderProviderType; + } public int FolderMappingID { get; set; } @@ -49,8 +65,6 @@ public Hashtable FolderMappingSettings return this._folderMappingSettings; } } - - private string _imageUrl; public string ImageUrl { @@ -90,33 +104,6 @@ public bool SyncAllSubFolders this.FolderMappingSettings["SyncAllSubFolders"] = value; } } - - public FolderMappingInfo() - { - this.FolderMappingID = Null.NullInteger; - this.PortalID = Null.NullInteger; - } - - public FolderMappingInfo(int portalID, string mappingName, string folderProviderType) - { - this.FolderMappingID = Null.NullInteger; - this.PortalID = portalID; - this.MappingName = mappingName; - this.FolderProviderType = folderProviderType; - } - - /// - /// Fills a FolderInfo from a Data Reader. - /// - /// The Data Reader to use. - public void Fill(IDataReader dr) - { - this.FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); - this.PortalID = Null.SetNullInteger(dr["PortalID"]); - this.MappingName = Null.SetNullString(dr["MappingName"]); - this.FolderProviderType = Null.SetNullString(dr["FolderProviderType"]); - this.Priority = Null.SetNullInteger(dr["Priority"]); - } /// /// Gets or sets and sets the Key ID. @@ -133,5 +120,18 @@ public int KeyID this.FolderMappingID = value; } } + + /// + /// Fills a FolderInfo from a Data Reader. + /// + /// The Data Reader to use. + public void Fill(IDataReader dr) + { + this.FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.MappingName = Null.SetNullString(dr["MappingName"]); + this.FolderProviderType = Null.SetNullString(dr["FolderProviderType"]); + this.Priority = Null.SetNullInteger(dr["Priority"]); + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs index 00c4aa08250..6ed64485396 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs @@ -16,6 +16,8 @@ namespace DotNetNuke.Services.FileSystem public class FolderMappingsConfigController : ServiceLocator, IFolderMappingsConfigController { + private const string configNode = "folderMappingsSettings"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FolderMappingsConfigController)); private static readonly string defaultConfigFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); @@ -26,7 +28,32 @@ public FolderMappingsConfigController() this.LoadConfig(); } + public IList FolderTypes { get; internal set; } + + public string ConfigNode + { + get { return configNode; } + } + private IDictionary FolderMappings { get; set; } + + public void LoadConfig() + { + try + { + if (File.Exists(defaultConfigFilePath)) + { + var configDocument = new XmlDocument { XmlResolver = null }; + configDocument.Load(defaultConfigFilePath); + this.FillFolderMappings(configDocument); + this.FillFolderTypes(configDocument); + } + } + catch (Exception ex) + { + Logger.Error(ex); + } + } private void FillFolderMappings(XmlDocument configDocument) { @@ -86,33 +113,6 @@ private FolderTypeConfig GetFolderMappingFromConfigNode(XmlNode node) return folderType; } - - public IList FolderTypes { get; internal set; } - - private const string configNode = "folderMappingsSettings"; - - public string ConfigNode - { - get { return configNode; } - } - - public void LoadConfig() - { - try - { - if (File.Exists(defaultConfigFilePath)) - { - var configDocument = new XmlDocument { XmlResolver = null }; - configDocument.Load(defaultConfigFilePath); - this.FillFolderMappings(configDocument); - this.FillFolderTypes(configDocument); - } - } - catch (Exception ex) - { - Logger.Error(ex); - } - } public void SaveConfig(string folderMappinsSettings) { diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs index 1f2e8cb47c1..3f18891e9b4 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs @@ -12,15 +12,15 @@ namespace DotNetNuke.Services.FileSystem /// ----------------------------------------------------------------------------- public class FolderTypeConfig { + public FolderTypeConfig() + { + this.Settings = new List(); + } + public string Name { get; set; } public string Provider { get; set; } public IList Settings { get; set; } - - public FolderTypeConfig() - { - this.Settings = new List(); - } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderProvider.cs b/DNN Platform/Library/Services/FileSystem/FolderProvider.cs index 2cfc7f07ba5..b9476747ea1 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderProvider.cs @@ -26,35 +26,6 @@ public abstract class FolderProvider private const string SettingsControlId = "Settings.ascx"; private string _providerName; - /// - /// Get the list of all the folder providers. - /// - /// - public static Dictionary GetProviderList() - { - var providerList = ComponentFactory.GetComponents(); - - foreach (var key in providerList.Keys) - { - providerList[key]._providerName = key; - } - - return providerList; - } - - /// - /// Gets an instance of a specific FolderProvider of a given name. - /// - /// - public static FolderProvider Instance(string friendlyName) - { - var provider = ComponentFactory.GetComponent(friendlyName); - - provider._providerName = friendlyName; - - return provider; - } - /// /// Gets a value indicating whether gets a value indicating if the provider ensures the files/folders it manages are secure from outside access. /// @@ -94,6 +65,35 @@ public virtual bool SupportsMappedPaths return false; } } + + /// + /// Get the list of all the folder providers. + /// + /// + public static Dictionary GetProviderList() + { + var providerList = ComponentFactory.GetComponents(); + + foreach (var key in providerList.Keys) + { + providerList[key]._providerName = key; + } + + return providerList; + } + + /// + /// Gets an instance of a specific FolderProvider of a given name. + /// + /// + public static FolderProvider Instance(string friendlyName) + { + var provider = ComponentFactory.GetComponent(friendlyName); + + provider._providerName = friendlyName; + + return provider; + } /// /// Gets a value indicating whether the provider supports the MoveFile method. If a provider supports the MoveFile method, the @@ -113,47 +113,6 @@ public virtual bool SupportsMoveFolder get { return false; } } - private static void AddFolderAndMoveFiles(string folderPath, string newFolderPath, FolderMappingInfo folderMapping) - { - var folderProvider = Instance(folderMapping.FolderProviderType); - - if (!folderProvider.FolderExists(newFolderPath, folderMapping)) - { - folderProvider.AddFolder(newFolderPath, folderMapping); - } - - var folder = new FolderInfo { FolderPath = folderPath, FolderMappingID = folderMapping.FolderMappingID, PortalID = folderMapping.PortalID }; - var newFolder = new FolderInfo { FolderPath = newFolderPath, FolderMappingID = folderMapping.FolderMappingID, PortalID = folderMapping.PortalID }; - - MoveFiles(folder, newFolder, folderMapping); - } - - private static void MoveFiles(IFolderInfo folder, IFolderInfo newFolder, FolderMappingInfo folderMapping) - { - var folderProvider = Instance(folderMapping.FolderProviderType); - var files = folderProvider.GetFiles(folder); - - foreach (var file in files) - { - using (var fileContent = folderProvider.GetFileStream(folder, file)) - { - if (!fileContent.CanSeek) - { - using (var seekableStream = FileManager.Instance.GetSeekableStream(fileContent)) - { - folderProvider.AddFile(newFolder, file, seekableStream); - } - } - else - { - folderProvider.AddFile(newFolder, file, fileContent); - } - } - - folderProvider.DeleteFile(new FileInfo { FileName = file, Folder = folder.FolderPath, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID }); - } - } - public virtual void AddFolder(string folderPath, FolderMappingInfo folderMapping, string mappedPath) { this.AddFolder(folderPath, folderMapping); @@ -195,6 +154,47 @@ public virtual void CopyFile(string folderPath, string fileName, string newFolde } } } + + private static void AddFolderAndMoveFiles(string folderPath, string newFolderPath, FolderMappingInfo folderMapping) + { + var folderProvider = Instance(folderMapping.FolderProviderType); + + if (!folderProvider.FolderExists(newFolderPath, folderMapping)) + { + folderProvider.AddFolder(newFolderPath, folderMapping); + } + + var folder = new FolderInfo { FolderPath = folderPath, FolderMappingID = folderMapping.FolderMappingID, PortalID = folderMapping.PortalID }; + var newFolder = new FolderInfo { FolderPath = newFolderPath, FolderMappingID = folderMapping.FolderMappingID, PortalID = folderMapping.PortalID }; + + MoveFiles(folder, newFolder, folderMapping); + } + + private static void MoveFiles(IFolderInfo folder, IFolderInfo newFolder, FolderMappingInfo folderMapping) + { + var folderProvider = Instance(folderMapping.FolderProviderType); + var files = folderProvider.GetFiles(folder); + + foreach (var file in files) + { + using (var fileContent = folderProvider.GetFileStream(folder, file)) + { + if (!fileContent.CanSeek) + { + using (var seekableStream = FileManager.Instance.GetSeekableStream(fileContent)) + { + folderProvider.AddFile(newFolder, file, seekableStream); + } + } + else + { + folderProvider.AddFile(newFolder, file, fileContent); + } + } + + folderProvider.DeleteFile(new FileInfo { FileName = file, Folder = folder.FolderPath, FolderMappingID = folderMapping.FolderMappingID, PortalId = folderMapping.PortalID }); + } + } /// /// Gets a file Stream of the specified file. diff --git a/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs b/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs index ed21a9eb30d..9b3d33e87ba 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs @@ -11,16 +11,16 @@ namespace DotNetNuke.Services.FileSystem public interface IFileContentTypeManager { + /// + /// Gets get all content types dictionary. + /// + IDictionary ContentTypes { get; } + /// /// Gets the Content Type for the specified file extension. /// /// The file extension. /// The Content Type for the specified extension. string GetContentType(string extension); - - /// - /// Gets get all content types dictionary. - /// - IDictionary ContentTypes { get; } } } diff --git a/DNN Platform/Library/Services/FileSystem/IFileManager.cs b/DNN Platform/Library/Services/FileSystem/IFileManager.cs index e9fb97b68f5..bfb39dd8dea 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileManager.cs @@ -14,6 +14,12 @@ namespace DotNetNuke.Services.FileSystem /// public interface IFileManager { + /// + /// Gets the system defined content types. + /// + [Obsolete("Deprecated in DNN 7.4.2. It has been replaced by FileContentTypeManager.Instance.ContentTypes. Scheduled removal in v10.0.0.")] + IDictionary ContentTypes { get; } + /// /// Adds a file to the specified folder. /// @@ -80,12 +86,6 @@ public interface IFileManager /// A IFileInfo with the information of the copied file. IFileInfo CopyFile(IFileInfo file, IFolderInfo destinationFolder); - /// - /// Gets the system defined content types. - /// - [Obsolete("Deprecated in DNN 7.4.2. It has been replaced by FileContentTypeManager.Instance.ContentTypes. Scheduled removal in v10.0.0.")] - IDictionary ContentTypes { get; } - /// /// Deletes the specified file. /// diff --git a/DNN Platform/Library/Services/FileSystem/IFolderManager.cs b/DNN Platform/Library/Services/FileSystem/IFolderManager.cs index 7131b1706d8..008b1ce6ed9 100644 --- a/DNN Platform/Library/Services/FileSystem/IFolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFolderManager.cs @@ -17,6 +17,11 @@ namespace DotNetNuke.Services.FileSystem /// public interface IFolderManager { + /// + /// Gets the alias name of the personal User Folder. + /// + string MyFolderName { get; } + /// /// Adds read permissions for all users to the specified folder. /// @@ -206,11 +211,6 @@ public interface IFolderManager /// The list of folders the specified user has the provided permissions. IEnumerable GetFolders(UserInfo user, string permissions); - /// - /// Gets the alias name of the personal User Folder. - /// - string MyFolderName { get; } - /// /// Moves the specified folder and its contents to a new location. /// diff --git a/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs b/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs index e5bc25a2404..e5e8a3fc595 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs @@ -62,6 +62,11 @@ public void DeleteFileData(IFileInfo file) this.DeleteContentItem(file.ContentItemID); } + protected override Func GetFactory() + { + return () => new FileDeletionController(); + } + private void DeleteContentItem(int contentItemId) { if (contentItemId == Null.NullInteger) @@ -71,10 +76,5 @@ private void DeleteContentItem(int contentItemId) Util.GetContentController().DeleteContentItem(contentItemId); } - - protected override Func GetFactory() - { - return () => new FileDeletionController(); - } } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/FileLockingController.cs b/DNN Platform/Library/Services/FileSystem/Internal/FileLockingController.cs index 0f281ba71d8..52f4e32b0ce 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/FileLockingController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/FileLockingController.cs @@ -53,15 +53,15 @@ public bool IsFileOutOfPublishPeriod(IFileInfo file, int portalId, int userId) return this.IsFileOutOfPublishPeriod(file); } - private bool IsFileOutOfPublishPeriod(IFileInfo file) + protected override Func GetFactory() { - // Publish Period locks - return file.EnablePublishPeriod && (file.StartDate > DateTime.Today || (file.EndDate < DateTime.Today && file.EndDate != Null.NullDate)); + return () => new FileLockingController(); } - protected override Func GetFactory() + private bool IsFileOutOfPublishPeriod(IFileInfo file) { - return () => new FileLockingController(); + // Publish Period locks + return file.EnablePublishPeriod && (file.StartDate > DateTime.Today || (file.EndDate < DateTime.Today && file.EndDate != Null.NullDate)); } } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs b/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs index df2a224a327..928ca3dc2b3 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs @@ -17,14 +17,9 @@ namespace DotNetNuke.Services.FileSystem.Internal /// public class FileSecurityController : ServiceLocator, IFileSecurityController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSecurityController)); - private const int BufferSize = 4096; - - protected override Func GetFactory() - { - return () => new FileSecurityController(); - } + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSecurityController)); public bool Validate(string fileName, Stream fileContent) { @@ -47,6 +42,11 @@ public bool Validate(string fileName, Stream fileContent) } } + protected override Func GetFactory() + { + return () => new FileSecurityController(); + } + private IFileSecurityChecker GetSecurityChecker(string extension) { var listEntry = new ListController().GetListEntryInfo("FileSecurityChecker", extension); diff --git a/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs b/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs index 32a77ee9cb3..c69fb304093 100644 --- a/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs @@ -20,61 +20,47 @@ namespace DotNetNuke.Services.FileSystem public class DatabaseFolderProvider : SecureFolderProvider { - private Stream GetFileStreamInternal(IDataReader dr) + /// + /// Clears the content of the file in the database. + /// + /// The file identifier. + public static void ClearFileContent(int fileId) { - byte[] bytes = null; - try - { - if (dr.Read()) - { - bytes = (byte[])dr["Content"]; - } - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return bytes != null ? new MemoryStream(bytes) : null; + DataProvider.Instance().ClearFileContent(fileId); + DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); } - private void UpdateFileInternal(int fileId, Stream content) + /// + /// Updates the content of the file in the database. + /// + /// The file identifier. + /// The new content. + public static void UpdateFileContent(int fileId, Stream content) { - byte[] fileContent = null; - if (content != null) { - var restorePosition = content.CanSeek; - long originalPosition = Null.NullInteger; - - if (restorePosition) - { - originalPosition = content.Position; - content.Position = 0; - } - + byte[] fileContent; var buffer = new byte[16 * 1024]; - using (var ms = new MemoryStream()) { int read; - while ((read = content.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } - + fileContent = ms.ToArray(); } - if (restorePosition) - { - content.Position = originalPosition; - } + UpdateFileContent(fileId, fileContent); + } + else + { + ClearFileContent(fileId); } - UpdateFileContent(fileId, fileContent); - } + DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); + } public override void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping) { @@ -117,6 +103,62 @@ public override void AddFile(IFolderInfo folder, string fileName, Stream content this.UpdateFile(folder, fileName, content); } + + private Stream GetFileStreamInternal(IDataReader dr) + { + byte[] bytes = null; + try + { + if (dr.Read()) + { + bytes = (byte[])dr["Content"]; + } + } + finally + { + CBO.CloseDataReader(dr, true); + } + + return bytes != null ? new MemoryStream(bytes) : null; + } + + private void UpdateFileInternal(int fileId, Stream content) + { + byte[] fileContent = null; + + if (content != null) + { + var restorePosition = content.CanSeek; + long originalPosition = Null.NullInteger; + + if (restorePosition) + { + originalPosition = content.Position; + content.Position = 0; + } + + var buffer = new byte[16 * 1024]; + + using (var ms = new MemoryStream()) + { + int read; + + while ((read = content.Read(buffer, 0, buffer.Length)) > 0) + { + ms.Write(buffer, 0, read); + } + + fileContent = ms.ToArray(); + } + + if (restorePosition) + { + content.Position = originalPosition; + } + } + + UpdateFileContent(fileId, fileContent); + } public override void DeleteFile(IFileInfo file) { @@ -253,48 +295,6 @@ public override void UpdateFile(IFolderInfo folder, string fileName, Stream cont this.UpdateFileInternal(file.FileId, content); } - - /// - /// Clears the content of the file in the database. - /// - /// The file identifier. - public static void ClearFileContent(int fileId) - { - DataProvider.Instance().ClearFileContent(fileId); - DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); - } - - /// - /// Updates the content of the file in the database. - /// - /// The file identifier. - /// The new content. - public static void UpdateFileContent(int fileId, Stream content) - { - if (content != null) - { - byte[] fileContent; - var buffer = new byte[16 * 1024]; - using (var ms = new MemoryStream()) - { - int read; - while ((read = content.Read(buffer, 0, buffer.Length)) > 0) - { - ms.Write(buffer, 0, read); - } - - fileContent = ms.ToArray(); - } - - UpdateFileContent(fileId, fileContent); - } - else - { - ClearFileContent(fileId); - } - - DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); - } /// /// Updates the content of the file in the database. diff --git a/DNN Platform/Library/Services/GeneratedImage/DiskImageStore.cs b/DNN Platform/Library/Services/GeneratedImage/DiskImageStore.cs index 79d0069f2aa..6c4c7db48b2 100644 --- a/DNN Platform/Library/Services/GeneratedImage/DiskImageStore.cs +++ b/DNN Platform/Library/Services/GeneratedImage/DiskImageStore.cs @@ -32,15 +32,32 @@ public class DiskImageStore : IImageStore private static DiskImageStore _diskImageStore; private static readonly object InstanceLock = new object(); private static string _cachePath; + private static TimeSpan _purgeInterval; private DateTime _lastPurge; private readonly object _purgeQueuedLock = new object(); private bool _purgeQueued; - private static TimeSpan _purgeInterval; #if INDIVIDUAL_LOCKS private Hashtable _fileLocks = new Hashtable(); #else private readonly object _fileLock = new object(); + static DiskImageStore() + { + EnableAutoPurge = true; + PurgeInterval = new TimeSpan(0, 5, 0); + CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); + } + + internal DiskImageStore() + { + if (CachePath != null && !Directory.Exists(CachePath)) + { + Directory.CreateDirectory(CachePath); + } + + this._lastPurge = DateTime.Now; + } + #endif public static string CachePath @@ -86,41 +103,6 @@ public static TimeSpan PurgeInterval } } - private DateTime LastPurge - { - get - { - if (this._lastPurge < new DateTime(1990, 1, 1)) - { - this._lastPurge = DateTime.Now.Subtract(PurgeInterval); - } - - return this._lastPurge; - } - - set - { - this._lastPurge = value; - } - } - - static DiskImageStore() - { - EnableAutoPurge = true; - PurgeInterval = new TimeSpan(0, 5, 0); - CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); - } - - internal DiskImageStore() - { - if (CachePath != null && !Directory.Exists(CachePath)) - { - Directory.CreateDirectory(CachePath); - } - - this._lastPurge = DateTime.Now; - } - internal static IImageStore Instance { get @@ -140,6 +122,24 @@ internal static IImageStore Instance } } + private DateTime LastPurge + { + get + { + if (this._lastPurge < new DateTime(1990, 1, 1)) + { + this._lastPurge = DateTime.Now.Subtract(PurgeInterval); + } + + return this._lastPurge; + } + + set + { + this._lastPurge = value; + } + } + public void ForcePurgeFromServerCache(string cacheId) { var files = new DirectoryInfo(CachePath).GetFiles(); @@ -153,6 +153,35 @@ public void ForcePurgeFromServerCache(string cacheId) // do nothing at this point. } } + + void IImageStore.Add(string id, byte[] data) + { + this.Add(id, data); + } + + bool IImageStore.TryTransmitIfContains(string id, HttpResponseBase response) + { + return this.TryTransmitIfContains(id, response); + } + +#if INDIVIDUAL_LOCKS + private static string GetEntryId(FileInfo fileinfo) { + string id = fileinfo.Name.Substring(0, fileinfo.Name.Length - s_tempFileExtension.Length); + return id; + } + + private void DiscardFileLockObject(string id) { + // lock on hashtable to prevent other writers + lock (_fileLocks) { + _fileLocks.Remove(id); + } + } +#endif + + private static string BuildFilePath(string id) + { + return CachePath + id + TempFileExtension; + } private void PurgeCallback(object target) { @@ -301,34 +330,5 @@ private object GetFileLockObject(string id) return this._fileLock; #endif } - -#if INDIVIDUAL_LOCKS - private static string GetEntryId(FileInfo fileinfo) { - string id = fileinfo.Name.Substring(0, fileinfo.Name.Length - s_tempFileExtension.Length); - return id; - } - - private void DiscardFileLockObject(string id) { - // lock on hashtable to prevent other writers - lock (_fileLocks) { - _fileLocks.Remove(id); - } - } -#endif - - private static string BuildFilePath(string id) - { - return CachePath + id + TempFileExtension; - } - - void IImageStore.Add(string id, byte[] data) - { - this.Add(id, data); - } - - bool IImageStore.TryTransmitIfContains(string id, HttpResponseBase response) - { - return this.TryTransmitIfContains(id, response); - } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs b/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs index a59ad52ee64..46a417f85f5 100644 --- a/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs @@ -38,32 +38,26 @@ public class DnnImageHandler : ImageHandler Globals.ApplicationPath + "/Portals/", }; - private static bool IsAllowedFilePathImage(string filePath) - { - var normalizeFilePath = NormalizeFilePath(filePath.Trim()); - - // Resources file cannot be served - if (filePath.EndsWith(".resources")) - { - return false; - } - - // File outside the white list cannot be served - return WhiteListFolderPaths.Any(normalizeFilePath.StartsWith); - } + private string _defaultImageFile = string.Empty; - private static string NormalizeFilePath(string filePath) + public DnnImageHandler() { - var normalizeFilePath = filePath.Replace("\\", "/"); - if (!normalizeFilePath.StartsWith("/")) - { - normalizeFilePath = "/" + normalizeFilePath; - } - - return normalizeFilePath; - } + // Set default settings here + this.EnableClientCache = true; + this.EnableServerCache = true; + this.AllowStandalone = true; + this.LogSecurity = false; + this.EnableIPCount = false; + this.ImageCompression = 95; + DiskImageStore.PurgeInterval = new TimeSpan(0, 3, 0); + this.IPCountPurgeInterval = new TimeSpan(0, 5, 0); + this.IPCountMaxCount = 500; + this.ClientCacheExpiration = new TimeSpan(0, 10, 0); + this.AllowedDomains = new[] { string.Empty }; - private string _defaultImageFile = string.Empty; + // read settings from web.config + this.ReadSettings(); + } private Image EmptyImage { @@ -103,25 +97,6 @@ private Image EmptyImage } } - public DnnImageHandler() - { - // Set default settings here - this.EnableClientCache = true; - this.EnableServerCache = true; - this.AllowStandalone = true; - this.LogSecurity = false; - this.EnableIPCount = false; - this.ImageCompression = 95; - DiskImageStore.PurgeInterval = new TimeSpan(0, 3, 0); - this.IPCountPurgeInterval = new TimeSpan(0, 5, 0); - this.IPCountMaxCount = 500; - this.ClientCacheExpiration = new TimeSpan(0, 10, 0); - this.AllowedDomains = new[] { string.Empty }; - - // read settings from web.config - this.ReadSettings(); - } - // Add image generation logic here and return an instance of ImageInfo public override ImageInfo GenerateImage(NameValueCollection parameters) { @@ -475,12 +450,29 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) } } - private ImageInfo GetEmptyImageInfo() + private static bool IsAllowedFilePathImage(string filePath) { - return new ImageInfo(this.EmptyImage) + var normalizeFilePath = NormalizeFilePath(filePath.Trim()); + + // Resources file cannot be served + if (filePath.EndsWith(".resources")) { - IsEmptyImage = true, - }; + return false; + } + + // File outside the white list cannot be served + return WhiteListFolderPaths.Any(normalizeFilePath.StartsWith); + } + + private static string NormalizeFilePath(string filePath) + { + var normalizeFilePath = filePath.Replace("\\", "/"); + if (!normalizeFilePath.StartsWith("/")) + { + normalizeFilePath = "/" + normalizeFilePath; + } + + return normalizeFilePath; } private static bool TryParseDimension(string value, out int dimension) @@ -508,6 +500,49 @@ private static bool TryParseDimension(string value, out int dimension) return true; } + private static ImageFormat GetImageFormat(string extension) + { + switch (extension.ToLowerInvariant()) + { + case "jpg": + case "jpeg": + return ImageFormat.Jpeg; + case "bmp": + return ImageFormat.Bmp; + case "gif": + return ImageFormat.Gif; + case "png": + return ImageFormat.Png; + case "ico": + return ImageFormat.Icon; + default: + return ImageFormat.Png; + } + } + + // checks whether the uri belongs to any of the site-wide aliases + private static bool UriBelongsToSite(Uri uri) + { + IEnumerable hostAliases = + from PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliases().Values + select alias.HTTPAlias.ToLowerInvariant(); + + // if URI, for example, = "http(s)://myDomain:80/DNNDev/myPage?var=name" , then the two strings will be + // uriNoScheme1 = "mydomain/dnndev/mypage" -- lower case + // uriNoScheme2 = "mydomain:80/dnndev/mypage" -- lower case + var uriNoScheme1 = (uri.DnsSafeHost + uri.LocalPath).ToLowerInvariant(); + var uriNoScheme2 = (uri.Authority + uri.LocalPath).ToLowerInvariant(); + return hostAliases.Any(alias => uriNoScheme1.StartsWith(alias) || uriNoScheme2.StartsWith(alias)); + } + + private ImageInfo GetEmptyImageInfo() + { + return new ImageInfo(this.EmptyImage) + { + IsEmptyImage = true, + }; + } + private void ReadSettings() { var settings = ConfigurationManager.AppSettings["DnnImageHandler"]; @@ -574,40 +609,5 @@ private void SetupCulture() TestableLocalization.Instance.SetThreadCultures(pageLocale, settings); } } - - private static ImageFormat GetImageFormat(string extension) - { - switch (extension.ToLowerInvariant()) - { - case "jpg": - case "jpeg": - return ImageFormat.Jpeg; - case "bmp": - return ImageFormat.Bmp; - case "gif": - return ImageFormat.Gif; - case "png": - return ImageFormat.Png; - case "ico": - return ImageFormat.Icon; - default: - return ImageFormat.Png; - } - } - - // checks whether the uri belongs to any of the site-wide aliases - private static bool UriBelongsToSite(Uri uri) - { - IEnumerable hostAliases = - from PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliases().Values - select alias.HTTPAlias.ToLowerInvariant(); - - // if URI, for example, = "http(s)://myDomain:80/DNNDev/myPage?var=name" , then the two strings will be - // uriNoScheme1 = "mydomain/dnndev/mypage" -- lower case - // uriNoScheme2 = "mydomain:80/dnndev/mypage" -- lower case - var uriNoScheme1 = (uri.DnsSafeHost + uri.LocalPath).ToLowerInvariant(); - var uriNoScheme2 = (uri.Authority + uri.LocalPath).ToLowerInvariant(); - return hostAliases.Any(alias => uriNoScheme1.StartsWith(alias) || uriNoScheme2.StartsWith(alias)); - } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs index a13fe4f6cf4..804aac37bfb 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs @@ -12,6 +12,15 @@ namespace DotNetNuke.Services.GeneratedImage.FilterTransform /// public class ImageBrightnessTransform : ImageTransform { + public ImageBrightnessTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.Brightness = 0; + } + /// /// Gets or sets the brightness value. Defaultvalue is 0. Range is -255 .. 255. /// @@ -22,15 +31,6 @@ public class ImageBrightnessTransform : ImageTransform /// public override string UniqueString => base.UniqueString + "-" + this.Brightness; - public ImageBrightnessTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - this.Brightness = 0; - } - /// /// Processes an input image applying a brightness image transformation. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs index d17829e0327..f69e5cc12c1 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs @@ -12,6 +12,15 @@ namespace DotNetNuke.Services.GeneratedImage.FilterTransform /// public class ImageContrastTransform : ImageTransform { + public ImageContrastTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.Contrast = 0; + } + /// /// Gets or sets the contrast value. Defaultvalue is 0. Range is -100 .. 100. /// @@ -22,15 +31,6 @@ public class ImageContrastTransform : ImageTransform /// public override string UniqueString => base.UniqueString + "-" + this.Contrast; - public ImageContrastTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - this.Contrast = 0; - } - /// /// Processes an input image applying a contrast image transformation. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs index bc648370a6a..0078d94d812 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs @@ -13,6 +13,15 @@ namespace DotNetNuke.Services.GeneratedImage.FilterTransform /// public class ImageGammaTransform : ImageTransform { + public ImageGammaTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.Gamma = 1; + } + /// /// Gets or sets the gamma value. Defaultvalue is 0. Range is 0.2 .. 5. /// @@ -23,15 +32,6 @@ public class ImageGammaTransform : ImageTransform /// public override string UniqueString => base.UniqueString + "-" + this.Gamma; - public ImageGammaTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - this.Gamma = 1; - } - /// /// Processes an input image applying a gamma image transformation. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs index 57795819a74..70ee838dc0c 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs @@ -21,6 +21,15 @@ public class ImageResizeTransform : ImageTransform private int _maxWidth; private int _maxHeight; + public ImageResizeTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.Mode = ImageResizeMode.Fit; + } + /// /// Gets or sets the resize mode. The default value is Fit. /// @@ -116,14 +125,11 @@ public int Border /// public Color BackColor { get; set; } = Color.White; - public ImageResizeTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - this.Mode = ImageResizeMode.Fit; - } + /// + /// Gets provides an Unique String for this transformation. + /// + [Browsable(false)] + public override string UniqueString => base.UniqueString + this.Width + this.InterpolationMode + this.Height + this.Mode; /// /// Processes an input image applying a resize image transformation. @@ -173,6 +179,11 @@ public override Image ProcessImage(Image image) return procImage; } + public override string ToString() + { + return "ImageResizeTransform"; + } + private static void CheckValue(int value) { if (value < 0) @@ -299,16 +310,5 @@ private Image FillImage(Image img) graphics.DrawImage(img, (this.Width - resizeWidth) / 2, (this.Height - resizeHeight) / 2, resizeWidth, resizeHeight); return newImage; } - - /// - /// Gets provides an Unique String for this transformation. - /// - [Browsable(false)] - public override string UniqueString => base.UniqueString + this.Width + this.InterpolationMode + this.Height + this.Mode; - - public override string ToString() - { - return "ImageResizeTransform"; - } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs index 5beea86627b..b35f5c7cb05 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs @@ -12,6 +12,15 @@ namespace DotNetNuke.Services.GeneratedImage.FilterTransform /// public class ImageRotateFlipTransform : ImageTransform { + public ImageRotateFlipTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.RotateFlip = RotateFlipType.RotateNoneFlipNone; + } + /// /// Gets or sets the type of rotation / flip . Defaultvalue is RotateNoneFlipNone. /// @@ -22,15 +31,6 @@ public class ImageRotateFlipTransform : ImageTransform /// public override string UniqueString => base.UniqueString + "-" + this.RotateFlip; - public ImageRotateFlipTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - this.RotateFlip = RotateFlipType.RotateNoneFlipNone; - } - /// /// Processes an input image applying a rotation image transformation. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs b/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs index d5bc245c927..c56e9f1ba7d 100644 --- a/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs +++ b/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs @@ -19,6 +19,18 @@ public class GeneratedImage : Image private readonly HttpContextBase _context; private string _imageHandlerUrl; + public GeneratedImage() + { + this.Parameters = new List(); + } + + internal GeneratedImage(HttpContextBase context, Control bindingContainer) + : this() + { + this._context = context; + this._bindingContainer = bindingContainer; + } + public string ImageHandlerUrl { get @@ -51,18 +63,6 @@ public string Timestamp private new Control BindingContainer => this._bindingContainer ?? base.BindingContainer; - public GeneratedImage() - { - this.Parameters = new List(); - } - - internal GeneratedImage(HttpContextBase context, Control bindingContainer) - : this() - { - this._context = context; - this._bindingContainer = bindingContainer; - } - protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); @@ -87,6 +87,14 @@ protected override void OnPreRender(EventArgs e) this.ImageUrl = this.BuildImageUrl(); } + private static void AddQueryStringParameter(StringBuilder stringBuilder, bool paramAlreadyAdded, string name, string value) + { + stringBuilder.Append(paramAlreadyAdded ? '&' : '?'); + stringBuilder.Append(HttpUtility.UrlEncode(name)); + stringBuilder.Append('='); + stringBuilder.Append(HttpUtility.UrlEncode(value)); + } + private string BuildImageUrl() { var stringBuilder = new StringBuilder(); @@ -108,13 +116,5 @@ private string BuildImageUrl() return stringBuilder.ToString(); } - - private static void AddQueryStringParameter(StringBuilder stringBuilder, bool paramAlreadyAdded, string name, string value) - { - stringBuilder.Append(paramAlreadyAdded ? '&' : '?'); - stringBuilder.Append(HttpUtility.UrlEncode(name)); - stringBuilder.Append('='); - stringBuilder.Append(HttpUtility.UrlEncode(value)); - } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs index 0b7c28f45ab..efb376bdef9 100644 --- a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs +++ b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs @@ -25,6 +25,13 @@ public class IPCount private static TimeSpan _purgeInterval; private static readonly object FileLock = new object(); + static IPCount() + { + PurgeInterval = new TimeSpan(0, 10, 0); + MaxCount = 500; + CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); + } + public static string CachePath { get { return _cachePath; } @@ -94,13 +101,6 @@ private static DateTime LastPurge } } - static IPCount() - { - PurgeInterval = new TimeSpan(0, 10, 0); - MaxCount = 500; - CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); - } - public static bool CheckIp(string ipAddress) { var now = DateTime.Now; @@ -173,13 +173,6 @@ public static bool CheckIp(string ipAddress) } } - private static string BuildFilePath(string ipAddress) - { - // it takes only the IP address without PORT for the file name - var fileName = ipAddress.Split(':')[0]; - return CachePath + fileName + TempFileExtension; - } - /// /// method to get Client ip address. /// @@ -189,5 +182,12 @@ public static string GetVisitorIPAddress(HttpContextBase context) { return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(context.Request); } + + private static string BuildFilePath(string ipAddress) + { + // it takes only the IP address without PORT for the file name + var fileName = ipAddress.Split(':')[0]; + return CachePath + fileName + TempFileExtension; + } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs b/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs index 987d6edda6d..cfbebcb8013 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs @@ -16,7 +16,20 @@ namespace DotNetNuke.Services.GeneratedImage /// public abstract class ImageHandler : IHttpHandler { - private ImageHandlerInternal Implementation { get; set; } + internal ImageHandler(IImageStore imageStore, DateTime now) + : this(new ImageHandlerInternal(imageStore, now)) + { + } + + protected ImageHandler() + : this(new ImageHandlerInternal()) + { + } + + private ImageHandler(ImageHandlerInternal implementation) + { + this.Implementation = implementation; + } /// /// Gets or sets a value indicating whether enables server-side caching of the result. @@ -35,6 +48,8 @@ public bool EnableClientCache get { return this.Implementation.EnableClientCache; } set { this.Implementation.EnableClientCache = value; } } + + private ImageHandlerInternal Implementation { get; set; } /// /// Gets or sets the client-side cache expiration time. @@ -112,30 +127,15 @@ public TimeSpan IPCountPurgeInterval set { this.Implementation.IpCountPurgeInterval = value; } } + public virtual bool IsReusable => false; + /// /// Gets a list of image transforms that will be applied successively to the image. /// protected List ImageTransforms => this.Implementation.ImageTransforms; - protected ImageHandler() - : this(new ImageHandlerInternal()) - { - } - - private ImageHandler(ImageHandlerInternal implementation) - { - this.Implementation = implementation; - } - - internal ImageHandler(IImageStore imageStore, DateTime now) - : this(new ImageHandlerInternal(imageStore, now)) - { - } - public abstract ImageInfo GenerateImage(NameValueCollection parameters); - public virtual bool IsReusable => false; - public void ProcessRequest(HttpContext context) { if (context == null) diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs b/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs index ed22bef3ca6..f9193940ef2 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs @@ -32,6 +32,21 @@ internal class ImageHandlerInternal private IImageStore _imageStore; private DateTime? _now; + public ImageHandlerInternal() + { + this.ContentType = ImageFormat.Jpeg; + this.ImageCompression = 95; + this.ImageTransforms = new List(); + this.AllowStandalone = false; + } + + internal ImageHandlerInternal(IImageStore imageStore, DateTime now) + : this() + { + this._imageStore = imageStore; + this._now = now; + } + public TimeSpan ClientCacheExpiration { get @@ -55,6 +70,18 @@ public TimeSpan ClientCacheExpiration public long ImageCompression { get; set; } + public int IPCountMax + { + get { return IPCount.MaxCount; } + set { IPCount.MaxCount = value; } + } + + public TimeSpan IpCountPurgeInterval + { + get { return IPCount.PurgeInterval; } + set { IPCount.PurgeInterval = value; } + } + private DateTime DateTime_Now { get @@ -71,18 +98,6 @@ private IImageStore ImageStore } } - public int IPCountMax - { - get { return IPCount.MaxCount; } - set { IPCount.MaxCount = value; } - } - - public TimeSpan IpCountPurgeInterval - { - get { return IPCount.PurgeInterval; } - set { IPCount.PurgeInterval = value; } - } - public bool EnableClientCache { get; set; } public bool EnableServerCache { get; set; } @@ -101,53 +116,6 @@ public List ImageTransforms private set; } - public ImageHandlerInternal() - { - this.ContentType = ImageFormat.Jpeg; - this.ImageCompression = 95; - this.ImageTransforms = new List(); - this.AllowStandalone = false; - } - - internal ImageHandlerInternal(IImageStore imageStore, DateTime now) - : this() - { - this._imageStore = imageStore; - this._now = now; - } - - internal static string GetImageMimeType(ImageFormat format) - { - string mimeType = "image/x-unknown"; - - if (format.Equals(ImageFormat.Gif)) - { - mimeType = "image/gif"; - } - else if (format.Equals(ImageFormat.Jpeg)) - { - mimeType = "image/jpeg"; - } - else if (format.Equals(ImageFormat.Png)) - { - mimeType = "image/png"; - } - else if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp)) - { - mimeType = "image/bmp"; - } - else if (format.Equals(ImageFormat.Tiff)) - { - mimeType = "image/tiff"; - } - else if (format.Equals(ImageFormat.Icon)) - { - mimeType = "image/x-icon"; - } - - return mimeType; - } - public void HandleImageRequest(HttpContextBase context, Func imageGenCallback, string uniqueIdStringSeed) { context.Response.Clear(); @@ -351,22 +319,36 @@ public void HandleImageRequest(HttpContextBase context, Func k)) + string mimeType = "image/x-unknown"; + + if (format.Equals(ImageFormat.Gif)) { - builder.Append(key); - builder.Append(context.Request.QueryString.Get(key)); + mimeType = "image/gif"; } - - foreach (var tran in this.ImageTransforms) + else if (format.Equals(ImageFormat.Jpeg)) { - builder.Append(tran.UniqueString); + mimeType = "image/jpeg"; + } + else if (format.Equals(ImageFormat.Png)) + { + mimeType = "image/png"; + } + else if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp)) + { + mimeType = "image/bmp"; + } + else if (format.Equals(ImageFormat.Tiff)) + { + mimeType = "image/tiff"; + } + else if (format.Equals(ImageFormat.Icon)) + { + mimeType = "image/x-icon"; } - return GetIDFromBytes(ASCIIEncoding.ASCII.GetBytes(builder.ToString())); + return mimeType; } private static string GetIDFromBytes(byte[] buffer) @@ -384,6 +366,36 @@ private static string GetIDFromBytes(byte[] buffer) } } + /// + /// Returns the encoder for the specified mime type. + /// + /// The mime type of the content. + /// ImageCodecInfo. + private static ImageCodecInfo GetEncoderInfo(string mimeType) + { + var encoders = ImageCodecInfo.GetImageEncoders(); + var e = encoders.FirstOrDefault(x => x.MimeType == mimeType); + return e; + } + + private string GetUniqueIDString(HttpContextBase context, string uniqueIdStringSeed) + { + var builder = new StringBuilder(); + builder.Append(uniqueIdStringSeed); + foreach (var key in context.Request.QueryString.AllKeys.OrderBy(k => k)) + { + builder.Append(key); + builder.Append(context.Request.QueryString.Get(key)); + } + + foreach (var tran in this.ImageTransforms) + { + builder.Append(tran.UniqueString); + } + + return GetIDFromBytes(ASCIIEncoding.ASCII.GetBytes(builder.ToString())); + } + private Image GetImageThroughTransforms(Image image) { try @@ -463,17 +475,5 @@ private void RenderImage(Image image, Stream outStream) image?.Dispose(); } } - - /// - /// Returns the encoder for the specified mime type. - /// - /// The mime type of the content. - /// ImageCodecInfo. - private static ImageCodecInfo GetEncoderInfo(string mimeType) - { - var encoders = ImageCodecInfo.GetImageEncoders(); - var e = encoders.FirstOrDefault(x => x.MimeType == mimeType); - return e; - } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs b/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs index ed706025055..09ff6e9de40 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs @@ -13,23 +13,6 @@ namespace DotNetNuke.Services.GeneratedImage /// public class ImageInfo { - /// - /// Gets image. - /// - public Image Image { get; private set; } - - /// - /// Gets image byte buffer. - /// - public byte[] ImageByteBuffer { get; private set; } - - /// - /// Gets http status code. - /// - public HttpStatusCode? HttpStatusCode { get; private set; } - - public bool IsEmptyImage { get; set; } = false; - public ImageInfo(HttpStatusCode statusCode) { this.HttpStatusCode = statusCode; @@ -54,5 +37,22 @@ public ImageInfo(byte[] imageBuffer) this.ImageByteBuffer = imageBuffer; } + + /// + /// Gets image. + /// + public Image Image { get; private set; } + + /// + /// Gets image byte buffer. + /// + public byte[] ImageByteBuffer { get; private set; } + + /// + /// Gets http status code. + /// + public HttpStatusCode? HttpStatusCode { get; private set; } + + public bool IsEmptyImage { get; set; } = false; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs b/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs index 7d90c088b6c..3315f1499f8 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs @@ -14,19 +14,17 @@ public class ImageParameter : IDataBindingsAccessor { private readonly DataBindingCollection _dataBindings = new DataBindingCollection(); + public event EventHandler DataBinding; + public string Name { get; set; } public string Value { get; set; } - public event EventHandler DataBinding; + public Control BindingContainer { get; internal set; } + + DataBindingCollection IDataBindingsAccessor.DataBindings => this._dataBindings; - internal void DataBind() - { - if (this.DataBinding != null) - { - this.DataBinding(this, EventArgs.Empty); - } - } + bool IDataBindingsAccessor.HasDataBindings => this._dataBindings.Count != 0; public override string ToString() { @@ -38,10 +36,12 @@ public override string ToString() return string.Format(CultureInfo.InvariantCulture, "{0} = {1}", this.Name, this.Value); } - public Control BindingContainer { get; internal set; } - - DataBindingCollection IDataBindingsAccessor.DataBindings => this._dataBindings; - - bool IDataBindingsAccessor.HasDataBindings => this._dataBindings.Count != 0; + internal void DataBind() + { + if (this.DataBinding != null) + { + this.DataBinding(this, EventArgs.Empty); + } + } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs index af53aebf056..fffe4e09aeb 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs @@ -14,6 +14,16 @@ namespace DotNetNuke.Services.GeneratedImage.ImageQuantization /// public class OctreeQuantizer : Quantizer { + /// + /// Stores the tree. + /// + private Octree _octree; + + /// + /// Maximum allowed color depth. + /// + private int _maxColors; + /// /// Initializes a new instance of the class. /// Construct the octree quantizer. @@ -63,7 +73,7 @@ protected override void InitialQuantizePixel(Color32 pixel) /// The quantized value. protected override byte QuantizePixel(Color32 pixel) { - byte paletteIndex = (byte)this._maxColors; // The color at [_maxColors] is set to transparent + byte paletteIndex = (byte)this._maxColors; // The color at [_maxColors] is set to transparent // Get the palette index if this non-transparent if (pixel.Alpha > 0) @@ -82,7 +92,7 @@ protected override byte QuantizePixel(Color32 pixel) protected override ColorPalette GetPalette(ColorPalette original) { // First off convert the octree to _maxColors colors - ArrayList palette = this._octree.Palletize(this._maxColors - 1); + ArrayList palette = this._octree.Palletize(this._maxColors - 1); // Then convert the palette based on those colors for (int index = 0; index < palette.Count; index++) @@ -96,21 +106,26 @@ protected override ColorPalette GetPalette(ColorPalette original) return original; } - /// - /// Stores the tree. - /// - private Octree _octree; - - /// - /// Maximum allowed color depth. - /// - private int _maxColors; - /// /// Class which does the actual quantization. /// private class Octree { + /// + /// Mask used when getting the appropriate pixels for a given node. + /// + private static readonly int[] mask = new int[8] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; + + /// + /// The root of the octree. + /// + private OctreeNode _root; + + /// + /// Number of leaves in the tree. + /// + private int _leafCount; + /// /// Initializes a new instance of the class. /// Construct the octree. @@ -126,6 +141,23 @@ public Octree(int maxColorBits) this._previousNode = null; } + /// + /// Gets or sets get/Set the number of leaves in the tree. + /// + public int Leaves + { + get { return this._leafCount; } + set { this._leafCount = value; } + } + + /// + /// Gets return the array of reducible nodes. + /// + protected OctreeNode[] ReducibleNodes + { + get { return this._reducibleNodes; } + } + /// /// Add a given color value to the octree. /// @@ -180,32 +212,6 @@ public void Reduce() this._previousNode = null; } - /// - /// Gets or sets get/Set the number of leaves in the tree. - /// - public int Leaves - { - get { return this._leafCount; } - set { this._leafCount = value; } - } - - /// - /// Gets return the array of reducible nodes. - /// - protected OctreeNode[] ReducibleNodes - { - get { return this._reducibleNodes; } - } - - /// - /// Keep track of the previous node that was quantized. - /// - /// The node last quantized. - protected void TrackPrevious(OctreeNode node) - { - this._previousNode = node; - } - /// /// Convert the nodes in the octree to a palette with a maximum of colorCount colors. /// @@ -219,7 +225,7 @@ public ArrayList Palletize(int colorCount) } // Now palettize the nodes - ArrayList palette = new ArrayList(this.Leaves); + ArrayList palette = new ArrayList(this.Leaves); int paletteIndex = 0; this._root.ConstructPalette(palette, ref paletteIndex); @@ -238,24 +244,18 @@ public int GetPaletteIndex(Color32 pixel) } /// - /// Mask used when getting the appropriate pixels for a given node. - /// - private static readonly int[] mask = new int[8] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; - - /// - /// The root of the octree. - /// - private OctreeNode _root; - - /// - /// Number of leaves in the tree. + /// Keep track of the previous node that was quantized. /// - private int _leafCount; + /// The node last quantized. + protected void TrackPrevious(OctreeNode node) + { + this._previousNode = node; + } /// /// Array of reducible nodes. /// - private OctreeNode[] _reducibleNodes; + private OctreeNode[] _reducibleNodes; /// /// Maximum number of significant bits in the image. @@ -277,6 +277,21 @@ public int GetPaletteIndex(Color32 pixel) /// protected class OctreeNode { + /// + /// Flag indicating that this is a leaf node. + /// + private bool _leaf; + + /// + /// Number of pixels in this node. + /// + private int _pixelCount; + + /// + /// Red component. + /// + private int _red; + /// /// Initializes a new instance of the class. /// Construct the node. @@ -308,6 +323,23 @@ public OctreeNode(int level, int colorBits, Octree octree) } } + /// + /// Gets or sets get/Set the next reducible node. + /// + public OctreeNode NextReducible + { + get { return this._nextReducible; } + set { this._nextReducible = value; } + } + + /// + /// Gets return the child nodes. + /// + public OctreeNode[] Children + { + get { return this._children; } + } + /// /// Add a color into the tree. /// @@ -333,7 +365,7 @@ public void AddColor(Color32 pixel, int colorBits, int level, Octree octree) ((pixel.Green & mask[level]) >> (shift - 1)) | ((pixel.Blue & mask[level]) >> shift); - OctreeNode child = this._children[index]; + OctreeNode child = this._children[index]; if (child == null) { @@ -347,23 +379,6 @@ public void AddColor(Color32 pixel, int colorBits, int level, Octree octree) } } - /// - /// Gets or sets get/Set the next reducible node. - /// - public OctreeNode NextReducible - { - get { return this._nextReducible; } - set { this._nextReducible = value; } - } - - /// - /// Gets return the child nodes. - /// - public OctreeNode[] Children - { - get { return this._children; } - } - /// /// Reduce this node by removing all of its children. /// @@ -460,21 +475,6 @@ public void Increment(Color32 pixel) this._blue += pixel.Blue; } - /// - /// Flag indicating that this is a leaf node. - /// - private bool _leaf; - - /// - /// Number of pixels in this node. - /// - private int _pixelCount; - - /// - /// Red component. - /// - private int _red; - /// /// Green Component. /// @@ -488,7 +488,7 @@ public void Increment(Color32 pixel) /// /// Pointers to any child nodes. /// - private OctreeNode[] _children; + private OctreeNode[] _children; /// /// Pointer to next reducible node. diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs index 5c7613246f1..d409710242a 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs @@ -15,6 +15,16 @@ namespace DotNetNuke.Services.GeneratedImage.ImageQuantization [CLSCompliant(false)] public class PaletteQuantizer : Quantizer { + /// + /// List of all colors in the palette. + /// + protected Color[] _colors; + + /// + /// Lookup table for colors. + /// + private readonly Hashtable _colorMap; + /// /// Initializes a new instance of the class. /// Construct the palette quantizer. @@ -39,7 +49,7 @@ public PaletteQuantizer(ArrayList palette) /// The quantized value. protected override byte QuantizePixel(Color32 pixel) { - byte colorIndex = 0; + byte colorIndex = 0; int colorHash = pixel.ARGB; // Check if the color is in the lookup table @@ -74,7 +84,7 @@ protected override byte QuantizePixel(Color32 pixel) // Loop through the entire palette, looking for the closest color match for (int index = 0; index < this._colors.Length; index++) { - Color paletteColor = this._colors[index]; + Color paletteColor = this._colors[index]; int redDistance = paletteColor.R - red; int greenDistance = paletteColor.G - green; @@ -119,15 +129,5 @@ protected override ColorPalette GetPalette(ColorPalette palette) return palette; } - - /// - /// Lookup table for colors. - /// - private readonly Hashtable _colorMap; - - /// - /// List of all colors in the palette. - /// - protected Color[] _colors; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs index 4ba787664be..1ba2d5f5408 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs @@ -14,6 +14,12 @@ namespace DotNetNuke.Services.GeneratedImage.ImageQuantization /// public abstract class Quantizer { + /// + /// Flag used to indicate whether a single pass or two passes are needed for quantization. + /// + private bool _singlePass; + private int _pixelSize; + /// /// Initializes a new instance of the class. /// Construct the quantizer. @@ -226,12 +232,6 @@ protected virtual void InitialQuantizePixel(Color32 pixel) /// The new color palette. protected abstract ColorPalette GetPalette(ColorPalette original); - /// - /// Flag used to indicate whether a single pass or two passes are needed for quantization. - /// - private bool _singlePass; - private int _pixelSize; - /// /// Struct that defines a 32 bpp colour. /// @@ -243,11 +243,6 @@ protected virtual void InitialQuantizePixel(Color32 pixel) [StructLayout(LayoutKind.Explicit)] public struct Color32 { - public Color32(IntPtr pSourcePixel) - { - this = (Color32)Marshal.PtrToStructure(pSourcePixel, typeof(Color32)); - } - /// /// Holds the blue component of the colour. /// @@ -266,6 +261,11 @@ public Color32(IntPtr pSourcePixel) [FieldOffset(2)] public byte Red; + public Color32(IntPtr pSourcePixel) + { + this = (Color32)Marshal.PtrToStructure(pSourcePixel, typeof(Color32)); + } + /// /// Holds the alpha component of the colour. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs b/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs index 3c537dd6370..79b2f42684e 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs @@ -34,13 +34,6 @@ public abstract class ImageTransform /// public CompositingQuality CompositingQuality { get; set; } - /// - /// Process an input image applying the image transformation. - /// - /// Input image. - /// Image processed. - public abstract Image ProcessImage(Image image); - // REVIEW: should this property be abstract? /// @@ -48,6 +41,13 @@ public abstract class ImageTransform /// public virtual string UniqueString => this.GetType().FullName; + /// + /// Process an input image applying the image transformation. + /// + /// Input image. + /// Image processed. + public abstract Image ProcessImage(Image image); + /// /// Creates a new image from stream. The created image is independent of the stream. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs index 1f3c8b60f93..15124734152 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs @@ -15,6 +15,14 @@ namespace DotNetNuke.Services.GeneratedImage.StartTransform /// public class ImageFileTransform : ImageTransform { + public ImageFileTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + } + /// /// Gets or sets file path of the image. /// @@ -35,14 +43,6 @@ public class ImageFileTransform : ImageTransform /// public override string UniqueString => base.UniqueString + "-" + this.ImageFilePath + this.ImageUrl; - public ImageFileTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - } - /// /// Processes an input image applying a file image transformation. /// This will return an image after read the stream from the File Path or Url . diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs index d4c1725c019..7646776f675 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs @@ -13,6 +13,19 @@ namespace DotNetNuke.Services.GeneratedImage.StartTransform /// public class PlaceholderTransform : ImageTransform { + public PlaceholderTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + this.BackColor = Color.LightGray; + this.Color = Color.LightSlateGray; + this.Width = 0; + this.Height = 0; + this.Text = string.Empty; + } + /// /// Gets or sets the width of the placeholder image. /// @@ -43,19 +56,6 @@ public class PlaceholderTransform : ImageTransform /// public override string UniqueString => base.UniqueString + this.Width + "-" + this.Height + "-" + this.Color + "-" + this.BackColor + "-" + this.Text; - public PlaceholderTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - this.BackColor = Color.LightGray; - this.Color = Color.LightSlateGray; - this.Width = 0; - this.Height = 0; - this.Text = string.Empty; - } - /// /// Processes an input image returning a placeholder image. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs index 0464b4e1318..cb98960fb1e 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs @@ -19,6 +19,14 @@ namespace DotNetNuke.Services.GeneratedImage.StartTransform /// public class SecureFileTransform : ImageTransform { + public SecureFileTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + } + /// /// Gets or sets set IFileInfo object of given FileId. /// @@ -33,14 +41,6 @@ public class SecureFileTransform : ImageTransform /// Gets provides an Unique String for the image transformation. /// public override string UniqueString => base.UniqueString + this.SecureFile.FileId; - - public SecureFileTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - } /// /// Processes an input image returing a secure file image. @@ -64,23 +64,6 @@ public override Image ProcessImage(Image image) } } - private Image GetSecureFileExtensionIconImage() - { - var extensionImageAbsolutePath = Globals.ApplicationMapPath + "\\" + - PortalSettings.Current.DefaultIconLocation.Replace("/", "\\") + "\\" + - "Ext" + this.SecureFile.Extension + "_32x32_Standard.png"; - - if (!File.Exists(extensionImageAbsolutePath)) - { - return this.EmptyImage; - } - - using (var stream = new FileStream(extensionImageAbsolutePath, FileMode.Open)) - { - return this.CopyImage(stream); - } - } - /// /// Checks if the current user have READ permission on a given folder. /// @@ -101,5 +84,22 @@ private static bool IsImageExtension(string extension) var imageExtensions = new List { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG", ".ICO" }; return imageExtensions.Contains(extension.ToUpper()); } + + private Image GetSecureFileExtensionIconImage() + { + var extensionImageAbsolutePath = Globals.ApplicationMapPath + "\\" + + PortalSettings.Current.DefaultIconLocation.Replace("/", "\\") + "\\" + + "Ext" + this.SecureFile.Extension + "_32x32_Standard.png"; + + if (!File.Exists(extensionImageAbsolutePath)) + { + return this.EmptyImage; + } + + using (var stream = new FileStream(extensionImageAbsolutePath, FileMode.Open)) + { + return this.CopyImage(stream); + } + } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs index a82ffc176c1..12d8237a7d0 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs @@ -20,6 +20,14 @@ namespace DotNetNuke.Services.GeneratedImage.StartTransform /// public class UserProfilePicTransform : ImageTransform { + public UserProfilePicTransform() + { + this.InterpolationMode = InterpolationMode.HighQualityBicubic; + this.SmoothingMode = SmoothingMode.HighQuality; + this.PixelOffsetMode = PixelOffsetMode.HighQuality; + this.CompositingQuality = CompositingQuality.HighQuality; + } + /// /// Gets or sets the UserID of the profile pic. /// @@ -34,14 +42,6 @@ public class UserProfilePicTransform : ImageTransform /// Gets a value indicating whether is reusable. /// public bool IsReusable => false; - - public UserProfilePicTransform() - { - this.InterpolationMode = InterpolationMode.HighQualityBicubic; - this.SmoothingMode = SmoothingMode.HighQuality; - this.PixelOffsetMode = PixelOffsetMode.HighQuality; - this.CompositingQuality = CompositingQuality.HighQuality; - } /// /// Processes an input image returning the user profile picture. diff --git a/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs b/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs index 2d1721dda6d..6fa2ed401a5 100644 --- a/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs +++ b/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs @@ -24,11 +24,6 @@ public class BeaconService : ServiceLocator, IBea { private static readonly bool IsAlphaMode = DotNetNukeContext.Current?.Application?.Status == ReleaseMode.Alpha; - protected override Func GetFactory() - { - return () => new BeaconService(); - } - private string _beaconEndpoint; public string GetBeaconEndpoint() @@ -68,6 +63,11 @@ public bool IsBeaconEnabledForControlBar(UserInfo user) return enabled; } + protected override Func GetFactory() + { + return () => new BeaconService(); + } + public bool IsBeaconEnabledForPersonaBar() { return Host.ParticipateInImprovementProg && !IsAlphaMode; @@ -150,15 +150,6 @@ public string GetBeaconUrl(UserInfo user, string filePath = null) return this.GetBeaconEndpoint() + this.GetBeaconQuery(user, filePath); } - private string GetHash(string data) - { - using (var sha256 = CryptographyUtils.CreateSHA256()) - { - var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(data)); - return Convert.ToBase64String(hash); - } - } - private static RolesEnum GetUserRolesBitValues(UserInfo user) { var roles = RolesEnum.None; @@ -192,5 +183,14 @@ private static RolesEnum GetUserRolesBitValues(UserInfo user) return roles; } + + private string GetHash(string data) + { + using (var sha256 = CryptographyUtils.CreateSHA256()) + { + var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(data)); + return Convert.ToBase64String(hash); + } + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs index 3a6cd112997..76af91f2840 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs @@ -39,6 +39,8 @@ public override bool IsValid return _IsValid; } } + + public PackageDependencyInfo PackageDependency { get; set; } public override void ReadManifest(XPathNavigator dependencyNav) { @@ -48,7 +50,5 @@ public override void ReadManifest(XPathNavigator dependencyNav) Version = new Version(Util.ReadAttribute(dependencyNav, "version")), }; } - - public PackageDependencyInfo PackageDependency { get; set; } } } diff --git a/DNN Platform/Library/Services/Installer/InstallFile.cs b/DNN Platform/Library/Services/Installer/InstallFile.cs index e3ae39bc151..59fb30975bd 100644 --- a/DNN Platform/Library/Services/Installer/InstallFile.cs +++ b/DNN Platform/Library/Services/Installer/InstallFile.cs @@ -241,6 +241,17 @@ public string TempFileName /// ----------------------------------------------------------------------------- public Version Version { get; private set; } + /// ----------------------------------------------------------------------------- + /// + /// The SetVersion method sets the version of the file. + /// + /// The version of the file. + /// ----------------------------------------------------------------------------- + public void SetVersion(Version version) + { + this.Version = version; + } + /// ----------------------------------------------------------------------------- /// /// The ParseFileName parses the ZipEntry metadata. @@ -335,16 +346,5 @@ private void ReadZip(ZipInputStream unzip, ZipEntry entry) Util.WriteStream(unzip, this.TempFileName); File.SetLastWriteTime(this.TempFileName, entry.DateTime); } - - /// ----------------------------------------------------------------------------- - /// - /// The SetVersion method sets the version of the file. - /// - /// The version of the file. - /// ----------------------------------------------------------------------------- - public void SetVersion(Version version) - { - this.Version = version; - } } } diff --git a/DNN Platform/Library/Services/Installer/Installer.cs b/DNN Platform/Library/Services/Installer/Installer.cs index 94b07101740..99c5e85030f 100644 --- a/DNN Platform/Library/Services/Installer/Installer.cs +++ b/DNN Platform/Library/Services/Installer/Installer.cs @@ -169,6 +169,165 @@ public string TempInstallFolder return this.InstallerInfo.TempInstallFolder; } } + + public static XPathNavigator ConvertLegacyNavigator(XPathNavigator rootNav, InstallerInfo info) + { + XPathNavigator nav = null; + + var packageType = Null.NullString; + if (rootNav.Name == "dotnetnuke") + { + packageType = Util.ReadAttribute(rootNav, "type"); + } + else if (rootNav.Name.Equals("languagepack", StringComparison.InvariantCultureIgnoreCase)) + { + packageType = "LanguagePack"; + } + + XPathDocument legacyDoc; + string legacyManifest; + switch (packageType.ToLowerInvariant()) + { + case "module": + var sb = new StringBuilder(); + using (var writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) + { + // Write manifest start element + PackageWriterBase.WriteManifestStartElement(writer); + + // Legacy Module - Process each folder + foreach (XPathNavigator folderNav in rootNav.Select("folders/folder")) + { + var modulewriter = new ModulePackageWriter(folderNav, info); + modulewriter.WriteManifest(writer, true); + } + + // Write manifest end element + PackageWriterBase.WriteManifestEndElement(writer); + + // Close XmlWriter + writer.Close(); + } + + // Load manifest into XPathDocument for processing + legacyDoc = new XPathDocument(new StringReader(sb.ToString())); + + // Parse the package nodes + nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); + break; + case "languagepack": + // Legacy Language Pack + var languageWriter = new LanguagePackWriter(rootNav, info); + info.LegacyError = languageWriter.LegacyError; + if (string.IsNullOrEmpty(info.LegacyError)) + { + legacyManifest = languageWriter.WriteManifest(false); + legacyDoc = new XPathDocument(new StringReader(legacyManifest)); + + // Parse the package nodes + nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); + } + + break; + case "skinobject": + // Legacy Skin Object + var skinControlwriter = new SkinControlPackageWriter(rootNav, info); + legacyManifest = skinControlwriter.WriteManifest(false); + legacyDoc = new XPathDocument(new StringReader(legacyManifest)); + + // Parse the package nodes + nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); + break; + } + + return nav; + } + + public void DeleteTempFolder() + { + try + { + if (!string.IsNullOrEmpty(this.TempInstallFolder)) + { + Directory.Delete(this.TempInstallFolder, true); + } + } + catch (Exception ex) + { + Logger.Error("Exception deleting folder " + this.TempInstallFolder + " while installing " + this.InstallerInfo.ManifestFile.Name, ex); + Exceptions.Exceptions.LogException(ex); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// The Install method installs the feature. + /// + /// + /// ----------------------------------------------------------------------------- + public bool Install() + { + this.InstallerInfo.Log.StartJob(Util.INSTALL_Start); + bool bStatus = true; + try + { + bool clearClientCache = false; + this.InstallPackages(ref clearClientCache); + if (clearClientCache) + { + // Update the version of the client resources - so the cache is cleared + HostController.Instance.IncrementCrmVersion(true); + } + } + catch (Exception ex) + { + this.InstallerInfo.Log.AddFailure(ex); + bStatus = false; + } + finally + { + // Delete Temp Folder + if (!string.IsNullOrEmpty(this.TempInstallFolder)) + { + Globals.DeleteFolderRecursive(this.TempInstallFolder); + } + + this.InstallerInfo.Log.AddInfo(Util.FOLDER_DeletedBackup); + } + + if (this.InstallerInfo.Log.Valid) + { + this.InstallerInfo.Log.EndJob(Util.INSTALL_Success); + } + else + { + this.InstallerInfo.Log.EndJob(Util.INSTALL_Failed); + bStatus = false; + } + + // log installation event + this.LogInstallEvent("Package", "Install"); + + // when the installer initialized by file stream, we need save the file stream into backup folder. + if (this._inputStream != null && bStatus && this.Packages.Any()) + { + Task.Run(() => + { + this.BackupStreamIntoFile(this._inputStream, this.Packages[0].Package); + }); + } + + // Clear Host Cache + DataCache.ClearHostCache(true); + + if (Config.GetFcnMode() == Config.FcnMode.Disabled.ToString()) + { + // force application restart after the new changes only when FCN is disabled + Config.Touch(); + } + + return bStatus; + } /// ----------------------------------------------------------------------------- /// @@ -319,79 +478,6 @@ private void UnInstallPackages(bool deleteFiles) } } - public static XPathNavigator ConvertLegacyNavigator(XPathNavigator rootNav, InstallerInfo info) - { - XPathNavigator nav = null; - - var packageType = Null.NullString; - if (rootNav.Name == "dotnetnuke") - { - packageType = Util.ReadAttribute(rootNav, "type"); - } - else if (rootNav.Name.Equals("languagepack", StringComparison.InvariantCultureIgnoreCase)) - { - packageType = "LanguagePack"; - } - - XPathDocument legacyDoc; - string legacyManifest; - switch (packageType.ToLowerInvariant()) - { - case "module": - var sb = new StringBuilder(); - using (var writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) - { - // Write manifest start element - PackageWriterBase.WriteManifestStartElement(writer); - - // Legacy Module - Process each folder - foreach (XPathNavigator folderNav in rootNav.Select("folders/folder")) - { - var modulewriter = new ModulePackageWriter(folderNav, info); - modulewriter.WriteManifest(writer, true); - } - - // Write manifest end element - PackageWriterBase.WriteManifestEndElement(writer); - - // Close XmlWriter - writer.Close(); - } - - // Load manifest into XPathDocument for processing - legacyDoc = new XPathDocument(new StringReader(sb.ToString())); - - // Parse the package nodes - nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); - break; - case "languagepack": - // Legacy Language Pack - var languageWriter = new LanguagePackWriter(rootNav, info); - info.LegacyError = languageWriter.LegacyError; - if (string.IsNullOrEmpty(info.LegacyError)) - { - legacyManifest = languageWriter.WriteManifest(false); - legacyDoc = new XPathDocument(new StringReader(legacyManifest)); - - // Parse the package nodes - nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); - } - - break; - case "skinobject": - // Legacy Skin Object - var skinControlwriter = new SkinControlPackageWriter(rootNav, info); - legacyManifest = skinControlwriter.WriteManifest(false); - legacyDoc = new XPathDocument(new StringReader(legacyManifest)); - - // Parse the package nodes - nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); - break; - } - - return nav; - } - private void BackupStreamIntoFile(Stream stream, PackageInfo package) { try @@ -419,92 +505,6 @@ private void BackupStreamIntoFile(Stream stream, PackageInfo package) Logger.Error(ex); } } - - public void DeleteTempFolder() - { - try - { - if (!string.IsNullOrEmpty(this.TempInstallFolder)) - { - Directory.Delete(this.TempInstallFolder, true); - } - } - catch (Exception ex) - { - Logger.Error("Exception deleting folder " + this.TempInstallFolder + " while installing " + this.InstallerInfo.ManifestFile.Name, ex); - Exceptions.Exceptions.LogException(ex); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The Install method installs the feature. - /// - /// - /// ----------------------------------------------------------------------------- - public bool Install() - { - this.InstallerInfo.Log.StartJob(Util.INSTALL_Start); - bool bStatus = true; - try - { - bool clearClientCache = false; - this.InstallPackages(ref clearClientCache); - if (clearClientCache) - { - // Update the version of the client resources - so the cache is cleared - HostController.Instance.IncrementCrmVersion(true); - } - } - catch (Exception ex) - { - this.InstallerInfo.Log.AddFailure(ex); - bStatus = false; - } - finally - { - // Delete Temp Folder - if (!string.IsNullOrEmpty(this.TempInstallFolder)) - { - Globals.DeleteFolderRecursive(this.TempInstallFolder); - } - - this.InstallerInfo.Log.AddInfo(Util.FOLDER_DeletedBackup); - } - - if (this.InstallerInfo.Log.Valid) - { - this.InstallerInfo.Log.EndJob(Util.INSTALL_Success); - } - else - { - this.InstallerInfo.Log.EndJob(Util.INSTALL_Failed); - bStatus = false; - } - - // log installation event - this.LogInstallEvent("Package", "Install"); - - // when the installer initialized by file stream, we need save the file stream into backup folder. - if (this._inputStream != null && bStatus && this.Packages.Any()) - { - Task.Run(() => - { - this.BackupStreamIntoFile(this._inputStream, this.Packages[0].Package); - }); - } - - // Clear Host Cache - DataCache.ClearHostCache(true); - - if (Config.GetFcnMode() == Config.FcnMode.Disabled.ToString()) - { - // force application restart after the new changes only when FCN is disabled - Config.Touch(); - } - - return bStatus; - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/InstallerInfo.cs b/DNN Platform/Library/Services/Installer/InstallerInfo.cs index 600f9733cd7..b4b27d97bbc 100644 --- a/DNN Platform/Library/Services/Installer/InstallerInfo.cs +++ b/DNN Platform/Library/Services/Installer/InstallerInfo.cs @@ -359,8 +359,8 @@ private void ReadZipStream(Stream inputStream, bool isEmbeddedZip) this.ManifestFile = file; } else if (file.Extension == "dnn6" && (this.ManifestFile.Extension == "dnn" || this.ManifestFile.Extension == "dnn5")) - { - this.ManifestFile = file; + { + this.ManifestFile = file; } else if (file.Extension == "dnn5" && this.ManifestFile.Extension == "dnn") { diff --git a/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs index 67592a5a042..bb0c97b0368 100644 --- a/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs @@ -26,6 +26,19 @@ public class AssemblyInstaller : FileInstaller private static readonly string OldVersion = "0.0.0.0-" + new Version(short.MaxValue, short.MaxValue, short.MaxValue, short.MaxValue); + /// ----------------------------------------------------------------------------- + /// + /// Gets a list of allowable file extensions (in addition to the Host's List). + /// + /// A String. + public override string AllowableFiles + { + get + { + return "dll,pdb"; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("assemblies"). @@ -78,19 +91,6 @@ protected override string PhysicalBasePath } } - /// ----------------------------------------------------------------------------- - /// - /// Gets a list of allowable file extensions (in addition to the Host's List). - /// - /// A String. - public override string AllowableFiles - { - get - { - return "dll,pdb"; - } - } - /// ----------------------------------------------------------------------------- /// /// The DeleteFile method deletes a single assembly. @@ -172,6 +172,47 @@ protected override bool InstallFile(InstallFile file) return bSuccess; } + /// Reads the file's . + /// The path for the assembly whose is to be returned. + /// An or null. + private static AssemblyName ReadAssemblyName(string assemblyFile) + { + try + { + return AssemblyName.GetAssemblyName(assemblyFile); + } + catch (BadImageFormatException) + { + // assemblyFile is not a valid assembly. + return null; + } + catch (ArgumentException) + { + // assemblyFile is invalid, such as an assembly with an invalid culture. + return null; + } + catch (SecurityException) + { + // The caller does not have path discovery permission. + return null; + } + catch (FileLoadException) + { + // An assembly or module was loaded twice with two different sets of evidence. + return null; + } + } + + private static string ReadPublicKey(AssemblyName assemblyName) + { + if (assemblyName == null || !assemblyName.Flags.HasFlag(AssemblyNameFlags.PublicKey)) + { + return null; + } + + return PublicKeyTokenRegex.Match(assemblyName.FullName).Groups[1].Value; + } + /// Adds or updates the binding redirect for the assembly file, if the assembly file it strong-named. /// The assembly file. private void AddOrUpdateBindingRedirect(InstallFile file) @@ -217,47 +258,6 @@ private bool ApplyXmlMerge(InstallFile file, string xmlMergeFile) return true; } - /// Reads the file's . - /// The path for the assembly whose is to be returned. - /// An or null. - private static AssemblyName ReadAssemblyName(string assemblyFile) - { - try - { - return AssemblyName.GetAssemblyName(assemblyFile); - } - catch (BadImageFormatException) - { - // assemblyFile is not a valid assembly. - return null; - } - catch (ArgumentException) - { - // assemblyFile is invalid, such as an assembly with an invalid culture. - return null; - } - catch (SecurityException) - { - // The caller does not have path discovery permission. - return null; - } - catch (FileLoadException) - { - // An assembly or module was loaded twice with two different sets of evidence. - return null; - } - } - - private static string ReadPublicKey(AssemblyName assemblyName) - { - if (assemblyName == null || !assemblyName.Flags.HasFlag(AssemblyNameFlags.PublicKey)) - { - return null; - } - - return PublicKeyTokenRegex.Match(assemblyName.FullName).Groups[1].Value; - } - /// Gets the XML merge document to create the binding redirect. /// The path to the template binding redirect XML Merge document. /// The assembly name. diff --git a/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs index 6ba8550d18d..708c70f2c72 100644 --- a/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs @@ -35,30 +35,6 @@ public override string AllowableFiles } } - /// ----------------------------------------------------------------------------- - /// - /// The DeleteAuthentiation method deletes the Authentication System - /// from the data Store. - /// - /// ----------------------------------------------------------------------------- - private void DeleteAuthentiation() - { - try - { - AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(this.Package.PackageID); - if (authSystem != null) - { - AuthenticationController.DeleteAuthentication(authSystem); - } - - this.Log.AddInfo(string.Format(Util.AUTHENTICATION_UnRegistered, authSystem.AuthenticationType)); - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } - } - /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -114,6 +90,30 @@ public override void Install() this.Log.AddFailure(ex); } } + + /// ----------------------------------------------------------------------------- + /// + /// The DeleteAuthentiation method deletes the Authentication System + /// from the data Store. + /// + /// ----------------------------------------------------------------------------- + private void DeleteAuthentiation() + { + try + { + AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(this.Package.PackageID); + if (authSystem != null) + { + AuthenticationController.DeleteAuthentication(authSystem); + } + + this.Log.AddInfo(string.Format(Util.AUTHENTICATION_UnRegistered, authSystem.AuthenticationType)); + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs index c27366fa243..43ee5431468 100644 --- a/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs @@ -35,54 +35,55 @@ public class CleanupInstaller : FileInstaller /// ----------------------------------------------------------------------------- public override string AllowableFiles => "*"; - private bool ProcessCleanupFile() + /// ----------------------------------------------------------------------------- + /// + /// The Commit method finalises the Install and commits any pending changes. + /// + /// In the case of Clenup this is not neccessary. + /// ----------------------------------------------------------------------------- + public override void Commit() { - this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); - try - { - var strListFile = Path.Combine(this.Package.InstallerInfo.TempInstallFolder, this._fileName); - if (File.Exists(strListFile)) - { - FileSystemUtils.DeleteFiles(File.ReadAllLines(strListFile)); - } - } - catch (Exception ex) - { - this.Log.AddWarning(string.Format(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))); - return true; + // Do nothing + base.Commit(); } - private bool ProcessGlob() + /// ----------------------------------------------------------------------------- + /// + /// The Install method cleansup the files. + /// + /// ----------------------------------------------------------------------------- + public override void Install() { - this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); try { - if (this._glob.Contains("..")) + bool bSuccess = true; + if (string.IsNullOrEmpty(this._fileName) && string.IsNullOrEmpty(this._glob)) // No attribute: use the xml files definition. { - this.Log.AddWarning(Util.EXCEPTION + " - " + Util.EXCEPTION_GlobDotDotNotSupportedInCleanup); + foreach (InstallFile file in this.Files) + { + bSuccess = this.CleanupFile(file); + if (!bSuccess) + { + break; + } + } } - else + else if (!string.IsNullOrEmpty(this._fileName)) // Cleanup file provided: clean each file in the cleanup text file line one by one. { - var globs = new Matcher(StringComparison.InvariantCultureIgnoreCase); - globs.AddIncludePatterns(this._glob.Split(';')); - var files = globs.GetResultsInFullPath(Globals.ApplicationMapPath).ToArray(); - FileSystemUtils.DeleteFiles(files); + bSuccess = this.ProcessCleanupFile(); + } + else if (!string.IsNullOrEmpty(this._glob)) // A globbing pattern was provided, use it to find the files and delete what matches. + { + bSuccess = this.ProcessGlob(); } + + this.Completed = bSuccess; } catch (Exception ex) { - this.Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } - - this.Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, this.Version.ToString(3))); - return true; - } + } /// ----------------------------------------------------------------------------- /// @@ -127,6 +128,55 @@ protected override void ProcessFile(InstallFile file, XPathNavigator nav) this.Files.Add(file); } } + + private bool ProcessCleanupFile() + { + this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); + try + { + var strListFile = Path.Combine(this.Package.InstallerInfo.TempInstallFolder, this._fileName); + if (File.Exists(strListFile)) + { + FileSystemUtils.DeleteFiles(File.ReadAllLines(strListFile)); + } + } + catch (Exception ex) + { + this.Log.AddWarning(string.Format(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))); + return true; + } + + private bool ProcessGlob() + { + this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); + try + { + if (this._glob.Contains("..")) + { + this.Log.AddWarning(Util.EXCEPTION + " - " + Util.EXCEPTION_GlobDotDotNotSupportedInCleanup); + } + else + { + var globs = new Matcher(StringComparison.InvariantCultureIgnoreCase); + globs.AddIncludePatterns(this._glob.Split(';')); + var files = globs.GetResultsInFullPath(Globals.ApplicationMapPath).ToArray(); + FileSystemUtils.DeleteFiles(files); + } + } + catch (Exception ex) + { + this.Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); + } + + this.Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, this.Version.ToString(3))); + return true; + } protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) { @@ -146,56 +196,6 @@ protected override void RollbackFile(InstallFile installFile) Util.RestoreFile(installFile, this.PhysicalBasePath, this.Log); } } - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method finalises the Install and commits any pending changes. - /// - /// In the case of Clenup this is not neccessary. - /// ----------------------------------------------------------------------------- - public override void Commit() - { - // Do nothing - base.Commit(); - } - - /// ----------------------------------------------------------------------------- - /// - /// The Install method cleansup the files. - /// - /// ----------------------------------------------------------------------------- - public override void Install() - { - try - { - bool bSuccess = true; - if (string.IsNullOrEmpty(this._fileName) && string.IsNullOrEmpty(this._glob)) // No attribute: use the xml files definition. - { - foreach (InstallFile file in this.Files) - { - bSuccess = this.CleanupFile(file); - if (!bSuccess) - { - break; - } - } - } - else if (!string.IsNullOrEmpty(this._fileName)) // Cleanup file provided: clean each file in the cleanup text file line one by one. - { - bSuccess = this.ProcessCleanupFile(); - } - else if (!string.IsNullOrEmpty(this._glob)) // A globbing pattern was provided, use it to find the files and delete what matches. - { - bSuccess = this.ProcessGlob(); - } - - this.Completed = bSuccess; - } - catch (Exception ex) - { - this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); - } - } public override void ReadManifest(XPathNavigator manifestNav) { diff --git a/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs b/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs index 831ef25995a..1ef0fe3746e 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs @@ -113,6 +113,30 @@ public string PhysicalSitePath } } + public bool Skipped { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public virtual bool SupportsManifestOnlyInstall + { + get + { + return true; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Type of the component. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string Type { get; set; } + public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) { EventMessage eventMessage = null; @@ -120,15 +144,15 @@ public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) XPathNavigator eventMessageNav = manifestNav.SelectSingleNode("eventMessage"); if (eventMessageNav != null) { - eventMessage = new EventMessage - { - Priority = MessagePriority.High, - ExpirationDate = DateTime.Now.AddYears(-1), - SentDate = DateTime.Now, - Body = string.Empty, - ProcessorType = Util.ReadElement(eventMessageNav, "processorType", this.Log, Util.EVENTMESSAGE_TypeMissing), - ProcessorCommand = Util.ReadElement(eventMessageNav, "processorCommand", this.Log, Util.EVENTMESSAGE_CommandMissing), - }; + eventMessage = new EventMessage + { + Priority = MessagePriority.High, + ExpirationDate = DateTime.Now.AddYears(-1), + SentDate = DateTime.Now, + Body = string.Empty, + ProcessorType = Util.ReadElement(eventMessageNav, "processorType", this.Log, Util.EVENTMESSAGE_TypeMissing), + ProcessorCommand = Util.ReadElement(eventMessageNav, "processorCommand", this.Log, Util.EVENTMESSAGE_CommandMissing), + }; foreach (XPathNavigator attributeNav in eventMessageNav.Select("attributes/*")) { var attribName = attributeNav.Name; @@ -192,30 +216,6 @@ public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) return eventMessage; } - public bool Skipped { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - public virtual bool SupportsManifestOnlyInstall - { - get - { - return true; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Type of the component. - /// - /// A String. - /// ----------------------------------------------------------------------------- - public string Type { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets or sets the Version of the Component. diff --git a/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs index d598a29810b..ea9479d9512 100644 --- a/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs @@ -22,6 +22,40 @@ public class FileInstaller : ComponentInstallerBase private readonly List _Files = new List(); private bool _DeleteFiles = Null.NullBoolean; + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the Packages files are deleted when uninstalling the + /// package. + /// + /// A Boolean value. + /// ----------------------------------------------------------------------------- + public bool DeleteFiles + { + get + { + return this._DeleteFiles; + } + + set + { + this._DeleteFiles = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public override bool SupportsManifestOnlyInstall + { + get + { + return Null.NullBoolean; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the BasePath for the files. @@ -109,37 +143,53 @@ protected virtual string PhysicalBasePath /// ----------------------------------------------------------------------------- /// - /// Gets or sets a value indicating whether gets and sets whether the Packages files are deleted when uninstalling the - /// package. + /// The Commit method finalises the Install and commits any pending changes. /// - /// A Boolean value. + /// In the case of Files this is not neccessary. /// ----------------------------------------------------------------------------- - public bool DeleteFiles + public override void Commit() { - get + try { - return this._DeleteFiles; - } + foreach (InstallFile file in this.Files) + { + this.CommitFile(file); + } - set + this.Completed = true; + } + catch (Exception ex) { - this._DeleteFiles = value; + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } } /// ----------------------------------------------------------------------------- /// - /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. + /// The Install method installs the file component. /// - /// A Boolean. /// ----------------------------------------------------------------------------- - public override bool SupportsManifestOnlyInstall + public override void Install() { - get + try { - return Null.NullBoolean; + bool bSuccess = true; + foreach (InstallFile file in this.Files) + { + bSuccess = this.InstallFile(file); + if (!bSuccess) + { + break; + } + } + + this.Completed = bSuccess; } - } + catch (Exception ex) + { + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); + } + } /// ----------------------------------------------------------------------------- /// @@ -347,56 +397,6 @@ protected virtual void UnInstallFile(InstallFile unInstallFile) { this.DeleteFile(unInstallFile); } - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method finalises the Install and commits any pending changes. - /// - /// In the case of Files this is not neccessary. - /// ----------------------------------------------------------------------------- - public override void Commit() - { - try - { - foreach (InstallFile file in this.Files) - { - this.CommitFile(file); - } - - this.Completed = true; - } - catch (Exception ex) - { - this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The Install method installs the file component. - /// - /// ----------------------------------------------------------------------------- - public override void Install() - { - try - { - bool bSuccess = true; - foreach (InstallFile file in this.Files) - { - bSuccess = this.InstallFile(file); - if (!bSuccess) - { - break; - } - } - - this.Completed = bSuccess; - } - catch (Exception ex) - { - this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); - } - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs index de8d12d8cb2..acade88447f 100644 --- a/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs @@ -13,43 +13,43 @@ public class JavaScriptFileInstaller : FileInstaller { /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("jsfiles"). + /// Gets a list of allowable file extensions (in addition to the Host's List). /// /// A String. /// ----------------------------------------------------------------------------- - protected override string CollectionNodeName + public override string AllowableFiles { get { - return "jsfiles"; + return "js"; } - } - + } + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("jsfile"). + /// Gets the name of the Collection Node ("jsfiles"). /// /// A String. /// ----------------------------------------------------------------------------- - protected override string ItemNodeName + protected override string CollectionNodeName { get { - return "jsfile"; + return "jsfiles"; } - } - + } + /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List). + /// Gets the name of the Item Node ("jsfile"). /// /// A String. /// ----------------------------------------------------------------------------- - public override string AllowableFiles + protected override string ItemNodeName { get { - return "js"; + return "jsfile"; } } diff --git a/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs index 189ebc60676..25682665a45 100644 --- a/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs @@ -15,26 +15,6 @@ public class JavaScriptLibraryInstaller : ComponentInstallerBase { private JavaScriptLibrary _library; private JavaScriptLibrary _installedLibrary; - - 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 Commit() { @@ -64,6 +44,26 @@ public override void Install() this.Log.AddFailure(ex); } } + + 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 ReadManifest(XPathNavigator manifestNav) { diff --git a/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs index f5cdf4fc4f1..e54515a707e 100644 --- a/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs @@ -30,6 +30,17 @@ public LanguageInstaller(LanguagePackType type) { this.LanguagePackType = type; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a list of allowable file extensions (in addition to the Host's List). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public override string AllowableFiles + { + get { return "resx, xml, tdf,template"; } + } /// ----------------------------------------------------------------------------- /// @@ -58,85 +69,6 @@ protected override string ItemNodeName return "languageFile"; } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets a list of allowable file extensions (in addition to the Host's List). - /// - /// A String. - /// ----------------------------------------------------------------------------- - public override string AllowableFiles - { - get { return "resx, xml, tdf,template"; } - } - - /// ----------------------------------------------------------------------------- - /// - /// The DeleteLanguage method deletes the Language - /// from the data Store. - /// - /// ----------------------------------------------------------------------------- - private void DeleteLanguage() - { - try - { - // Attempt to get the LanguagePack - LanguagePackInfo tempLanguagePack = LanguagePackController.GetLanguagePackByPackage(this.Package.PackageID); - - // Attempt to get the Locale - Locale language = LocaleController.Instance.GetLocale(tempLanguagePack.LanguageID); - if (tempLanguagePack != null) - { - LanguagePackController.DeleteLanguagePack(tempLanguagePack); - } - - // fix DNN-26330 Removing a language pack extension removes the language - // we should not delete language when deleting language pack, as there is just a loose relationship - // if (language != null && tempLanguagePack.PackageType == LanguagePackType.Core) - // { - // Localization.DeleteLanguage(language); - // } - this.Log.AddInfo(string.Format(Util.LANGUAGE_UnRegistered, language.Text)); - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The ReadCustomManifest method reads the custom manifest items. - /// - /// The XPathNavigator representing the node. - /// ----------------------------------------------------------------------------- - protected override void ReadCustomManifest(XPathNavigator nav) - { - this.Language = new Locale(); - this.LanguagePack = new LanguagePackInfo(); - - // Get the Skin name - this.Language.Code = Util.ReadElement(nav, "code"); - this.Language.Text = Util.ReadElement(nav, "displayName"); - this.Language.Fallback = Util.ReadElement(nav, "fallback"); - - if (this.LanguagePackType == LanguagePackType.Core) - { - this.LanguagePack.DependentPackageID = -2; - } - else - { - string packageName = Util.ReadElement(nav, "package"); - PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name.Equals(packageName, StringComparison.OrdinalIgnoreCase)); - if (package != null) - { - this.LanguagePack.DependentPackageID = package.PackageID; - } - } - - // Call base class - base.ReadCustomManifest(nav); - } /// ----------------------------------------------------------------------------- /// @@ -147,8 +79,8 @@ protected override void ReadCustomManifest(XPathNavigator nav) public override void Commit() { if (this.LanguagePackType == LanguagePackType.Core || this.LanguagePack.DependentPackageID > 0) - { - base.Commit(); + { + base.Commit(); } else { @@ -211,6 +143,74 @@ public override void Install() this.Skipped = true; } } + + /// ----------------------------------------------------------------------------- + /// + /// The ReadCustomManifest method reads the custom manifest items. + /// + /// The XPathNavigator representing the node. + /// ----------------------------------------------------------------------------- + protected override void ReadCustomManifest(XPathNavigator nav) + { + this.Language = new Locale(); + this.LanguagePack = new LanguagePackInfo(); + + // Get the Skin name + this.Language.Code = Util.ReadElement(nav, "code"); + this.Language.Text = Util.ReadElement(nav, "displayName"); + this.Language.Fallback = Util.ReadElement(nav, "fallback"); + + if (this.LanguagePackType == LanguagePackType.Core) + { + this.LanguagePack.DependentPackageID = -2; + } + else + { + string packageName = Util.ReadElement(nav, "package"); + PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name.Equals(packageName, StringComparison.OrdinalIgnoreCase)); + if (package != null) + { + this.LanguagePack.DependentPackageID = package.PackageID; + } + } + + // Call base class + base.ReadCustomManifest(nav); + } + + /// ----------------------------------------------------------------------------- + /// + /// The DeleteLanguage method deletes the Language + /// from the data Store. + /// + /// ----------------------------------------------------------------------------- + private void DeleteLanguage() + { + try + { + // Attempt to get the LanguagePack + LanguagePackInfo tempLanguagePack = LanguagePackController.GetLanguagePackByPackage(this.Package.PackageID); + + // Attempt to get the Locale + Locale language = LocaleController.Instance.GetLocale(tempLanguagePack.LanguageID); + if (tempLanguagePack != null) + { + LanguagePackController.DeleteLanguagePack(tempLanguagePack); + } + + // fix DNN-26330 Removing a language pack extension removes the language + // we should not delete language when deleting language pack, as there is just a loose relationship + // if (language != null && tempLanguagePack.PackageType == LanguagePackType.Core) + // { + // Localization.DeleteLanguage(language); + // } + this.Log.AddInfo(string.Format(Util.LANGUAGE_UnRegistered, language.Text)); + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs index 75cce108652..553d9fdde63 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs @@ -44,91 +44,6 @@ public override string AllowableFiles } } - /// ----------------------------------------------------------------------------- - /// - /// The DeleteModule method deletes the Module from the data Store. - /// - /// ----------------------------------------------------------------------------- - private void DeleteModule() - { - try - { - // Attempt to get the Desktop Module - DesktopModuleInfo tempDesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(this.Package.PackageID); - if (tempDesktopModule != null) - { - var modules = ModuleController.Instance.GetModulesByDesktopModuleId(tempDesktopModule.DesktopModuleID); - - // Remove CodeSubDirectory - if ((this._desktopModule != null) && (!string.IsNullOrEmpty(this._desktopModule.CodeSubDirectory))) - { - Config.RemoveCodeSubDirectory(this._desktopModule.CodeSubDirectory); - } - - var controller = new DesktopModuleController(); - - this.Log.AddInfo(string.Format(Util.MODULE_UnRegistered, tempDesktopModule.ModuleName)); - - // remove admin/host pages - if (!string.IsNullOrEmpty(tempDesktopModule.AdminPage)) - { - string tabPath = "//Admin//" + tempDesktopModule.AdminPage; - - var portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) - { - var tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); - - TabInfo temp = TabController.Instance.GetTab(tabID, portal.PortalID); - if (temp != null) - { - var mods = TabModulesController.Instance.GetTabModules(temp); - bool noOtherTabModule = true; - foreach (ModuleInfo mod in mods) - { - if (mod.DesktopModuleID != tempDesktopModule.DesktopModuleID) - { - noOtherTabModule = false; - } - } - - if (noOtherTabModule) - { - this.Log.AddInfo(string.Format(Util.MODULE_AdminPageRemoved, tempDesktopModule.AdminPage, portal.PortalID)); - TabController.Instance.DeleteTab(tabID, portal.PortalID); - } - - this.Log.AddInfo(string.Format(Util.MODULE_AdminPagemoduleRemoved, tempDesktopModule.AdminPage, portal.PortalID)); - } - } - } - - 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)); - } - - controller.DeleteDesktopModule(tempDesktopModule); - - // Remove all the tab versions related with the module. - foreach (var module in modules) - { - var moduleInfo = module as ModuleInfo; - if (moduleInfo != null) - { - TabVersionController.Instance.DeleteTabVersionDetailByModule(moduleInfo.ModuleID); - } - } - } - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } - } - /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -146,15 +61,15 @@ public override void Commit() if (this._desktopModule.SupportedFeatures == Null.NullInteger) { // Set an Event Message so the features are loaded by reflection on restart - var oAppStartMessage = new EventMessage - { - Priority = MessagePriority.High, - ExpirationDate = DateTime.Now.AddYears(-1), - SentDate = DateTime.Now, - Body = string.Empty, - ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", - ProcessorCommand = "UpdateSupportedFeatures", - }; + var oAppStartMessage = new EventMessage + { + Priority = MessagePriority.High, + ExpirationDate = DateTime.Now.AddYears(-1), + SentDate = DateTime.Now, + Body = string.Empty, + ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke", + ProcessorCommand = "UpdateSupportedFeatures", + }; // Add custom Attributes for this message oAppStartMessage.Attributes.Add("BusinessControllerClass", this._desktopModule.BusinessControllerClass); @@ -254,6 +169,91 @@ public override void Install() this.Log.AddFailure(ex); } } + + /// ----------------------------------------------------------------------------- + /// + /// The DeleteModule method deletes the Module from the data Store. + /// + /// ----------------------------------------------------------------------------- + private void DeleteModule() + { + try + { + // Attempt to get the Desktop Module + DesktopModuleInfo tempDesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(this.Package.PackageID); + if (tempDesktopModule != null) + { + var modules = ModuleController.Instance.GetModulesByDesktopModuleId(tempDesktopModule.DesktopModuleID); + + // Remove CodeSubDirectory + if ((this._desktopModule != null) && (!string.IsNullOrEmpty(this._desktopModule.CodeSubDirectory))) + { + Config.RemoveCodeSubDirectory(this._desktopModule.CodeSubDirectory); + } + + var controller = new DesktopModuleController(); + + this.Log.AddInfo(string.Format(Util.MODULE_UnRegistered, tempDesktopModule.ModuleName)); + + // remove admin/host pages + if (!string.IsNullOrEmpty(tempDesktopModule.AdminPage)) + { + string tabPath = "//Admin//" + tempDesktopModule.AdminPage; + + var portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) + { + var tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); + + TabInfo temp = TabController.Instance.GetTab(tabID, portal.PortalID); + if (temp != null) + { + var mods = TabModulesController.Instance.GetTabModules(temp); + bool noOtherTabModule = true; + foreach (ModuleInfo mod in mods) + { + if (mod.DesktopModuleID != tempDesktopModule.DesktopModuleID) + { + noOtherTabModule = false; + } + } + + if (noOtherTabModule) + { + this.Log.AddInfo(string.Format(Util.MODULE_AdminPageRemoved, tempDesktopModule.AdminPage, portal.PortalID)); + TabController.Instance.DeleteTab(tabID, portal.PortalID); + } + + this.Log.AddInfo(string.Format(Util.MODULE_AdminPagemoduleRemoved, tempDesktopModule.AdminPage, portal.PortalID)); + } + } + } + + 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)); + } + + controller.DeleteDesktopModule(tempDesktopModule); + + // Remove all the tab versions related with the module. + foreach (var module in modules) + { + var moduleInfo = module as ModuleInfo; + if (moduleInfo != null) + { + TabVersionController.Instance.DeleteTabVersionDetailByModule(moduleInfo.ModuleID); + } + } + } + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs index bb42399c791..0a38230cec1 100644 --- a/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs @@ -100,92 +100,6 @@ public PackageInstaller(string packageManifest, InstallerInfo info) /// ----------------------------------------------------------------------------- public bool IsValid { get; private set; } - /// ----------------------------------------------------------------------------- - /// - /// The CheckSecurity method checks whether the user has the appropriate security. - /// - /// ----------------------------------------------------------------------------- - private void CheckSecurity() - { - PackageType type = PackageController.Instance.GetExtensionPackageType(t => t.PackageType.Equals(this.Package.PackageType, StringComparison.OrdinalIgnoreCase)); - if (type == null) - { - // This package type not registered - this.Log.Logs.Clear(); - this.Log.AddFailure(Util.SECURITY_NotRegistered + " - " + this.Package.PackageType); - this.IsValid = false; - } - else - { - if (type.SecurityAccessLevel > this.Package.InstallerInfo.SecurityAccessLevel) - { - this.Log.Logs.Clear(); - this.Log.AddFailure(Util.SECURITY_Installer); - this.IsValid = false; - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The ReadComponents method reads the components node of the manifest file. - /// - /// ----------------------------------------------------------------------------- - private void ReadComponents(XPathNavigator manifestNav) - { - foreach (XPathNavigator componentNav in manifestNav.CreateNavigator().Select("components/component")) - { - // Set default order to next value (ie the same as the size of the collection) - int order = this._componentInstallers.Count; - - string type = componentNav.GetAttribute("type", string.Empty); - if (this.InstallMode == InstallMode.Install) - { - string installOrder = componentNav.GetAttribute("installOrder", string.Empty); - if (!string.IsNullOrEmpty(installOrder)) - { - order = int.Parse(installOrder); - } - } - else - { - string unInstallOrder = componentNav.GetAttribute("unInstallOrder", string.Empty); - if (!string.IsNullOrEmpty(unInstallOrder)) - { - order = int.Parse(unInstallOrder); - } - } - - if (this.Package.InstallerInfo != null) - { - this.Log.AddInfo(Util.DNN_ReadingComponent + " - " + type); - } - - ComponentInstallerBase installer = InstallerFactory.GetInstaller(componentNav, this.Package); - if (installer == null) - { - this.Log.AddFailure(Util.EXCEPTION_InstallerCreate); - } - else - { - this._componentInstallers.Add(order, installer); - this.Package.InstallerInfo.AllowableFiles += ", " + installer.AllowableFiles; - } - } - } - - private string ReadTextFromFile(string source) - { - string strText = Null.NullString; - if (this.Package.InstallerInfo.InstallMode != InstallMode.ManifestOnly) - { - // Load from file - strText = FileSystemUtils.ReadFile(this.Package.InstallerInfo.TempInstallFolder + "\\" + source); - } - - return strText; - } - /// ----------------------------------------------------------------------------- /// /// The Commit method commits the package installation. @@ -284,6 +198,92 @@ public override void Install() this.Rollback(); } } + + /// ----------------------------------------------------------------------------- + /// + /// The CheckSecurity method checks whether the user has the appropriate security. + /// + /// ----------------------------------------------------------------------------- + private void CheckSecurity() + { + PackageType type = PackageController.Instance.GetExtensionPackageType(t => t.PackageType.Equals(this.Package.PackageType, StringComparison.OrdinalIgnoreCase)); + if (type == null) + { + // This package type not registered + this.Log.Logs.Clear(); + this.Log.AddFailure(Util.SECURITY_NotRegistered + " - " + this.Package.PackageType); + this.IsValid = false; + } + else + { + if (type.SecurityAccessLevel > this.Package.InstallerInfo.SecurityAccessLevel) + { + this.Log.Logs.Clear(); + this.Log.AddFailure(Util.SECURITY_Installer); + this.IsValid = false; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// The ReadComponents method reads the components node of the manifest file. + /// + /// ----------------------------------------------------------------------------- + private void ReadComponents(XPathNavigator manifestNav) + { + foreach (XPathNavigator componentNav in manifestNav.CreateNavigator().Select("components/component")) + { + // Set default order to next value (ie the same as the size of the collection) + int order = this._componentInstallers.Count; + + string type = componentNav.GetAttribute("type", string.Empty); + if (this.InstallMode == InstallMode.Install) + { + string installOrder = componentNav.GetAttribute("installOrder", string.Empty); + if (!string.IsNullOrEmpty(installOrder)) + { + order = int.Parse(installOrder); + } + } + else + { + string unInstallOrder = componentNav.GetAttribute("unInstallOrder", string.Empty); + if (!string.IsNullOrEmpty(unInstallOrder)) + { + order = int.Parse(unInstallOrder); + } + } + + if (this.Package.InstallerInfo != null) + { + this.Log.AddInfo(Util.DNN_ReadingComponent + " - " + type); + } + + ComponentInstallerBase installer = InstallerFactory.GetInstaller(componentNav, this.Package); + if (installer == null) + { + this.Log.AddFailure(Util.EXCEPTION_InstallerCreate); + } + else + { + this._componentInstallers.Add(order, installer); + this.Package.InstallerInfo.AllowableFiles += ", " + installer.AllowableFiles; + } + } + } + + private string ReadTextFromFile(string source) + { + string strText = Null.NullString; + if (this.Package.InstallerInfo.InstallMode != InstallMode.ManifestOnly) + { + // Load from file + strText = FileSystemUtils.ReadFile(this.Package.InstallerInfo.TempInstallFolder + "\\" + source); + } + + return strText; + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs index c12b6a3f77f..106cd2e94b1 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs @@ -21,10 +21,24 @@ namespace DotNetNuke.Services.Installer.Installers /// ----------------------------------------------------------------------------- public class ResourceFileInstaller : FileInstaller { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ResourceFileInstaller)); public const string DEFAULT_MANIFESTEXT = ".manifest"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ResourceFileInstaller)); private string _Manifest; + /// ----------------------------------------------------------------------------- + /// + /// Gets a list of allowable file extensions (in addition to the Host's List). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public override string AllowableFiles + { + get + { + return "resources, zip"; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("resourceFiles"). @@ -62,20 +76,6 @@ protected string Manifest } } - /// ----------------------------------------------------------------------------- - /// - /// Gets a list of allowable file extensions (in addition to the Host's List). - /// - /// A String. - /// ----------------------------------------------------------------------------- - public override string AllowableFiles - { - get - { - return "resources, zip"; - } - } - /// ----------------------------------------------------------------------------- /// /// The CommitFile method commits a single file. diff --git a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs index 78161b41c24..4bc8102d0ea 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs @@ -26,6 +26,20 @@ public class ScriptInstaller : FileInstaller private InstallFile _installScript; private InstallFile _upgradeScript; + /// ----------------------------------------------------------------------------- + /// + /// Gets a list of allowable file extensions (in addition to the Host's List). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public override string AllowableFiles + { + get + { + return "*dataprovider, sql"; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the base Install Script (if present). @@ -120,75 +134,82 @@ protected InstallFile UpgradeScript /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List). + /// The Commit method finalises the Install and commits any pending changes. /// - /// A String. + /// In the case of Files this is not neccessary. /// ----------------------------------------------------------------------------- - public override string AllowableFiles - { - get - { - return "*dataprovider, sql"; - } - } - - private bool ExecuteSql(InstallFile scriptFile) + public override void Commit() { - bool bSuccess = true; - - this.Log.AddInfo(string.Format(Util.SQL_BeginFile, scriptFile.Name)); - - // read script file for installation - string strScript = FileSystemUtils.ReadFile(this.PhysicalBasePath + scriptFile.FullName); + base.Commit(); + } - // 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("?")) - { - strScript = strScript.Substring(1); - } - - string strSQLExceptions = DataProvider.Instance().ExecuteScript(strScript); - if (!string.IsNullOrEmpty(strSQLExceptions)) + /// ----------------------------------------------------------------------------- + /// + /// The Install method installs the script component. + /// + /// ----------------------------------------------------------------------------- + public override void Install() + { + this.Log.AddInfo(Util.SQL_Begin); + try { - if (this.Package.InstallerInfo.IsLegacyMode) + bool bSuccess = true; + Version installedVersion = this.Package.InstalledVersion; + + // First process InstallScript + if (installedVersion == new Version(0, 0, 0)) { - this.Log.AddWarning(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); + if (this.InstallScript != null) + { + bSuccess = this.InstallScriptFile(this.InstallScript); + installedVersion = this.InstallScript.Version; + } } - else + + // Then process remain Install/Upgrade Scripts + if (bSuccess) { - this.Log.AddFailure(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); - bSuccess = false; + foreach (InstallFile file in this.InstallScripts.Values) + { + if (file.Version > installedVersion) + { + bSuccess = this.InstallScriptFile(file); + if (!bSuccess) + { + break; + } + } + } } - } - - this.Log.AddInfo(string.Format(Util.SQL_EndFile, scriptFile.Name)); - return bSuccess; - } - private bool IsValidScript(string fileExtension) - { - return this.ProviderConfiguration.DefaultProvider.Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase) || fileExtension.Equals("sql", StringComparison.InvariantCultureIgnoreCase); - } - - private bool InstallScriptFile(InstallFile scriptFile) - { - // Call base InstallFile method to copy file - bool bSuccess = this.InstallFile(scriptFile); + // Next process UpgradeScript - this script always runs if present + if (this.UpgradeScript != null) + { + bSuccess = this.InstallScriptFile(this.UpgradeScript); + installedVersion = this.UpgradeScript.Version; + } - // Process the file if it is an Install Script - var extension = Path.GetExtension(scriptFile.Name.ToLowerInvariant()); - if (extension != null) - { - string fileExtension = extension.Substring(1); - if (bSuccess && this.IsValidScript(fileExtension)) + // Then process uninstallScripts - these need to be copied but not executed + if (bSuccess) { - this.Log.AddInfo(Util.SQL_Executing + scriptFile.Name); - bSuccess = this.ExecuteSql(scriptFile); + foreach (InstallFile file in this.UnInstallScripts.Values) + { + bSuccess = this.InstallFile(file); + if (!bSuccess) + { + break; + } + } } + + this.Completed = bSuccess; + } + catch (Exception ex) + { + this.Log.AddFailure(ex); } - return bSuccess; + this.Log.AddInfo(Util.SQL_End); } /// ----------------------------------------------------------------------------- @@ -239,6 +260,65 @@ protected override void ProcessFile(InstallFile file, XPathNavigator nav) // Call base method to set up for file processing base.ProcessFile(file, nav); } + + private bool ExecuteSql(InstallFile scriptFile) + { + bool bSuccess = true; + + this.Log.AddInfo(string.Format(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 + // The extra character - '?' - causes an error with the database. + if (strScript.StartsWith("?")) + { + strScript = strScript.Substring(1); + } + + 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)); + } + else + { + this.Log.AddFailure(string.Format(Util.SQL_Exceptions, Environment.NewLine, strSQLExceptions)); + bSuccess = false; + } + } + + this.Log.AddInfo(string.Format(Util.SQL_EndFile, scriptFile.Name)); + return bSuccess; + } + + private bool IsValidScript(string fileExtension) + { + return this.ProviderConfiguration.DefaultProvider.Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase) || fileExtension.Equals("sql", StringComparison.InvariantCultureIgnoreCase); + } + + private bool InstallScriptFile(InstallFile scriptFile) + { + // Call base InstallFile method to copy file + bool bSuccess = this.InstallFile(scriptFile); + + // Process the file if it is an Install Script + var extension = Path.GetExtension(scriptFile.Name.ToLowerInvariant()); + if (extension != null) + { + string fileExtension = extension.Substring(1); + if (bSuccess && this.IsValidScript(fileExtension)) + { + this.Log.AddInfo(Util.SQL_Executing + scriptFile.Name); + bSuccess = this.ExecuteSql(scriptFile); + } + } + + return bSuccess; + } protected override void UnInstallFile(InstallFile scriptFile) { @@ -258,86 +338,6 @@ protected override void UnInstallFile(InstallFile scriptFile) // Call base method to delete file base.UnInstallFile(scriptFile); } - - /// ----------------------------------------------------------------------------- - /// - /// The Commit method finalises the Install and commits any pending changes. - /// - /// In the case of Files this is not neccessary. - /// ----------------------------------------------------------------------------- - public override void Commit() - { - base.Commit(); - } - - /// ----------------------------------------------------------------------------- - /// - /// The Install method installs the script component. - /// - /// ----------------------------------------------------------------------------- - public override void Install() - { - this.Log.AddInfo(Util.SQL_Begin); - try - { - bool bSuccess = true; - Version installedVersion = this.Package.InstalledVersion; - - // First process InstallScript - if (installedVersion == new Version(0, 0, 0)) - { - if (this.InstallScript != null) - { - bSuccess = this.InstallScriptFile(this.InstallScript); - installedVersion = this.InstallScript.Version; - } - } - - // Then process remain Install/Upgrade Scripts - if (bSuccess) - { - foreach (InstallFile file in this.InstallScripts.Values) - { - if (file.Version > installedVersion) - { - bSuccess = this.InstallScriptFile(file); - if (!bSuccess) - { - break; - } - } - } - } - - // Next process UpgradeScript - this script always runs if present - if (this.UpgradeScript != null) - { - bSuccess = this.InstallScriptFile(this.UpgradeScript); - installedVersion = this.UpgradeScript.Version; - } - - // Then process uninstallScripts - these need to be copied but not executed - if (bSuccess) - { - foreach (InstallFile file in this.UnInstallScripts.Values) - { - bSuccess = this.InstallFile(file); - if (!bSuccess) - { - break; - } - } - } - - this.Completed = bSuccess; - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } - - this.Log.AddInfo(Util.SQL_End); - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs index 81a37933e8f..06e42d33362 100644 --- a/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs @@ -36,30 +36,6 @@ public override string AllowableFiles } } - /// ----------------------------------------------------------------------------- - /// - /// The DeleteSkinControl method deletes the SkinControl from the data Store. - /// - /// ----------------------------------------------------------------------------- - private void DeleteSkinControl() - { - try - { - // Attempt to get the SkinControl - SkinControlInfo skinControl = SkinControlController.GetSkinControlByPackageID(this.Package.PackageID); - if (skinControl != null) - { - SkinControlController.DeleteSkinControl(skinControl); - } - - this.Log.AddInfo(string.Format(Util.MODULE_UnRegistered, skinControl.ControlKey)); - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } - } - /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -99,6 +75,30 @@ public override void Install() this.Log.AddFailure(ex); } } + + /// ----------------------------------------------------------------------------- + /// + /// The DeleteSkinControl method deletes the SkinControl from the data Store. + /// + /// ----------------------------------------------------------------------------- + private void DeleteSkinControl() + { + try + { + // Attempt to get the SkinControl + SkinControlInfo skinControl = SkinControlController.GetSkinControlByPackageID(this.Package.PackageID); + if (skinControl != null) + { + SkinControlController.DeleteSkinControl(skinControl); + } + + this.Log.AddInfo(string.Format(Util.MODULE_UnRegistered, skinControl.ControlKey)); + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs index a38dceb96b0..a0fd91b89ab 100644 --- a/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs @@ -28,6 +28,20 @@ public class SkinInstaller : FileInstaller private SkinPackageInfo TempSkinPackage; private string _SkinName = Null.NullString; + /// ----------------------------------------------------------------------------- + /// + /// Gets a list of allowable file extensions (in addition to the Host's List). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public override string AllowableFiles + { + get + { + return "ascx, html, htm, css, xml, js, resx, jpg, jpeg, gif, png"; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("skinFiles"). @@ -156,110 +170,6 @@ protected virtual string SkinType } } - /// ----------------------------------------------------------------------------- - /// - /// Gets a list of allowable file extensions (in addition to the Host's List). - /// - /// A String. - /// ----------------------------------------------------------------------------- - public override string AllowableFiles - { - get - { - return "ascx, html, htm, css, xml, js, resx, jpg, jpeg, gif, png"; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The DeleteSkinPackage method deletes the Skin Package - /// from the data Store. - /// - /// ----------------------------------------------------------------------------- - private void DeleteSkinPackage() - { - try - { - // Attempt to get the Authentication Service - SkinPackageInfo skinPackage = SkinController.GetSkinByPackageID(this.Package.PackageID); - if (skinPackage != null) - { - SkinController.DeleteSkinPackage(skinPackage); - } - - this.Log.AddInfo(string.Format(Util.SKIN_UnRegistered, skinPackage.SkinName)); - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The ProcessFile method determines what to do with parsed "file" node. - /// - /// The file represented by the node. - /// The XPathNavigator representing the node. - /// ----------------------------------------------------------------------------- - protected override void ProcessFile(InstallFile file, XPathNavigator nav) - { - switch (file.Extension) - { - case "htm": - case "html": - case "ascx": - case "css": - if (file.Path.IndexOf(Globals.glbAboutPage, StringComparison.InvariantCultureIgnoreCase) < 0) - { - this.SkinFiles.Add(this.PhysicalBasePath + file.FullName); - } - - break; - } - - // Call base method to set up for file processing - base.ProcessFile(file, nav); - } - - /// ----------------------------------------------------------------------------- - /// - /// The ReadCustomManifest method reads the custom manifest items. - /// - /// The XPathNavigator representing the node. - /// ----------------------------------------------------------------------------- - protected override void ReadCustomManifest(XPathNavigator nav) - { - this.SkinPackage = new SkinPackageInfo(); - this.SkinPackage.PortalID = this.Package.PortalID; - - // Get the Skin name - this.SkinPackage.SkinName = Util.ReadElement(nav, this.SkinNameNodeName); - - // Call base class - base.ReadCustomManifest(nav); - } - - /// ----------------------------------------------------------------------------- - /// - /// The UnInstallFile method unInstalls a single file. - /// - /// The InstallFile to unInstall. - /// ----------------------------------------------------------------------------- - protected override void UnInstallFile(InstallFile unInstallFile) - { - // Uninstall file - base.UnInstallFile(unInstallFile); - - if (unInstallFile.Extension == "htm" || unInstallFile.Extension == "html") - { - // Try to remove "processed file" - string fileName = unInstallFile.FullName; - fileName = fileName.Replace(Path.GetExtension(fileName), ".ascx"); - Util.DeleteFile(fileName, this.PhysicalBasePath, this.Log); - } - } - /// ----------------------------------------------------------------------------- /// /// The Install method installs the skin component. @@ -372,6 +282,96 @@ public override void Rollback() // Call base class to prcoess files base.Rollback(); } + + /// ----------------------------------------------------------------------------- + /// + /// The ProcessFile method determines what to do with parsed "file" node. + /// + /// The file represented by the node. + /// The XPathNavigator representing the node. + /// ----------------------------------------------------------------------------- + protected override void ProcessFile(InstallFile file, XPathNavigator nav) + { + switch (file.Extension) + { + case "htm": + case "html": + case "ascx": + case "css": + if (file.Path.IndexOf(Globals.glbAboutPage, StringComparison.InvariantCultureIgnoreCase) < 0) + { + this.SkinFiles.Add(this.PhysicalBasePath + file.FullName); + } + + break; + } + + // Call base method to set up for file processing + base.ProcessFile(file, nav); + } + + /// ----------------------------------------------------------------------------- + /// + /// The ReadCustomManifest method reads the custom manifest items. + /// + /// The XPathNavigator representing the node. + /// ----------------------------------------------------------------------------- + protected override void ReadCustomManifest(XPathNavigator nav) + { + this.SkinPackage = new SkinPackageInfo(); + this.SkinPackage.PortalID = this.Package.PortalID; + + // Get the Skin name + this.SkinPackage.SkinName = Util.ReadElement(nav, this.SkinNameNodeName); + + // Call base class + base.ReadCustomManifest(nav); + } + + /// ----------------------------------------------------------------------------- + /// + /// The DeleteSkinPackage method deletes the Skin Package + /// from the data Store. + /// + /// ----------------------------------------------------------------------------- + private void DeleteSkinPackage() + { + try + { + // Attempt to get the Authentication Service + SkinPackageInfo skinPackage = SkinController.GetSkinByPackageID(this.Package.PackageID); + if (skinPackage != null) + { + SkinController.DeleteSkinPackage(skinPackage); + } + + this.Log.AddInfo(string.Format(Util.SKIN_UnRegistered, skinPackage.SkinName)); + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// The UnInstallFile method unInstalls a single file. + /// + /// The InstallFile to unInstall. + /// ----------------------------------------------------------------------------- + protected override void UnInstallFile(InstallFile unInstallFile) + { + // Uninstall file + base.UnInstallFile(unInstallFile); + + if (unInstallFile.Extension == "htm" || unInstallFile.Extension == "html") + { + // Try to remove "processed file" + string fileName = unInstallFile.FullName; + fileName = fileName.Replace(Path.GetExtension(fileName), ".ascx"); + Util.DeleteFile(fileName, this.PhysicalBasePath, this.Log); + } + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs index c6fb93c8659..835ca0d4442 100644 --- a/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs @@ -31,24 +31,6 @@ public override string AllowableFiles } } - private void DeleteProvider() - { - try - { - ExtensionUrlProviderInfo tempUrlProvider = ExtensionUrlProviderController.GetProviders(Null.NullInteger).Where(p => p.ProviderName == this._extensionUrlProvider.ProviderName && p.ProviderType == this._extensionUrlProvider.ProviderType).FirstOrDefault(); - if (tempUrlProvider != null) - { - ExtensionUrlProviderController.DeleteProvider(tempUrlProvider); - - this.Log.AddInfo(string.Format(Util.URLPROVIDER_UnRegistered, tempUrlProvider.ProviderName)); - } - } - catch (Exception ex) - { - this.Log.AddFailure(ex); - } - } - /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -96,6 +78,24 @@ public override void Install() } } + private void DeleteProvider() + { + try + { + ExtensionUrlProviderInfo tempUrlProvider = ExtensionUrlProviderController.GetProviders(Null.NullInteger).Where(p => p.ProviderName == this._extensionUrlProvider.ProviderName && p.ProviderType == this._extensionUrlProvider.ProviderType).FirstOrDefault(); + if (tempUrlProvider != null) + { + ExtensionUrlProviderController.DeleteProvider(tempUrlProvider); + + this.Log.AddInfo(string.Format(Util.URLPROVIDER_UnRegistered, tempUrlProvider.ProviderName)); + } + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } + /// ----------------------------------------------------------------------------- /// /// The ReadManifest method reads the manifest file for the compoent. @@ -104,15 +104,15 @@ public override void Install() public override void ReadManifest(XPathNavigator manifestNav) { this._extensionUrlProvider = new ExtensionUrlProviderInfo - { - ProviderName = Util.ReadElement(manifestNav, "urlProvider/name", this.Log, Util.URLPROVIDER_NameMissing), - ProviderType = Util.ReadElement(manifestNav, "urlProvider/type", this.Log, Util.URLPROVIDER_TypeMissing), - SettingsControlSrc = Util.ReadElement(manifestNav, "urlProvider/settingsControlSrc"), - IsActive = true, - RedirectAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/redirectAllUrls", "false")), - ReplaceAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/replaceAllUrls", "false")), - RewriteAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/rewriteAllUrls", "false")), - }; + { + ProviderName = Util.ReadElement(manifestNav, "urlProvider/name", this.Log, Util.URLPROVIDER_NameMissing), + ProviderType = Util.ReadElement(manifestNav, "urlProvider/type", this.Log, Util.URLPROVIDER_TypeMissing), + SettingsControlSrc = Util.ReadElement(manifestNav, "urlProvider/settingsControlSrc"), + IsActive = true, + RedirectAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/redirectAllUrls", "false")), + ReplaceAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/replaceAllUrls", "false")), + RewriteAllUrls = Convert.ToBoolean(Util.ReadElement(manifestNav, "urlProvider/rewriteAllUrls", "false")), + }; this._desktopModuleName = Util.ReadElement(manifestNav, "urlProvider/desktopModule"); if (this.Log.Valid) diff --git a/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs index 8e89b4ce6a3..de509d94889 100644 --- a/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs @@ -18,58 +18,58 @@ public class WidgetInstaller : FileInstaller { /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Collection Node ("widgetFiles"). + /// Gets a list of allowable file extensions (in addition to the Host's List). /// /// A String. /// ----------------------------------------------------------------------------- - protected override string CollectionNodeName + public override string AllowableFiles { get { - return "widgetFiles"; + return "js"; } } - + /// ----------------------------------------------------------------------------- /// - /// Gets the name of the Item Node ("widgetFiles"). + /// Gets the name of the Collection Node ("widgetFiles"). /// /// A String. /// ----------------------------------------------------------------------------- - protected override string ItemNodeName + protected override string CollectionNodeName { get { - return "widgetFile"; + return "widgetFiles"; } } /// ----------------------------------------------------------------------------- /// - /// Gets the PhysicalBasePath for the widget files. + /// Gets the name of the Item Node ("widgetFiles"). /// /// A String. /// ----------------------------------------------------------------------------- - protected override string PhysicalBasePath + protected override string ItemNodeName { get { - string widgetPath = Path.Combine("Resources\\Widgets\\User", this.BasePath); - return Path.Combine(Globals.ApplicationMapPath, widgetPath); + return "widgetFile"; } } /// ----------------------------------------------------------------------------- /// - /// Gets a list of allowable file extensions (in addition to the Host's List). + /// Gets the PhysicalBasePath for the widget files. /// /// A String. /// ----------------------------------------------------------------------------- - public override string AllowableFiles + protected override string PhysicalBasePath { get { - return "js"; + string widgetPath = Path.Combine("Resources\\Widgets\\User", this.BasePath); + return Path.Combine(Globals.ApplicationMapPath, widgetPath); } } } diff --git a/DNN Platform/Library/Services/Installer/LegacyUtil.cs b/DNN Platform/Library/Services/Installer/LegacyUtil.cs index 284e1345537..02e5d346115 100644 --- a/DNN Platform/Library/Services/Installer/LegacyUtil.cs +++ b/DNN Platform/Library/Services/Installer/LegacyUtil.cs @@ -42,99 +42,6 @@ public class LegacyUtil private static string KnownSkins = "DNN-Blue, DNN-Gray, MinimalExtropy,"; - private static PackageInfo CreateSkinPackage(SkinPackageInfo skin) - { - // Create a Package - var package = new PackageInfo(new InstallerInfo()); - package.Name = skin.SkinName; - package.FriendlyName = skin.SkinName; - package.Description = Null.NullString; - package.Version = new Version(1, 0, 0); - package.PackageType = skin.SkinType; - package.License = Util.PACKAGE_NoLicense; - - // See if the Skin is using a Namespace (or is a known skin) - ParsePackageName(package); - - return package; - } - - private static void CreateSkinManifest(XmlWriter writer, string skinFolder, string skinType, string tempInstallFolder, string subFolder) - { - string skinName = Path.GetFileNameWithoutExtension(skinFolder); - var skin = new SkinPackageInfo(); - skin.SkinName = skinName; - skin.SkinType = skinType; - - // Create a Package - PackageInfo package = CreateSkinPackage(skin); - - // Create a SkinPackageWriter - var skinWriter = new SkinPackageWriter(skin, package, tempInstallFolder, subFolder); - skinWriter.GetFiles(false); - - // We need to reset the BasePath so it using the correct basePath rather than the Temp InstallFolder - skinWriter.SetBasePath(); - - // Writer package manifest fragment to writer - skinWriter.WriteManifest(writer, true); - } - - private static void ProcessLegacySkin(string skinFolder, string skinType) - { - string skinName = Path.GetFileName(skinFolder); - if (skinName != "_default") - { - var skin = new SkinPackageInfo(); - skin.SkinName = skinName; - skin.SkinType = skinType; - - // Create a Package - PackageInfo package = CreateSkinPackage(skin); - - // Create a SkinPackageWriter - var skinWriter = new SkinPackageWriter(skin, package); - skinWriter.GetFiles(false); - - // Save the manifest - package.Manifest = skinWriter.WriteManifest(true); - - // Save Package - PackageController.Instance.SaveExtensionPackage(package); - - // Update Skin Package with new PackageID - skin.PackageID = package.PackageID; - - // Save Skin Package - skin.SkinPackageID = SkinController.AddSkinPackage(skin); - - foreach (InstallFile skinFile in skinWriter.Files.Values) - { - if (skinFile.Type == InstallFileType.Ascx) - { - if (skinType == "Skin") - { - SkinController.AddSkin(skin.SkinPackageID, Path.Combine("[G]" + SkinController.RootSkin, Path.Combine(skin.SkinName, skinFile.FullName))); - } - else - { - SkinController.AddSkin(skin.SkinPackageID, Path.Combine("[G]" + SkinController.RootContainer, Path.Combine(skin.SkinName, skinFile.FullName))); - } - } - } - } - } - - 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); - if (ownerIndex > 0) - { - package.Owner = package.Name.Substring(0, ownerIndex); - } - } - public static string CreateSkinManifest(string skinFolder, string skinType, string tempInstallFolder) { // Test if there are Skins and Containers folders in TempInstallFolder (ie it is a legacy combi package) @@ -235,6 +142,99 @@ public static void ParsePackageName(PackageInfo package) } } + private static PackageInfo CreateSkinPackage(SkinPackageInfo skin) + { + // Create a Package + var package = new PackageInfo(new InstallerInfo()); + package.Name = skin.SkinName; + package.FriendlyName = skin.SkinName; + package.Description = Null.NullString; + package.Version = new Version(1, 0, 0); + package.PackageType = skin.SkinType; + package.License = Util.PACKAGE_NoLicense; + + // See if the Skin is using a Namespace (or is a known skin) + ParsePackageName(package); + + return package; + } + + private static void CreateSkinManifest(XmlWriter writer, string skinFolder, string skinType, string tempInstallFolder, string subFolder) + { + string skinName = Path.GetFileNameWithoutExtension(skinFolder); + var skin = new SkinPackageInfo(); + skin.SkinName = skinName; + skin.SkinType = skinType; + + // Create a Package + PackageInfo package = CreateSkinPackage(skin); + + // Create a SkinPackageWriter + var skinWriter = new SkinPackageWriter(skin, package, tempInstallFolder, subFolder); + skinWriter.GetFiles(false); + + // We need to reset the BasePath so it using the correct basePath rather than the Temp InstallFolder + skinWriter.SetBasePath(); + + // Writer package manifest fragment to writer + skinWriter.WriteManifest(writer, true); + } + + private static void ProcessLegacySkin(string skinFolder, string skinType) + { + string skinName = Path.GetFileName(skinFolder); + if (skinName != "_default") + { + var skin = new SkinPackageInfo(); + skin.SkinName = skinName; + skin.SkinType = skinType; + + // Create a Package + PackageInfo package = CreateSkinPackage(skin); + + // Create a SkinPackageWriter + var skinWriter = new SkinPackageWriter(skin, package); + skinWriter.GetFiles(false); + + // Save the manifest + package.Manifest = skinWriter.WriteManifest(true); + + // Save Package + PackageController.Instance.SaveExtensionPackage(package); + + // Update Skin Package with new PackageID + skin.PackageID = package.PackageID; + + // Save Skin Package + skin.SkinPackageID = SkinController.AddSkinPackage(skin); + + foreach (InstallFile skinFile in skinWriter.Files.Values) + { + if (skinFile.Type == InstallFileType.Ascx) + { + if (skinType == "Skin") + { + SkinController.AddSkin(skin.SkinPackageID, Path.Combine("[G]" + SkinController.RootSkin, Path.Combine(skin.SkinName, skinFile.FullName))); + } + else + { + SkinController.AddSkin(skin.SkinPackageID, Path.Combine("[G]" + SkinController.RootContainer, Path.Combine(skin.SkinName, skinFile.FullName))); + } + } + } + } + } + + 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); + if (ownerIndex > 0) + { + package.Owner = package.Name.Substring(0, ownerIndex); + } + } + /// /// Process legacy language package (that is based on manifest xml file). /// @@ -273,15 +273,15 @@ public static void ProcessLegacyLanguages() if (language.Code != Localization.SystemLocale) { // Create a Package - var package = new PackageInfo(new InstallerInfo()) - { - Name = language.Text, - FriendlyName = language.Text, - Description = Null.NullString, - Version = new Version(1, 0, 0), - PackageType = "CoreLanguagePack", - License = Util.PACKAGE_NoLicense, - }; + var package = new PackageInfo(new InstallerInfo()) + { + Name = language.Text, + FriendlyName = language.Text, + Description = Null.NullString, + Version = new Version(1, 0, 0), + PackageType = "CoreLanguagePack", + License = Util.PACKAGE_NoLicense, + }; // Create a LanguagePackWriter var packageWriter = new LanguagePackWriter(language, package); @@ -292,12 +292,12 @@ public static void ProcessLegacyLanguages() // Save Package PackageController.Instance.SaveExtensionPackage(package); - var languagePack = new LanguagePackInfo - { - LanguageID = language.LanguageId, - PackageID = package.PackageID, - DependentPackageID = -2, - }; + var languagePack = new LanguagePackInfo + { + LanguageID = language.LanguageId, + PackageID = package.PackageID, + DependentPackageID = -2, + }; LanguagePackController.SaveLanguagePack(languagePack); } } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs index c90a214ad64..3382c575aff 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs @@ -33,6 +33,134 @@ public class PackageController : ServiceLocator d.PackageName.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && d.Version <= package.Version); + if (dependencies.Count > 0) + { + // There is at least one package dependent on this package. + foreach (var dependency in dependencies) + { + var dep = dependency; + + // Check if there is an alternative package + var packages = Instance.GetExtensionPackages( + package.PortalID, + p => p.Name.Equals(dep.PackageName, StringComparison.OrdinalIgnoreCase) + && p.Version >= dep.Version + && p.PackageID != package.PackageID); + if (packages.Count == 0) + { + bCanDelete = false; + } + } + } + + if (bCanDelete) + { + switch (package.PackageType) + { + case "Skin": + case "Container": + // Need to get path of skin being deleted so we can call the public CanDeleteSkin function in the SkinController + string strRootSkin = package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase) ? SkinController.RootSkin : SkinController.RootContainer; + SkinPackageInfo _SkinPackageInfo = SkinController.GetSkinByPackageID(package.PackageID); + string strFolderPath = Path.Combine(_SkinPackageInfo.PortalID == Null.NullInteger ? Path.Combine(Globals.HostMapPath, strRootSkin) : Path.Combine(portalSettings.HomeSystemDirectoryMapPath, strRootSkin), _SkinPackageInfo.SkinName); + + bCanDelete = SkinController.CanDeleteSkin(strFolderPath, portalSettings.HomeSystemDirectoryMapPath); + if (_SkinPackageInfo.PortalID != Null.NullInteger) + { + // To be compliant with all versions + strFolderPath = Path.Combine(Path.Combine(portalSettings.HomeDirectoryMapPath, strRootSkin), _SkinPackageInfo.SkinName); + bCanDelete = bCanDelete && SkinController.CanDeleteSkin(strFolderPath, portalSettings.HomeDirectoryMapPath); + } + + break; + case "Provider": + // Check if the provider is the default provider + XmlDocument configDoc = Config.Load(); + string providerName = package.Name; + if (providerName.IndexOf(".", StringComparison.Ordinal) > Null.NullInteger) + { + providerName = providerName.Substring(providerName.IndexOf(".", StringComparison.Ordinal) + 1); + } + + switch (providerName) + { + case "SchedulingProvider": + providerName = "DNNScheduler"; + break; + case "SearchIndexProvider": + providerName = "ModuleIndexProvider"; + break; + case "SearchProvider": + providerName = "SearchDataStoreProvider"; + break; + } + + XPathNavigator providerNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/dotnetnuke/*[@defaultProvider='" + providerName + "']"); + bCanDelete = providerNavigator == null; + break; + } + } + + return bCanDelete; + } + + public static IDictionary GetModulePackagesInUse(int portalID, bool forHost) + { + return CBO.FillDictionary("PackageID", provider.GetModulePackagesInUse(portalID, forHost)); + } + + public void DeleteExtensionPackage(PackageInfo package) + { + switch (package.PackageType) + { + case "Auth_System": + AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); + if (authSystem != null) + { + AuthenticationController.DeleteAuthentication(authSystem); + } + + break; + case "CoreLanguagePack": + LanguagePackInfo languagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); + if (languagePack != null) + { + LanguagePackController.DeleteLanguagePack(languagePack); + } + + break; + case "Module": + var controller = new DesktopModuleController(); + DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); + if (desktopModule != null) + { + controller.DeleteDesktopModule(desktopModule); + } + + break; + case "SkinObject": + SkinControlInfo skinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); + if (skinControl != null) + { + SkinControlController.DeleteSkinControl(skinControl); + } + + break; + } + + DeletePackageInternal(package); + } + + public PackageInfo GetExtensionPackage(int portalId, Func predicate) + { + return this.GetExtensionPackage(portalId, predicate, false); + } + protected override Func GetFactory() { return () => new PackageController(); @@ -152,53 +280,6 @@ private static void SavePackageDependency(PackageDependencyInfo dependency) ClearDependenciesCache(); } - - public void DeleteExtensionPackage(PackageInfo package) - { - switch (package.PackageType) - { - case "Auth_System": - AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); - if (authSystem != null) - { - AuthenticationController.DeleteAuthentication(authSystem); - } - - break; - case "CoreLanguagePack": - LanguagePackInfo languagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); - if (languagePack != null) - { - LanguagePackController.DeleteLanguagePack(languagePack); - } - - break; - case "Module": - var controller = new DesktopModuleController(); - DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); - if (desktopModule != null) - { - controller.DeleteDesktopModule(desktopModule); - } - - break; - case "SkinObject": - SkinControlInfo skinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); - if (skinControl != null) - { - SkinControlController.DeleteSkinControl(skinControl); - } - - break; - } - - DeletePackageInternal(package); - } - - public PackageInfo GetExtensionPackage(int portalId, Func predicate) - { - return this.GetExtensionPackage(portalId, predicate, false); - } public PackageInfo GetExtensionPackage(int portalId, Func predicate, bool useCopy) { @@ -261,87 +342,6 @@ public IList GetPackageDependencies(Func d.PackageName.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && d.Version <= package.Version); - if (dependencies.Count > 0) - { - // There is at least one package dependent on this package. - foreach (var dependency in dependencies) - { - var dep = dependency; - - // Check if there is an alternative package - var packages = Instance.GetExtensionPackages( - package.PortalID, - p => p.Name.Equals(dep.PackageName, StringComparison.OrdinalIgnoreCase) - && p.Version >= dep.Version - && p.PackageID != package.PackageID); - if (packages.Count == 0) - { - bCanDelete = false; - } - } - } - - if (bCanDelete) - { - switch (package.PackageType) - { - case "Skin": - case "Container": - // Need to get path of skin being deleted so we can call the public CanDeleteSkin function in the SkinController - string strRootSkin = package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase) ? SkinController.RootSkin : SkinController.RootContainer; - SkinPackageInfo _SkinPackageInfo = SkinController.GetSkinByPackageID(package.PackageID); - string strFolderPath = Path.Combine(_SkinPackageInfo.PortalID == Null.NullInteger ? Path.Combine(Globals.HostMapPath, strRootSkin) : Path.Combine(portalSettings.HomeSystemDirectoryMapPath, strRootSkin), _SkinPackageInfo.SkinName); - - bCanDelete = SkinController.CanDeleteSkin(strFolderPath, portalSettings.HomeSystemDirectoryMapPath); - if (_SkinPackageInfo.PortalID != Null.NullInteger) - { - // To be compliant with all versions - strFolderPath = Path.Combine(Path.Combine(portalSettings.HomeDirectoryMapPath, strRootSkin), _SkinPackageInfo.SkinName); - bCanDelete = bCanDelete && SkinController.CanDeleteSkin(strFolderPath, portalSettings.HomeDirectoryMapPath); - } - - break; - case "Provider": - // Check if the provider is the default provider - XmlDocument configDoc = Config.Load(); - string providerName = package.Name; - if (providerName.IndexOf(".", StringComparison.Ordinal) > Null.NullInteger) - { - providerName = providerName.Substring(providerName.IndexOf(".", StringComparison.Ordinal) + 1); - } - - switch (providerName) - { - case "SchedulingProvider": - providerName = "DNNScheduler"; - break; - case "SearchIndexProvider": - providerName = "ModuleIndexProvider"; - break; - case "SearchProvider": - providerName = "SearchDataStoreProvider"; - break; - } - - XPathNavigator providerNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/dotnetnuke/*[@defaultProvider='" + providerName + "']"); - bCanDelete = providerNavigator == null; - break; - } - } - - return bCanDelete; - } - - public static IDictionary GetModulePackagesInUse(int portalID, bool forHost) - { - return CBO.FillDictionary("PackageID", provider.GetModulePackagesInUse(portalID, forHost)); - } public static void ParsePackage(string file, string installPath, Dictionary packages, List invalidPackages) { @@ -501,6 +501,19 @@ public static void ParsePackage(string file, string installPath, Dictionary (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); - - protected virtual string EditorID - { - get - { - return Null.NullString; - } - } - - protected bool IsSuperTab - { - get - { - return this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab; - } - } - - protected PackageInfo Package - { - get - { - if (this._Package == null) - { - this._Package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, (p) => p.PackageID == this.PackageID); - } - - return this._Package; - } - } /// ----------------------------------------------------------------------------- /// @@ -88,6 +57,37 @@ public bool IsWizard } } + protected string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); + + protected virtual string EditorID + { + get + { + return Null.NullString; + } + } + + protected bool IsSuperTab + { + get + { + return this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab; + } + } + + protected PackageInfo Package + { + get + { + if (this._Package == null) + { + this._Package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, (p) => p.PackageID == this.PackageID); + } + + return this._Package; + } + } + /// ----------------------------------------------------------------------------- /// /// Used to Initialize the Control. diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs b/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs index 16634c31f08..039477efce7 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs @@ -295,30 +295,30 @@ public void AttachInstallerInfo(InstallerInfo installer) /// public PackageInfo Clone() { - return new PackageInfo - { - PackageID = this.PackageID, - PortalID = this.PortalID, - PackageType = this.PackageType, - InstallerInfo = this.InstallerInfo, - Name = this.Name, - FriendlyName = this.FriendlyName, - Manifest = this.Manifest, - Email = this.Email, - Description = this.Description, - FolderName = this.FolderName, - FileName = this.FileName, - IconFile = this.IconFile, - IsSystemPackage = this.IsSystemPackage, - IsValid = this.IsValid, - Organization = this.Organization, - Owner = this.Owner, - License = this.License, - ReleaseNotes = this.ReleaseNotes, - Url = this.Url, - Version = this.Version, - InstalledVersion = this.InstalledVersion, - }; + return new PackageInfo + { + PackageID = this.PackageID, + PortalID = this.PortalID, + PackageType = this.PackageType, + InstallerInfo = this.InstallerInfo, + Name = this.Name, + FriendlyName = this.FriendlyName, + Manifest = this.Manifest, + Email = this.Email, + Description = this.Description, + FolderName = this.FolderName, + FileName = this.FileName, + IconFile = this.IconFile, + IsSystemPackage = this.IsSystemPackage, + IsValid = this.IsValid, + Organization = this.Organization, + Owner = this.Owner, + License = this.License, + ReleaseNotes = this.ReleaseNotes, + Url = this.Url, + Version = this.Version, + InstalledVersion = this.InstalledVersion, + }; } } } diff --git a/DNN Platform/Library/Services/Installer/Util.cs b/DNN Platform/Library/Services/Installer/Util.cs index 1c9b8328f95..94cae3642ae 100644 --- a/DNN Platform/Library/Services/Installer/Util.cs +++ b/DNN Platform/Library/Services/Installer/Util.cs @@ -33,6 +33,7 @@ public class Util { // ReSharper disable InconsistentNaming public const string DEFAULT_MANIFESTEXT = ".manifest"; + public const string BackupInstallPackageFolder = "App_Data/ExtensionPackages/"; public static string ASSEMBLY_Added = GetLocalizedString("ASSEMBLY_Added"); public static string ASSEMBLY_AddedBindingRedirect = GetLocalizedString("ASSEMBLY_AddedBindingRedirect"); public static string ASSEMBLY_RemovedBindingRedirect = GetLocalizedString("ASSEMBLY_RemovedBindingRedirect"); @@ -170,7 +171,54 @@ public class Util public static string WRITER_SavedFile = GetLocalizedString("WRITER_SavedFile"); public static string WRITER_SaveFileError = GetLocalizedString("WRITER_SaveFileError"); public static string REGEX_Version = "\\d{2}.\\d{2}.\\d{2}"; - public const string BackupInstallPackageFolder = "App_Data/ExtensionPackages/"; + + /// ----------------------------------------------------------------------------- + /// + /// The BackupFile method backs up a file to the backup folder. + /// + /// The file to backup. + /// The basePath to the file. + /// A Logger to log the result. + public static void BackupFile(InstallFile installFile, string basePath, Logger log) + { + string fullFileName = Path.Combine(basePath, installFile.FullName); + string backupFileName = Path.Combine(installFile.BackupPath, installFile.Name + ".config"); + + // create the backup folder if neccessary + if (!Directory.Exists(installFile.BackupPath)) + { + Directory.CreateDirectory(installFile.BackupPath); + } + + // Copy file to backup location + RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.CopyFile(fullFileName, backupFileName), "Backup file " + fullFileName); + log.AddInfo(string.Format(FILE_CreateBackup, installFile.FullName)); + } + + /// ----------------------------------------------------------------------------- + /// + /// The CopyFile method copies a file from the temporary extract location. + /// + /// The file to copy. + /// The basePath to the file. + /// A Logger to log the result. + 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 + if (!Directory.Exists(filePath)) + { + log.AddInfo(string.Format(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)); + } // ReSharper restore InconsistentNaming @@ -225,54 +273,6 @@ private static string ValidateNode(string propValue, bool isRequired, Logger log return propValue; } - /// ----------------------------------------------------------------------------- - /// - /// The BackupFile method backs up a file to the backup folder. - /// - /// The file to backup. - /// The basePath to the file. - /// A Logger to log the result. - public static void BackupFile(InstallFile installFile, string basePath, Logger log) - { - string fullFileName = Path.Combine(basePath, installFile.FullName); - string backupFileName = Path.Combine(installFile.BackupPath, installFile.Name + ".config"); - - // create the backup folder if neccessary - if (!Directory.Exists(installFile.BackupPath)) - { - Directory.CreateDirectory(installFile.BackupPath); - } - - // Copy file to backup location - RetryableAction.RetryEverySecondFor30Seconds(() => FileSystemUtils.CopyFile(fullFileName, backupFileName), "Backup file " + fullFileName); - log.AddInfo(string.Format(FILE_CreateBackup, installFile.FullName)); - } - - /// ----------------------------------------------------------------------------- - /// - /// The CopyFile method copies a file from the temporary extract location. - /// - /// The file to copy. - /// The basePath to the file. - /// A Logger to log the result. - 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 - if (!Directory.Exists(filePath)) - { - log.AddInfo(string.Format(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)); - } - /// ----------------------------------------------------------------------------- /// /// The DeleteFile method deletes a file. diff --git a/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs index b0919baab44..19de549d86d 100644 --- a/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs @@ -40,6 +40,12 @@ public AuthenticationPackageWriter(AuthenticationInfo authSystem, PackageInfo pa /// ----------------------------------------------------------------------------- public AuthenticationInfo AuthSystem { get; set; } + protected override void WriteManifestComponent(XmlWriter writer) + { + // Write Authentication Component + this.WriteAuthenticationComponent(writer); + } + private void Initialize() { this.BasePath = Path.Combine("DesktopModules\\AuthenticationServices", this.AuthSystem.AuthenticationType); @@ -67,11 +73,5 @@ private void WriteAuthenticationComponent(XmlWriter writer) // End component Element writer.WriteEndElement(); } - - protected override void WriteManifestComponent(XmlWriter writer) - { - // Write Authentication Component - this.WriteAuthenticationComponent(writer); - } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs index e858e4a8dbb..8efe1c39906 100644 --- a/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs @@ -41,6 +41,32 @@ public FileComponentWriter(string basePath, Dictionary file this._Package = package; } + public int InstallOrder + { + get + { + return this._InstallOrder; + } + + set + { + this._InstallOrder = value; + } + } + + public int UnInstallOrder + { + get + { + return this._UnInstallOrder; + } + + set + { + this._UnInstallOrder = value; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("files"). @@ -111,30 +137,43 @@ protected virtual PackageInfo Package } } - public int InstallOrder + public virtual void WriteManifest(XmlWriter writer) { - get + // Start component Element + writer.WriteStartElement("component"); + writer.WriteAttributeString("type", this.ComponentType); + if (this.InstallOrder > Null.NullInteger) { - return this._InstallOrder; + writer.WriteAttributeString("installOrder", this.InstallOrder.ToString()); } - set + if (this.UnInstallOrder > Null.NullInteger) { - this._InstallOrder = value; + writer.WriteAttributeString("unInstallOrder", this.UnInstallOrder.ToString()); } - } - public int UnInstallOrder - { - get + // Start files element + writer.WriteStartElement(this.CollectionNodeName); + + // Write custom manifest items + this.WriteCustomManifest(writer); + + // Write basePath Element + if (!string.IsNullOrEmpty(this._BasePath)) { - return this._UnInstallOrder; + writer.WriteElementString("basePath", this._BasePath); } - set + foreach (InstallFile file in this._Files.Values) { - this._UnInstallOrder = value; + this.WriteFileElement(writer, file); } + + // End files Element + writer.WriteEndElement(); + + // End component Element + writer.WriteEndElement(); } /// ----------------------------------------------------------------------------- @@ -182,44 +221,5 @@ protected virtual void WriteFileElement(XmlWriter writer, InstallFile file) // Close file Element writer.WriteEndElement(); } - - public virtual void WriteManifest(XmlWriter writer) - { - // Start component Element - writer.WriteStartElement("component"); - writer.WriteAttributeString("type", this.ComponentType); - if (this.InstallOrder > Null.NullInteger) - { - writer.WriteAttributeString("installOrder", this.InstallOrder.ToString()); - } - - if (this.UnInstallOrder > Null.NullInteger) - { - writer.WriteAttributeString("unInstallOrder", this.UnInstallOrder.ToString()); - } - - // Start files element - writer.WriteStartElement(this.CollectionNodeName); - - // Write custom manifest items - this.WriteCustomManifest(writer); - - // Write basePath Element - if (!string.IsNullOrEmpty(this._BasePath)) - { - writer.WriteElementString("basePath", this._BasePath); - } - - foreach (InstallFile file in this._Files.Values) - { - this.WriteFileElement(writer, file); - } - - // End files Element - writer.WriteEndElement(); - - // End component Element - writer.WriteEndElement(); - } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs b/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs index bfc5c7ea428..db1aa2f09fa 100644 --- a/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs @@ -135,6 +135,47 @@ public LanguagePackInfo LanguagePack 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.ToLowerInvariant() == "app_localresources" || folder.Name.ToLowerInvariant() == "app_globalresources" || folder.Name.ToLowerInvariant() == "_default") + { + // 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.ToLowerInvariant().Contains(this.Language.Code.ToLowerInvariant()) || (this.Language.Code.ToLowerInvariant() == "en-us" && !file.Name.Contains("-"))) + { + this.AddFile(Path.Combine(filePath, file.Name)); + } + } + } + } private void ReadLegacyManifest(XPathNavigator manifestNav) { @@ -501,47 +542,6 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) } } } - - 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.ToLowerInvariant() == "app_localresources" || folder.Name.ToLowerInvariant() == "app_globalresources" || folder.Name.ToLowerInvariant() == "_default") - { - // 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.ToLowerInvariant().Contains(this.Language.Code.ToLowerInvariant()) || (this.Language.Code.ToLowerInvariant() == "en-us" && !file.Name.Contains("-"))) - { - this.AddFile(Path.Combine(filePath, file.Name)); - } - } - } - } protected override void WriteFilesToManifest(XmlWriter writer) { diff --git a/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs index e1beb03c384..0cc9226e9d3 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs @@ -82,6 +82,14 @@ public ModulePackageWriter(DesktopModuleInfo desktopModule, PackageInfo package) this.Initialize(desktopModule.FolderName); } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the associated Desktop Module. + /// + /// A DesktopModuleInfo object. + /// ----------------------------------------------------------------------------- + public DesktopModuleInfo DesktopModule { get; set; } + protected override Dictionary Dependencies { get @@ -101,20 +109,11 @@ protected override Dictionary Dependencies } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the associated Desktop Module. - /// - /// A DesktopModuleInfo object. - /// ----------------------------------------------------------------------------- - public DesktopModuleInfo DesktopModule { get; set; } - - private void Initialize(string folder) + protected override void WriteManifestComponent(XmlWriter writer) { - this.BasePath = Path.Combine("DesktopModules", folder).Replace("/", "\\"); - this.AppCodePath = Path.Combine("App_Code", folder).Replace("/", "\\"); - this.AssemblyPath = "bin"; - } + // Write Module Component + this.WriteModuleComponent(writer); + } private static void ProcessControls(XPathNavigator controlNav, string moduleFolder, ModuleDefinitionInfo definition) { @@ -173,6 +172,13 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold definition.ModuleControls[moduleControl.ControlKey] = moduleControl; } + + private void Initialize(string folder) + { + this.BasePath = Path.Combine("DesktopModules", folder).Replace("/", "\\"); + this.AppCodePath = Path.Combine("App_Code", folder).Replace("/", "\\"); + this.AssemblyPath = "bin"; + } private void ProcessModuleFiles(string folder, string basePath) { @@ -386,11 +392,5 @@ private void WriteModuleComponent(XmlWriter writer) // End component Element writer.WriteEndElement(); } - - protected override void WriteManifestComponent(XmlWriter writer) - { - // Write Module Component - this.WriteModuleComponent(writer); - } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs b/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs index 4a0b78bfe7d..ad70e28e35e 100644 --- a/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs +++ b/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs @@ -26,6 +26,8 @@ namespace DotNetNuke.Services.Installer.Writers /// ----------------------------------------------------------------------------- public class PackageWriterBase { + private static readonly Regex FileVersionMatchRegex = new Regex(Util.REGEX_Version, RegexOptions.Compiled); + private readonly Dictionary _AppCodeFiles = new Dictionary(); private readonly Dictionary _Assemblies = new Dictionary(); private readonly SortedList _CleanUpFiles = new SortedList(); @@ -36,25 +38,15 @@ public class PackageWriterBase private string _BasePath = Null.NullString; private PackageInfo _Package; - private static readonly Regex FileVersionMatchRegex = new Regex(Util.REGEX_Version, RegexOptions.Compiled); - - protected PackageWriterBase() - { - } - public PackageWriterBase(PackageInfo package) { this._Package = package; this._Package.AttachInstallerInfo(new InstallerInfo()); } - protected virtual Dictionary Dependencies + protected PackageWriterBase() { - get - { - return new Dictionary(); - } - } + } /// ----------------------------------------------------------------------------- /// @@ -68,15 +60,23 @@ public Dictionary AppCodeFiles { return this._AppCodeFiles; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Path for the Package's app code files. - /// - /// A String. - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Path for the Package's app code files. + /// + /// A String. + /// ----------------------------------------------------------------------------- public string AppCodePath { get; set; } + + protected virtual Dictionary Dependencies + { + get + { + return new Dictionary(); + } + } /// ----------------------------------------------------------------------------- /// @@ -90,14 +90,14 @@ public Dictionary Assemblies { return this._Assemblies; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Path for the Package's assemblies. - /// - /// A String. - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Path for the Package's assemblies. + /// + /// A String. + /// ----------------------------------------------------------------------------- public string AssemblyPath { get; set; } /// ----------------------------------------------------------------------------- @@ -145,14 +145,14 @@ public Dictionary Files { return this._Files; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether gets and sets whether a project file is found in the folder. - /// - /// A String. - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether a project file is found in the folder. + /// + /// A String. + /// ----------------------------------------------------------------------------- public bool HasProjectFile { get; set; } /// ----------------------------------------------------------------------------- @@ -253,6 +253,72 @@ public List Versions return this._Versions; } } + + public static void WriteManifestEndElement(XmlWriter writer) + { + // Close packages Element + writer.WriteEndElement(); + + // Close root Element + writer.WriteEndElement(); + } + + public static void WriteManifestStartElement(XmlWriter writer) + { + // Start the new Root Element + writer.WriteStartElement("dotnetnuke"); + writer.WriteAttributeString("type", "Package"); + writer.WriteAttributeString("version", "5.0"); + + // Start packages Element + writer.WriteStartElement("packages"); + } + + public virtual void AddFile(InstallFile file) + { + switch (file.Type) + { + case InstallFileType.AppCode: + this._AppCodeFiles[file.FullName.ToLowerInvariant()] = file; + break; + case InstallFileType.Assembly: + this._Assemblies[file.FullName.ToLowerInvariant()] = file; + break; + case InstallFileType.CleanUp: + this._CleanUpFiles[file.FullName.ToLowerInvariant()] = file; + break; + case InstallFileType.Script: + this._Scripts[file.FullName.ToLowerInvariant()] = file; + break; + default: + this._Files[file.FullName.ToLowerInvariant()] = file; + break; + } + + if ((file.Type == InstallFileType.CleanUp || file.Type == InstallFileType.Script) && FileVersionMatchRegex.IsMatch(file.Name)) + { + string version = Path.GetFileNameWithoutExtension(file.Name); + if (!this._Versions.Contains(version)) + { + this._Versions.Add(version); + } + } + } + + public void AddResourceFile(InstallFile file) + { + this._Resources[file.FullName.ToLowerInvariant()] = file; + } + + protected virtual void AddFile(string fileName) + { + this.AddFile(new InstallFile(fileName, this.Package.InstallerInfo)); + } + + protected virtual void AddFile(string fileName, string sourceFileName) + { + this.AddFile(new InstallFile(fileName, sourceFileName, this.Package.InstallerInfo)); + } private void AddFilesToZip(ZipOutputStream stream, IDictionary files, string basePath) { @@ -398,16 +464,6 @@ private void WritePackageStartElement(XmlWriter writer) // Write components Element writer.WriteStartElement("components"); } - - protected virtual void AddFile(string fileName) - { - this.AddFile(new InstallFile(fileName, this.Package.InstallerInfo)); - } - - protected virtual void AddFile(string fileName, string sourceFileName) - { - this.AddFile(new InstallFile(fileName, sourceFileName, this.Package.InstallerInfo)); - } protected virtual void ConvertLegacyManifest(XPathNavigator legacyManifest, XmlWriter writer) { @@ -563,42 +619,6 @@ protected virtual void WriteFilesToManifest(XmlWriter writer) protected virtual void WriteManifestComponent(XmlWriter writer) { } - - public virtual void AddFile(InstallFile file) - { - switch (file.Type) - { - case InstallFileType.AppCode: - this._AppCodeFiles[file.FullName.ToLowerInvariant()] = file; - break; - case InstallFileType.Assembly: - this._Assemblies[file.FullName.ToLowerInvariant()] = file; - break; - case InstallFileType.CleanUp: - this._CleanUpFiles[file.FullName.ToLowerInvariant()] = file; - break; - case InstallFileType.Script: - this._Scripts[file.FullName.ToLowerInvariant()] = file; - break; - default: - this._Files[file.FullName.ToLowerInvariant()] = file; - break; - } - - if ((file.Type == InstallFileType.CleanUp || file.Type == InstallFileType.Script) && FileVersionMatchRegex.IsMatch(file.Name)) - { - string version = Path.GetFileNameWithoutExtension(file.Name); - if (!this._Versions.Contains(version)) - { - this._Versions.Add(version); - } - } - } - - public void AddResourceFile(InstallFile file) - { - this._Resources[file.FullName.ToLowerInvariant()] = file; - } public void CreatePackage(string archiveName, string manifestName, string manifest, bool createManifest) { @@ -742,25 +762,5 @@ public void WriteManifest(XmlWriter writer, bool packageFragment) this.Log.EndJob(Util.WRITER_CreatedManifest); } - - public static void WriteManifestEndElement(XmlWriter writer) - { - // Close packages Element - writer.WriteEndElement(); - - // Close root Element - writer.WriteEndElement(); - } - - public static void WriteManifestStartElement(XmlWriter writer) - { - // Start the new Root Element - writer.WriteStartElement("dotnetnuke"); - writer.WriteAttributeString("type", "Package"); - writer.WriteAttributeString("version", "5.0"); - - // Start packages Element - writer.WriteStartElement("packages"); - } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs index b0c73c09313..5dc9ca51bea 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs @@ -63,6 +63,19 @@ public SkinControlPackageWriter(XPathNavigator manifestNav, InstallerInfo instal /// ----------------------------------------------------------------------------- public SkinControlInfo SkinControl { get; set; } + protected override void WriteManifestComponent(XmlWriter writer) + { + // Start component Element + writer.WriteStartElement("component"); + writer.WriteAttributeString("type", "SkinObject"); + + // Write SkinControl Manifest + CBO.SerializeObject(this.SkinControl, writer); + + // End component Element + writer.WriteEndElement(); + } + private void ReadLegacyManifest(XPathNavigator legacyManifest, bool processModule) { XPathNavigator folderNav = legacyManifest.SelectSingleNode("folders/folder"); @@ -100,18 +113,5 @@ private void ReadLegacyManifest(XPathNavigator legacyManifest, bool processModul this.AddFile(Util.ReadElement(folderNav, "resourcefile")); } } - - protected override void WriteManifestComponent(XmlWriter writer) - { - // Start component Element - writer.WriteStartElement("component"); - writer.WriteAttributeString("type", "SkinObject"); - - // Write SkinControl Manifest - CBO.SerializeObject(this.SkinControl, writer); - - // End component Element - writer.WriteEndElement(); - } } } diff --git a/DNN Platform/Library/Services/Installer/XmlMerge.cs b/DNN Platform/Library/Services/Installer/XmlMerge.cs index 40a321f6257..d7f2c19d249 100644 --- a/DNN Platform/Library/Services/Installer/XmlMerge.cs +++ b/DNN Platform/Library/Services/Installer/XmlMerge.cs @@ -150,6 +150,46 @@ public IDictionary PendingDocuments } } + /// ----------------------------------------------------------------------------- + /// + /// The UpdateConfig method processes the source file and updates the Target + /// Config Xml Document. + /// + /// An Xml Document represent the Target Xml File. + /// ----------------------------------------------------------------------------- + public void UpdateConfig(XmlDocument target) + { + var changedAnyNodes = false; + this.TargetConfig = target; + if (this.TargetConfig != null) + { + changedAnyNodes = this.ProcessNodes(this.SourceConfig.SelectNodes("/configuration/nodes/node"), false); + } + + this.ConfigUpdateChangedNodes = changedAnyNodes; + } + + /// ----------------------------------------------------------------------------- + /// + /// The UpdateConfig method processes the source file and updates the Target + /// Config file. + /// + /// An Xml Document represent the Target Xml File. + /// The fileName for the Target Xml File - relative to the webroot. + /// ----------------------------------------------------------------------------- + public void UpdateConfig(XmlDocument target, string fileName) + { + var changedAnyNodes = false; + this.TargetFileName = fileName; + this.TargetConfig = target; + if (this.TargetConfig != null) + { + changedAnyNodes = this.ProcessNodes(this.SourceConfig.SelectNodes("/configuration/nodes/node"), true); + } + + this.ConfigUpdateChangedNodes = changedAnyNodes; + } + private bool AddNode(XmlNode rootNode, XmlNode actionNode) { var changedNode = false; @@ -572,46 +612,6 @@ private void RemoveCommentNodes(XmlNode node) commentNodes.ForEach(n => { node.RemoveChild(n); }); } } - - /// ----------------------------------------------------------------------------- - /// - /// The UpdateConfig method processes the source file and updates the Target - /// Config Xml Document. - /// - /// An Xml Document represent the Target Xml File. - /// ----------------------------------------------------------------------------- - public void UpdateConfig(XmlDocument target) - { - var changedAnyNodes = false; - this.TargetConfig = target; - if (this.TargetConfig != null) - { - changedAnyNodes = this.ProcessNodes(this.SourceConfig.SelectNodes("/configuration/nodes/node"), false); - } - - this.ConfigUpdateChangedNodes = changedAnyNodes; - } - - /// ----------------------------------------------------------------------------- - /// - /// The UpdateConfig method processes the source file and updates the Target - /// Config file. - /// - /// An Xml Document represent the Target Xml File. - /// The fileName for the Target Xml File - relative to the webroot. - /// ----------------------------------------------------------------------------- - public void UpdateConfig(XmlDocument target, string fileName) - { - var changedAnyNodes = false; - this.TargetFileName = fileName; - this.TargetConfig = target; - if (this.TargetConfig != null) - { - changedAnyNodes = this.ProcessNodes(this.SourceConfig.SelectNodes("/configuration/nodes/node"), true); - } - - this.ConfigUpdateChangedNodes = changedAnyNodes; - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Journal/CommentInfo.cs b/DNN Platform/Library/Services/Journal/CommentInfo.cs index 560ef8eb6c4..97467a4660b 100644 --- a/DNN Platform/Library/Services/Journal/CommentInfo.cs +++ b/DNN Platform/Library/Services/Journal/CommentInfo.cs @@ -45,6 +45,14 @@ public int KeyID } } + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + public void Fill(System.Data.IDataReader dr) { this.CommentId = Null.SetNullInteger(dr["CommentId"]); @@ -62,14 +70,6 @@ public void Fill(System.Data.IDataReader dr) this.DisplayName = Null.SetNullString(dr["DisplayName"]); } - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { throw new NotImplementedException(); diff --git a/DNN Platform/Library/Services/Journal/Content.cs b/DNN Platform/Library/Services/Journal/Content.cs index 68643cbc9ee..a01489a1900 100644 --- a/DNN Platform/Library/Services/Journal/Content.cs +++ b/DNN Platform/Library/Services/Journal/Content.cs @@ -12,6 +12,29 @@ namespace DotNetNuke.Services.Journal public class Content { + /// + /// This is used to determine the ContentTypeID (part of the Core API) based on this module's content type. If the content type doesn't exist yet for the module, it is created. + /// + /// The primary key value (ContentTypeID) from the core API's Content Types table. + internal static int GetContentTypeID(string ContentTypeName) + { + var typeController = new ContentTypeController(); + var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t; + int contentTypeId; + + if (colContentTypes.Count() > 0) + { + var contentType = colContentTypes.Single(); + contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; + } + else + { + contentTypeId = CreateContentType(ContentTypeName); + } + + return contentTypeId; + } + /// /// This should only run after the Post exists in the data store. /// @@ -108,29 +131,6 @@ internal void DeleteContentItem(int contentItemID) // cntTerms.RemoveQuestionTerms(objContent); Util.GetContentController().DeleteContentItem(objContent); } - - /// - /// This is used to determine the ContentTypeID (part of the Core API) based on this module's content type. If the content type doesn't exist yet for the module, it is created. - /// - /// The primary key value (ContentTypeID) from the core API's Content Types table. - internal static int GetContentTypeID(string ContentTypeName) - { - var typeController = new ContentTypeController(); - var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t; - int contentTypeId; - - if (colContentTypes.Count() > 0) - { - var contentType = colContentTypes.Single(); - contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; - } - else - { - contentTypeId = CreateContentType(ContentTypeName); - } - - return contentTypeId; - } /// /// Creates a Content Type (for taxonomy) in the data store. diff --git a/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs b/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs index 1e8e1733041..6a8e059cf3c 100644 --- a/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs +++ b/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs @@ -103,8 +103,8 @@ public int Journal_Save(int portalId, int currentUserId, int profileId, int grou { journalId = this._provider.ExecuteScalar("Journal_Save", portalId, journalId, journalTypeId, currentUserId, profileId, groupId, title, summary, itemData, xml, objectKey, accessKey, securitySet, false, false); - return journalId; - } + return journalId; + } public int Journal_Save(int portalId, int currentUserId, int profileId, int groupId, int journalId, int journalTypeId, string title, string summary, string body, string itemData, string xml, string objectKey, Guid accessKey, string securitySet, bool commentsDisabled, bool commentsHidden) diff --git a/DNN Platform/Library/Services/Journal/ItemData.cs b/DNN Platform/Library/Services/Journal/ItemData.cs index 6f0b15f38ac..3c85cd542ae 100644 --- a/DNN Platform/Library/Services/Journal/ItemData.cs +++ b/DNN Platform/Library/Services/Journal/ItemData.cs @@ -11,53 +11,53 @@ namespace DotNetNuke.Services.Journal using System.Text; using System.Xml; - using DotNetNuke.Services.Tokens; - - public class ItemData : IPropertyAccess - { - public string Url { get; set; } - - public string Title { get; set; } - - public string Description { get; set; } - - public string ImageUrl { get; set; } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - - 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 "url": - return PropertyAccess.FormatString(this.Url, format); - case "title": - return PropertyAccess.FormatString(this.Title, format); - case "description": - return PropertyAccess.FormatString(this.Description, format); - case "imageurl": - return PropertyAccess.FormatString(this.ImageUrl, format); - } - - propertyNotFound = true; - return string.Empty; - } - } + using DotNetNuke.Services.Tokens; + + public class ItemData : IPropertyAccess + { + public string Url { get; set; } + + public string Title { get; set; } + + public string Description { get; set; } + + public string ImageUrl { get; set; } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + + 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 "url": + return PropertyAccess.FormatString(this.Url, format); + case "title": + return PropertyAccess.FormatString(this.Title, format); + case "description": + return PropertyAccess.FormatString(this.Description, format); + case "imageurl": + return PropertyAccess.FormatString(this.ImageUrl, format); + } + + propertyNotFound = true; + return string.Empty; + } + } } diff --git a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs index 41c16be4906..27b953bf026 100644 --- a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs +++ b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs @@ -28,16 +28,147 @@ namespace DotNetNuke.Services.Journal internal class JournalControllerImpl : IJournalController { - private readonly IJournalDataService _dataService; private const string AllowResizePhotosSetting = "Journal_AllowResizePhotos"; private const string AllowPhotosSetting = "Journal_AllowPhotos"; + private readonly IJournalDataService _dataService; private const string EditorEnabledSetting = "Journal_EditorEnabled"; + + private static readonly string[] InvalidSecuritySetsWithoutId = new[] { "R", "U", "F", "P" }; + private static readonly char[] ValidSecurityDescriptors = new[] { 'E', 'C', 'R', 'U', 'F', 'P' }; public JournalControllerImpl() { this._dataService = JournalDataService.Instance; } + // Journal Items + 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 Exception("Unable to locate the current user"); + } + + string xml = null; + var portalSecurity = PortalSecurity.Instance; + if (!string.IsNullOrEmpty(journalItem.Title)) + { + journalItem.Title = portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); + } + + if (!string.IsNullOrEmpty(journalItem.Summary)) + { + journalItem.Summary = portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.Body)) + { + journalItem.Body = portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.Body)) + { + var xDoc = new XmlDocument { XmlResolver = null }; + XmlElement xnode = xDoc.CreateElement("items"); + XmlElement xnode2 = xDoc.CreateElement("item"); + xnode2.AppendChild(this.CreateElement(xDoc, "id", "-1")); + xnode2.AppendChild(this.CreateCDataElement(xDoc, "body", journalItem.Body)); + xnode.AppendChild(xnode2); + xDoc.AppendChild(xnode); + XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", null, null); + xDec.Encoding = "UTF-16"; + xDec.Standalone = "yes"; + XmlElement 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 = portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.Description)) + { + journalItem.ItemData.Description = portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.Url)) + { + journalItem.ItemData.Url = portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); + } + + if (!string.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) + { + journalItem.ItemData.ImageUrl = portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); + } + } + + string journalData = journalItem.ItemData.ToJson(); + if (journalData == "null") + { + journalData = null; + } + + this.PrepareSecuritySet(journalItem, currentUser); + + 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 + { + ContentItem 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); + } + } + } + private XmlElement CreateElement(XmlDocument xDoc, string name, string value) { XmlElement xnode = xDoc.CreateElement(name); @@ -279,137 +410,6 @@ private void PrepareSecuritySet(JournalItem journalItem, UserInfo currentUser) journalItem.SecuritySet = string.Join(",", parts); } - private static readonly string[] InvalidSecuritySetsWithoutId = new[] { "R", "U", "F", "P" }; - private static readonly char[] ValidSecurityDescriptors = new[] { 'E', 'C', 'R', 'U', 'F', 'P' }; - - // Journal Items - 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 Exception("Unable to locate the current user"); - } - - string xml = null; - var portalSecurity = PortalSecurity.Instance; - if (!string.IsNullOrEmpty(journalItem.Title)) - { - journalItem.Title = portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); - } - - if (!string.IsNullOrEmpty(journalItem.Summary)) - { - journalItem.Summary = portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.Body)) - { - journalItem.Body = portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.Body)) - { - var xDoc = new XmlDocument { XmlResolver = null }; - XmlElement xnode = xDoc.CreateElement("items"); - XmlElement xnode2 = xDoc.CreateElement("item"); - xnode2.AppendChild(this.CreateElement(xDoc, "id", "-1")); - xnode2.AppendChild(this.CreateCDataElement(xDoc, "body", journalItem.Body)); - xnode.AppendChild(xnode2); - xDoc.AppendChild(xnode); - XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", null, null); - xDec.Encoding = "UTF-16"; - xDec.Standalone = "yes"; - XmlElement 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 = portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.Description)) - { - journalItem.ItemData.Description = portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.Url)) - { - journalItem.ItemData.Url = portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); - } - - if (!string.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) - { - journalItem.ItemData.ImageUrl = portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); - } - } - - string journalData = journalItem.ItemData.ToJson(); - if (journalData == "null") - { - journalData = null; - } - - this.PrepareSecuritySet(journalItem, currentUser); - - 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 - { - ContentItem 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 void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) { if (journalItem.UserId < 1) @@ -626,8 +626,8 @@ public void HideComments(int portalId, int journalId) } public void ShowComments(int portalId, int journalId) - { - this._dataService.Journal_Comments_ToggleHidden(portalId, journalId, false); + { + this._dataService.Journal_Comments_ToggleHidden(portalId, journalId, false); } // Delete Journal Items diff --git a/DNN Platform/Library/Services/Journal/JournalEntity.cs b/DNN Platform/Library/Services/Journal/JournalEntity.cs index 41f0c31c9f3..6193564a206 100644 --- a/DNN Platform/Library/Services/Journal/JournalEntity.cs +++ b/DNN Platform/Library/Services/Journal/JournalEntity.cs @@ -14,14 +14,6 @@ namespace DotNetNuke.Services.Journal public class JournalEntity : IPropertyAccess { - public int Id { get; set; } - - public string Name { get; set; } - - public string Vanity { get; set; } - - public string Avatar { get; set; } - public JournalEntity() { } @@ -49,6 +41,14 @@ public JournalEntity(string entityXML) } } } + + public int Id { get; set; } + + public string Name { get; set; } + + public string Vanity { get; set; } + + public string Avatar { get; set; } public CacheLevel Cacheability { diff --git a/DNN Platform/Library/Services/Journal/JournalItem.cs b/DNN Platform/Library/Services/Journal/JournalItem.cs index 93905f674bb..eae1339a26b 100644 --- a/DNN Platform/Library/Services/Journal/JournalItem.cs +++ b/DNN Platform/Library/Services/Journal/JournalItem.cs @@ -15,9 +15,9 @@ namespace DotNetNuke.Services.Journal using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Security; - using DotNetNuke.Services.Tokens; + using DotNetNuke.Services.Tokens; - public class JournalItem : IHydratable, IPropertyAccess + public class JournalItem : IHydratable, IPropertyAccess { public int JournalId { get; set; } @@ -69,9 +69,9 @@ public class JournalItem : IHydratable, IPropertyAccess public bool CommentsHidden { get; set; } - public int SimilarCount { get; set; } - - /// + public int SimilarCount { get; set; } + + /// /// Gets or sets the key ID. /// /// @@ -93,6 +93,14 @@ public virtual int KeyID this.JournalId = value; } } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } public void Fill(IDataReader dr) { @@ -137,14 +145,6 @@ public void Fill(IDataReader dr) this.CommentsHidden = Null.SetNullBoolean(dr["CommentsHidden"]); this.SimilarCount = Null.SetNullInteger(dr["SimilarCount"]); } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { diff --git a/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs b/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs index 4700d560fa4..646a434d9fe 100644 --- a/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs +++ b/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs @@ -84,17 +84,6 @@ public LanguagePackType PackageType } } } - - public void Fill(IDataReader dr) - { - this.LanguagePackID = Null.SetNullInteger(dr["LanguagePackID"]); - this.LanguageID = Null.SetNullInteger(dr["LanguageID"]); - this.PackageID = Null.SetNullInteger(dr["PackageID"]); - this.DependentPackageID = Null.SetNullInteger(dr["DependentPackageID"]); - - // Call the base classes fill method to populate base class proeprties - this.FillInternal(dr); - } public int KeyID { @@ -108,5 +97,16 @@ public int KeyID this.LanguagePackID = value; } } + + public void Fill(IDataReader dr) + { + this.LanguagePackID = Null.SetNullInteger(dr["LanguagePackID"]); + this.LanguageID = Null.SetNullInteger(dr["LanguageID"]); + this.PackageID = Null.SetNullInteger(dr["PackageID"]); + this.DependentPackageID = Null.SetNullInteger(dr["DependentPackageID"]); + + // Call the base classes fill method to populate base class proeprties + this.FillInternal(dr); + } } } diff --git a/DNN Platform/Library/Services/Localization/Locale.cs b/DNN Platform/Library/Services/Localization/Locale.cs index 8b14856aa12..dc531d2925b 100644 --- a/DNN Platform/Library/Services/Localization/Locale.cs +++ b/DNN Platform/Library/Services/Localization/Locale.cs @@ -85,6 +85,19 @@ public string NativeName public int PortalId { get; set; } public string Text { get; set; } + + public int KeyID + { + get + { + return this.LanguageId; + } + + set + { + this.LanguageId = value; + } + } public void Fill(IDataReader dr) { @@ -106,18 +119,5 @@ public void Fill(IDataReader dr) // Call the base classes fill method to populate base class proeprties this.FillInternal(dr); } - - public int KeyID - { - get - { - return this.LanguageId; - } - - set - { - this.LanguageId = value; - } - } } } diff --git a/DNN Platform/Library/Services/Localization/LocaleCollection.cs b/DNN Platform/Library/Services/Localization/LocaleCollection.cs index c614ca8e913..f57afa35f0a 100644 --- a/DNN Platform/Library/Services/Localization/LocaleCollection.cs +++ b/DNN Platform/Library/Services/Localization/LocaleCollection.cs @@ -14,54 +14,54 @@ public class LocaleCollection : NameObjectCollectionBase { private DictionaryEntry _de; - public DictionaryEntry this[int index] + // Gets a String array that contains all the keys in the collection. + public string[] AllKeys { get { - this._de.Key = this.BaseGetKey(index); - this._de.Value = this.BaseGet(index); - return this._de; + return this.BaseGetAllKeys(); } } - // Gets or sets the value associated with the specified key. - public Locale this[string key] + // Gets an Object array that contains all the values in the collection. + public Array AllValues { get { - return (Locale)this.BaseGet(key); - } - - set - { - this.BaseSet(key, value); + return this.BaseGetAllValues(); } } - // Gets a String array that contains all the keys in the collection. - public string[] AllKeys + // Gets a value indicating if the collection contains keys that are not null. + public bool HasKeys { get { - return this.BaseGetAllKeys(); + return this.BaseHasKeys(); } } - // Gets an Object array that contains all the values in the collection. - public Array AllValues + public DictionaryEntry this[int index] { get { - return this.BaseGetAllValues(); + this._de.Key = this.BaseGetKey(index); + this._de.Value = this.BaseGet(index); + return this._de; } } - // Gets a value indicating if the collection contains keys that are not null. - public bool HasKeys + // Gets or sets the value associated with the specified key. + public Locale this[string key] { get { - return this.BaseHasKeys(); + return (Locale)this.BaseGet(key); + } + + set + { + this.BaseSet(key, value); } } diff --git a/DNN Platform/Library/Services/Localization/LocaleController.cs b/DNN Platform/Library/Services/Localization/LocaleController.cs index 33a4acb2209..8e8c58de632 100644 --- a/DNN Platform/Library/Services/Localization/LocaleController.cs +++ b/DNN Platform/Library/Services/Localization/LocaleController.cs @@ -30,13 +30,12 @@ namespace DotNetNuke.Services.Localization /// public class LocaleController : ComponentBase, ILocaleController { - private static object GetLocalesCallBack(CacheItemArgs cacheItemArgs) + public static bool IsValidCultureName(string name) { - var portalID = (int)cacheItemArgs.ParamList[0]; - Dictionary locales = CBO.FillDictionary("CultureCode", portalID > Null.NullInteger - ? DataProvider.Instance().GetLanguagesByPortal(portalID) - : DataProvider.Instance().GetLanguages(), new Dictionary(StringComparer.OrdinalIgnoreCase)); - return locales; + return + CultureInfo + .GetCultures(CultureTypes.SpecificCultures) + .Any(c => c.Name == name); } /// @@ -62,6 +61,15 @@ public List GetCultures(Dictionary locales) { return locales.Values.Select(locale => new CultureInfo(locale.Code)).ToList(); } + + private static object GetLocalesCallBack(CacheItemArgs cacheItemArgs) + { + var portalID = (int)cacheItemArgs.ParamList[0]; + Dictionary locales = CBO.FillDictionary("CultureCode", portalID > Null.NullInteger + ? DataProvider.Instance().GetLanguagesByPortal(portalID) + : DataProvider.Instance().GetLanguages(), new Dictionary(StringComparer.OrdinalIgnoreCase)); + return locales; + } /// /// Gets the current locale for current request to the portal. @@ -304,13 +312,5 @@ public void PublishLanguage(int portalid, string cultureCode, bool publish) } } } - - public static bool IsValidCultureName(string name) - { - return - CultureInfo - .GetCultures(CultureTypes.SpecificCultures) - .Any(c => c.Name == name); - } } } diff --git a/DNN Platform/Library/Services/Localization/Localization.cs b/DNN Platform/Library/Services/Localization/Localization.cs index fbb0f47c333..cb9d342172f 100644 --- a/DNN Platform/Library/Services/Localization/Localization.cs +++ b/DNN Platform/Library/Services/Localization/Localization.cs @@ -268,6 +268,75 @@ public string CurrentUICulture } } + public static int ActiveLanguagesByPortalID(int portalID) + { + // Default to 1 (maybe called during portal creation before languages are enabled for portal) + int count = 1; + Dictionary locales = LocaleController.Instance.GetLocales(portalID); + if (locales != null) + { + count = locales.Count; + } + + return count; + } + + public static void AddLanguageToPortal(int portalID, int languageID, bool clearCache) + { + // try to get valid locale reference + var newLocale = LocaleController.Instance.GetLocale(languageID); + + // we can only add a valid locale + if (newLocale != null) + { + // check if locale has not been added to portal already + var portalLocale = LocaleController.Instance.GetLocale(portalID, newLocale.Code); + + // locale needs to be added + if (portalLocale == null) + { + // We need to add a translator role for the language + bool contentLocalizationEnabled = PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalID, false); + if (contentLocalizationEnabled) + { + // Create new Translator Role + AddTranslatorRole(portalID, newLocale); + } + + DataProvider.Instance().AddPortalLanguage(portalID, languageID, false, UserController.Instance.GetCurrentUserInfo().UserID); + string cacheKey = string.Format(DataCache.LocalesCacheKey, portalID); + DataCache.RemoveCache(cacheKey); + + EventLogController.Instance.AddLog( + "portalID/languageID", + portalID + "/" + languageID, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.LANGUAGETOPORTAL_CREATED); + + var portalInfo = PortalController.Instance.GetPortal(portalID); + if (portalInfo != null && newLocale.Code != portalInfo.DefaultLanguage) + { + // check to see if this is the first extra language being added to the portal + var portalLocales = LocaleController.Instance.GetLocales(portalID); + var firstExtraLanguage = (portalLocales != null) && portalLocales.Count == 2; + + if (firstExtraLanguage) + { + AddLanguageHttpAlias(portalID, LocaleController.Instance.GetLocale(portalID, portalInfo.DefaultLanguage)); + } + + AddLanguageHttpAlias(portalID, newLocale); + } + + if (clearCache) + { + DataCache.ClearPortalCache(portalID, false); + } + } + } + } + private static void LocalizeDataControlField(DataControlField controlField, string resourceFile) { string localizedText; @@ -369,73 +438,26 @@ private static void LocalizeDataControlField(DataControlField controlField, stri } } } - - public static int ActiveLanguagesByPortalID(int portalID) + + public static void AddLanguagesToPortal(int portalID) { - // Default to 1 (maybe called during portal creation before languages are enabled for portal) - int count = 1; - Dictionary locales = LocaleController.Instance.GetLocales(portalID); - if (locales != null) + foreach (Locale language in LocaleController.Instance.GetLocales(Null.NullInteger).Values) { - count = locales.Count; + // Add Portal/Language to PortalLanguages + AddLanguageToPortal(portalID, language.LanguageId, false); } - return count; + DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portalID)); } - public static void AddLanguageToPortal(int portalID, int languageID, bool clearCache) + public static void AddLanguageToPortals(int languageID) { - // try to get valid locale reference - var newLocale = LocaleController.Instance.GetLocale(languageID); - - // we can only add a valid locale - if (newLocale != null) + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - // check if locale has not been added to portal already - var portalLocale = LocaleController.Instance.GetLocale(portalID, newLocale.Code); - - // locale needs to be added - if (portalLocale == null) - { - // We need to add a translator role for the language - bool contentLocalizationEnabled = PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", portalID, false); - if (contentLocalizationEnabled) - { - // Create new Translator Role - AddTranslatorRole(portalID, newLocale); - } - - DataProvider.Instance().AddPortalLanguage(portalID, languageID, false, UserController.Instance.GetCurrentUserInfo().UserID); - string cacheKey = string.Format(DataCache.LocalesCacheKey, portalID); - DataCache.RemoveCache(cacheKey); - - EventLogController.Instance.AddLog( - "portalID/languageID", - portalID + "/" + languageID, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.LANGUAGETOPORTAL_CREATED); - - var portalInfo = PortalController.Instance.GetPortal(portalID); - if (portalInfo != null && newLocale.Code != portalInfo.DefaultLanguage) - { - // check to see if this is the first extra language being added to the portal - var portalLocales = LocaleController.Instance.GetLocales(portalID); - var firstExtraLanguage = (portalLocales != null) && portalLocales.Count == 2; - - if (firstExtraLanguage) - { - AddLanguageHttpAlias(portalID, LocaleController.Instance.GetLocale(portalID, portalInfo.DefaultLanguage)); - } - - AddLanguageHttpAlias(portalID, newLocale); - } + // Add Portal/Language to PortalLanguages + AddLanguageToPortal(portal.PortalID, languageID, false); - if (clearCache) - { - DataCache.ClearPortalCache(portalID, false); - } - } + DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portal.PortalID)); } } @@ -477,12 +499,12 @@ private static void AddLanguageHttpAlias(int portalId, Locale locale) 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()), - }; + var newAlias = new PortalAliasInfo(currentAlias) + { + IsPrimary = true, + CultureCode = locale.Code, + HTTPAlias = GetValidLanguageURL(portalId, httpAlias, locale.Code.ToLowerInvariant()), + }; PortalAliasController.Instance.AddPortalAlias(newAlias); } @@ -533,28 +555,6 @@ private static string GetValidLanguageURL(int portalId, string httpAlias, string return alias; } - public static void AddLanguagesToPortal(int portalID) - { - foreach (Locale language in LocaleController.Instance.GetLocales(Null.NullInteger).Values) - { - // Add Portal/Language to PortalLanguages - AddLanguageToPortal(portalID, language.LanguageId, false); - } - - DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portalID)); - } - - public static void AddLanguageToPortals(int languageID) - { - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - // Add Portal/Language to PortalLanguages - AddLanguageToPortal(portal.PortalID, languageID, false); - - DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portal.PortalID)); - } - } - public static void AddTranslatorRole(int portalID, Locale language) { // Create new Translator Role @@ -753,28 +753,6 @@ public static string GetExceptionMessage(string key, string defaultValue, params var content = GetString(key, ExceptionsResourceFile); return string.Format(string.IsNullOrEmpty(content) ? defaultValue : GetString(key, ExceptionsResourceFile), @params); } - - public string GetFixedCurrency(decimal expression, string culture, int numDigitsAfterDecimal) - { - string oldCurrentCulture = this.CurrentUICulture; - var newCulture = new CultureInfo(culture); - Thread.CurrentThread.CurrentUICulture = newCulture; - string currencyStr = expression.ToString(newCulture.NumberFormat.CurrencySymbol); - var oldCulture = new CultureInfo(oldCurrentCulture); - Thread.CurrentThread.CurrentUICulture = oldCulture; - return currencyStr; - } - - 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); - var oldCulture = new CultureInfo(oldCurrentCulture); - Thread.CurrentThread.CurrentUICulture = oldCulture; - return dateStr; - } public static string GetLanguageDisplayMode(int portalId) { @@ -824,6 +802,28 @@ public static string GetLocaleName(string code, CultureDropDownTypes displayType return name; } + public string GetFixedCurrency(decimal expression, string culture, int numDigitsAfterDecimal) + { + string oldCurrentCulture = this.CurrentUICulture; + var newCulture = new CultureInfo(culture); + Thread.CurrentThread.CurrentUICulture = newCulture; + string currencyStr = expression.ToString(newCulture.NumberFormat.CurrencySymbol); + var oldCulture = new CultureInfo(oldCurrentCulture); + Thread.CurrentThread.CurrentUICulture = oldCulture; + return currencyStr; + } + + 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); + var oldCulture = new CultureInfo(oldCurrentCulture); + Thread.CurrentThread.CurrentUICulture = oldCulture; + return dateStr; + } + /// /// Detects the current language for the request. /// The order in which the language is being detect is: @@ -882,6 +882,110 @@ public static CultureInfo GetPageLocale(PortalSettings portalSettings) return pageCulture; } + /// + /// Tries to get a valid language from the browser preferences. + /// + /// Id of the current portal. + /// A valid CultureInfo if any is found. + public static CultureInfo GetBrowserCulture(int portalId) + { + if (HttpContext.Current == null || HttpContext.Current.Request == null || HttpContext.Current.Request.UserLanguages == null) + { + return null; + } + + CultureInfo culture = null; + foreach (string userLang in HttpContext.Current.Request.UserLanguages) + { + // split userlanguage by ";"... all but the first language will contain a preferrence index eg. ;q=.5 + string language = userLang.Split(';')[0]; + culture = GetCultureFromString(portalId, language); + if (culture != null) + { + break; + } + } + + return culture; + } + + public static string GetResourceFileName(string resourceFileName, string language, string mode, int portalId) + { + if (!resourceFileName.EndsWith(".resx")) + { + resourceFileName += ".resx"; + } + + if (language != SystemLocale) + { + if (resourceFileName.ToLowerInvariant().EndsWith(".en-us.resx")) + { + resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 11) + "." + language + ".resx"; + } + else + { + resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + language + ".resx"; + } + } + + if (mode == "Host") + { + resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Host.resx"; + } + else if (mode == "Portal") + { + resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Portal-" + portalId + ".resx"; + } + + return resourceFileName; + } + + public static string GetResourceFile(Control control, string fileName) + { + return control.TemplateSourceDirectory + "/" + LocalResourceDirectory + "/" + fileName; + } + + /// + /// Parses the language parameter into a valid and enabled language in the current portal. + /// 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. + /// Language to be parsed. + /// A valid and enabled CultureInfo that matches the language passed if any. + internal static CultureInfo GetCultureFromString(int portalId, string language) + { + CultureInfo culture = null; + if (!string.IsNullOrEmpty(language)) + { + if (LocaleController.Instance.IsEnabled(ref language, portalId)) + { + culture = new CultureInfo(language); + } + else + { + string preferredLanguage = language.Split('-')[0]; + + Dictionary enabledLocales = new Dictionary(); + if (portalId > Null.NullInteger) + { + enabledLocales = LocaleController.Instance.GetLocales(portalId); + } + + foreach (string localeCode in enabledLocales.Keys) + { + if (localeCode.Split('-')[0] == preferredLanguage.Split('-')[0]) + { + culture = new CultureInfo(localeCode); + break; + } + } + } + } + + return culture; + } + /// /// Tries to get a valid language from the querystring. /// @@ -988,110 +1092,6 @@ private static CultureInfo GetCultureFromPortal(PortalSettings portalSettings) return culture; } - - /// - /// Tries to get a valid language from the browser preferences. - /// - /// Id of the current portal. - /// A valid CultureInfo if any is found. - public static CultureInfo GetBrowserCulture(int portalId) - { - if (HttpContext.Current == null || HttpContext.Current.Request == null || HttpContext.Current.Request.UserLanguages == null) - { - return null; - } - - CultureInfo culture = null; - foreach (string userLang in HttpContext.Current.Request.UserLanguages) - { - // split userlanguage by ";"... all but the first language will contain a preferrence index eg. ;q=.5 - string language = userLang.Split(';')[0]; - culture = GetCultureFromString(portalId, language); - if (culture != null) - { - break; - } - } - - return culture; - } - - /// - /// Parses the language parameter into a valid and enabled language in the current portal. - /// 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. - /// Language to be parsed. - /// A valid and enabled CultureInfo that matches the language passed if any. - internal static CultureInfo GetCultureFromString(int portalId, string language) - { - CultureInfo culture = null; - if (!string.IsNullOrEmpty(language)) - { - if (LocaleController.Instance.IsEnabled(ref language, portalId)) - { - culture = new CultureInfo(language); - } - else - { - string preferredLanguage = language.Split('-')[0]; - - Dictionary enabledLocales = new Dictionary(); - if (portalId > Null.NullInteger) - { - enabledLocales = LocaleController.Instance.GetLocales(portalId); - } - - foreach (string localeCode in enabledLocales.Keys) - { - if (localeCode.Split('-')[0] == preferredLanguage.Split('-')[0]) - { - culture = new CultureInfo(localeCode); - break; - } - } - } - } - - return culture; - } - - public static string GetResourceFileName(string resourceFileName, string language, string mode, int portalId) - { - if (!resourceFileName.EndsWith(".resx")) - { - resourceFileName += ".resx"; - } - - if (language != SystemLocale) - { - if (resourceFileName.ToLowerInvariant().EndsWith(".en-us.resx")) - { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 11) + "." + language + ".resx"; - } - else - { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + language + ".resx"; - } - } - - if (mode == "Host") - { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Host.resx"; - } - else if (mode == "Portal") - { - resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Portal-" + portalId + ".resx"; - } - - return resourceFileName; - } - - public static string GetResourceFile(Control control, string fileName) - { - return control.TemplateSourceDirectory + "/" + LocalResourceDirectory + "/" + fileName; - } public static string GetString(string key, Control ctrl) { @@ -1833,11 +1833,6 @@ public static string LocalizeRole(string role) return localRole; } - private static IList GetPortalLocalizations(int portalID) - { - return CBO.FillCollection(DataProvider.Instance().GetPortalLocalizations(portalID)); - } - public static void RemoveLanguageFromPortal(int portalID, int languageID) { RemoveLanguageFromPortal(portalID, languageID, false); @@ -1915,6 +1910,11 @@ public static void RemoveLanguageFromPortal(int portalID, int languageID, bool i } } + private static IList GetPortalLocalizations(int portalID) + { + return CBO.FillCollection(DataProvider.Instance().GetPortalLocalizations(portalID)); + } + public static void RemoveLanguageFromPortals(int languageId) { RemoveLanguageFromPortals(languageId, false); @@ -2034,6 +2034,19 @@ public static void SetThreadCultures(CultureInfo cultureInfo, PortalSettings por } } + /// + /// Maps the culture code string into the corresponding language ID in the + /// database. In case there is no language defined in the systen with the + /// passed code, -1 () is returned. + /// + /// The culture to get the language ID for. + /// Language ID integer. + public static int GetCultureLanguageID(string cultureCode) + { + var locale = LocaleController.Instance.GetLocale(cultureCode); + return locale != null ? locale.LanguageId : Null.NullInteger; + } + /// /// When portal allows users to select their preferred UI language, this method /// will return the user ui preferred language if defined. Otherwise defaults @@ -2065,18 +2078,5 @@ private static CultureInfo GetUserUICulture(CultureInfo currentCulture, PortalSe return uiCulture; } - - /// - /// Maps the culture code string into the corresponding language ID in the - /// database. In case there is no language defined in the systen with the - /// passed code, -1 () is returned. - /// - /// The culture to get the language ID for. - /// Language ID integer. - public static int GetCultureLanguageID(string cultureCode) - { - var locale = LocaleController.Instance.GetLocale(cultureCode); - return locale != null ? locale.LanguageId : Null.NullInteger; - } } } diff --git a/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs b/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs index 2fb6bfeaffd..cdd3e6b6809 100644 --- a/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs +++ b/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs @@ -24,19 +24,6 @@ public override bool SupportsEvaluate } } - public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) - { - var inputParams = new CodeExpression[] - { - new CodePrimitiveExpression(entry.Expression.Trim()), - new CodeTypeOfExpression(entry.DeclaringType), - new CodePrimitiveExpression(entry.PropertyInfo.Name), - new CodePrimitiveExpression(context.VirtualPath), - }; - - return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.GetType()), "GetLocalizedResource", inputParams); - } - public static object GetLocalizedResource(string key, Type targetType, string propertyName, string virtualPath) { if (HttpContext.Current == null) @@ -84,6 +71,19 @@ public static object GetLocalizedResource(string key, Type targetType, string pr return value; } + public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) + { + var inputParams = new CodeExpression[] + { + new CodePrimitiveExpression(entry.Expression.Trim()), + new CodeTypeOfExpression(entry.DeclaringType), + new CodePrimitiveExpression(entry.PropertyInfo.Name), + new CodePrimitiveExpression(context.VirtualPath), + }; + + return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.GetType()), "GetLocalizedResource", inputParams); + } + public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) { string key = entry.Expression.Trim(); diff --git a/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs b/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs index a7e46090331..9430cd5887f 100644 --- a/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs +++ b/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs @@ -22,17 +22,49 @@ namespace DotNetNuke.Services.Log.EventLog public class DBLoggingProvider : LoggingProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DBLoggingProvider)); + public const string LogTypeCacheKey = "LogTypes"; + public const string LogTypeInfoCacheKey = "GetLogTypeConfigInfo"; + private const int ReaderLockTimeout = 10000; private const int WriterLockTimeout = 10000; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DBLoggingProvider)); private static readonly IList LogQueue = new List(); private static readonly ReaderWriterLockSlim LockNotif = new ReaderWriterLockSlim(); private static readonly ReaderWriterLockSlim LockQueueLog = new ReaderWriterLockSlim(); - - public const string LogTypeCacheKey = "LogTypes"; - public const string LogTypeInfoCacheKey = "GetLogTypeConfigInfo"; public const string LogTypeInfoByKeyCacheKey = "GetLogTypeConfigInfoByKey"; + public override void AddLog(LogInfo logInfo) + { + string configPortalID = logInfo.LogPortalID != Null.NullInteger + ? logInfo.LogPortalID.ToString() + : "*"; + var logTypeConfigInfo = this.GetLogTypeConfigInfoByKey(logInfo.LogTypeKey, configPortalID); + if (logTypeConfigInfo == null || logTypeConfigInfo.LoggingIsActive == false) + { + return; + } + + logInfo.LogConfigID = logTypeConfigInfo.ID; + var logQueueItem = new LogQueueItem { LogInfo = logInfo, LogTypeConfigInfo = logTypeConfigInfo }; + SchedulingProvider scheduler = SchedulingProvider.Instance(); + if (scheduler == null || logInfo.BypassBuffering || SchedulingProvider.Enabled == false + || scheduler.GetScheduleStatus() == ScheduleStatus.STOPPED || !Host.EventLogBuffer) + { + WriteLog(logQueueItem); + } + else + { + LogQueue.Add(logQueueItem); + } + } + + // ReSharper disable once InconsistentNaming + public override void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner) + { + DataProvider.Instance().AddLogType(logTypeKey, logTypeFriendlyName, logTypeDescription, logTypeCSSClass, logTypeOwner); + DataCache.RemoveCache(LogTypeCacheKey); + } + private static Hashtable FillLogTypeConfigInfoByKey(ArrayList arr) { var ht = new Hashtable(); @@ -57,38 +89,6 @@ private static Hashtable FillLogTypeConfigInfoByKey(ArrayList arr) return ht; } - private LogTypeConfigInfo GetLogTypeConfigInfoByKey(string logTypeKey, string logTypePortalID) - { - var configInfoByKey = (Hashtable)DataCache.GetCache(LogTypeInfoByKeyCacheKey) ?? FillLogTypeConfigInfoByKey(this.GetLogTypeConfigInfo()); - var logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey[logTypeKey + "|" + logTypePortalID]; - if (logTypeConfigInfo == null) - { - logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey["*|" + logTypePortalID]; - if (logTypeConfigInfo == null) - { - logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey[logTypeKey + "|*"]; - if (logTypeConfigInfo == null) - { - logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey["*|*"]; - } - else - { - return logTypeConfigInfo; - } - } - else - { - return logTypeConfigInfo; - } - } - else - { - return logTypeConfigInfo; - } - - return logTypeConfigInfo; - } - private static LogInfo FillLogInfo(IDataReader dr) { var obj = new LogInfo(); @@ -156,6 +156,38 @@ private static void FillLogs(IDataReader dr, IList logs, ref int totalRecords) } } + private LogTypeConfigInfo GetLogTypeConfigInfoByKey(string logTypeKey, string logTypePortalID) + { + var configInfoByKey = (Hashtable)DataCache.GetCache(LogTypeInfoByKeyCacheKey) ?? FillLogTypeConfigInfoByKey(this.GetLogTypeConfigInfo()); + var logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey[logTypeKey + "|" + logTypePortalID]; + if (logTypeConfigInfo == null) + { + logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey["*|" + logTypePortalID]; + if (logTypeConfigInfo == null) + { + logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey[logTypeKey + "|*"]; + if (logTypeConfigInfo == null) + { + logTypeConfigInfo = (LogTypeConfigInfo)configInfoByKey["*|*"]; + } + else + { + return logTypeConfigInfo; + } + } + else + { + return logTypeConfigInfo; + } + } + else + { + return logTypeConfigInfo; + } + + return logTypeConfigInfo; + } + private static void WriteError(LogTypeConfigInfo logTypeConfigInfo, Exception exc, string header, string message) { if (HttpContext.Current != null) @@ -236,38 +268,6 @@ private static void WriteLog(LogQueueItem logQueueItem) } } - public override void AddLog(LogInfo logInfo) - { - string configPortalID = logInfo.LogPortalID != Null.NullInteger - ? logInfo.LogPortalID.ToString() - : "*"; - var logTypeConfigInfo = this.GetLogTypeConfigInfoByKey(logInfo.LogTypeKey, configPortalID); - if (logTypeConfigInfo == null || logTypeConfigInfo.LoggingIsActive == false) - { - return; - } - - logInfo.LogConfigID = logTypeConfigInfo.ID; - var logQueueItem = new LogQueueItem { LogInfo = logInfo, LogTypeConfigInfo = logTypeConfigInfo }; - SchedulingProvider scheduler = SchedulingProvider.Instance(); - if (scheduler == null || logInfo.BypassBuffering || SchedulingProvider.Enabled == false - || scheduler.GetScheduleStatus() == ScheduleStatus.STOPPED || !Host.EventLogBuffer) - { - WriteLog(logQueueItem); - } - else - { - LogQueue.Add(logQueueItem); - } - } - - // ReSharper disable once InconsistentNaming - public override void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner) - { - DataProvider.Instance().AddLogType(logTypeKey, logTypeFriendlyName, logTypeDescription, logTypeCSSClass, logTypeOwner); - DataCache.RemoveCache(LogTypeCacheKey); - } - 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) { diff --git a/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs b/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs index 605e40b0979..47a80fcb294 100644 --- a/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs @@ -178,9 +178,14 @@ public enum EventLogType FOLDER_MOVED, } - protected override Func GetFactory() + public static void AddSettingLog(EventLogType logTypeKey, string idFieldName, int idValue, string settingName, string settingValue, int userId) { - return () => new EventLogController(); + var log = new LogInfo() { LogUserID = userId, LogTypeKey = logTypeKey.ToString() }; + log.LogProperties.Add(new LogDetailInfo(idFieldName, idValue.ToString())); + log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); + log.LogProperties.Add(new LogDetailInfo("SettingValue", settingValue)); + + LogController.Instance.AddLog(log); } public void AddLog(string propertyName, string propertyValue, EventLogType logType) @@ -192,6 +197,11 @@ public void AddLog(string propertyName, string propertyValue, PortalSettings por { this.AddLog(propertyName, propertyValue, portalSettings, userID, logType.ToString()); } + + protected override Func GetFactory() + { + return () => new EventLogController(); + } public void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, string logType) { @@ -204,13 +214,13 @@ public void AddLog(string propertyName, string propertyValue, PortalSettings por public void AddLog(LogProperties properties, PortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering) { // supports adding a custom string for LogType - var log = new LogInfo - { - LogUserID = userID, - LogTypeKey = logTypeKey, - LogProperties = properties, - BypassBuffering = bypassBuffering, - }; + var log = new LogInfo + { + LogUserID = userID, + LogTypeKey = logTypeKey, + LogProperties = properties, + BypassBuffering = bypassBuffering, + }; if (portalSettings != null) { log.LogPortalID = portalSettings.PortalId; @@ -415,15 +425,5 @@ public virtual void UpdateLogType(LogTypeInfo logType) { LogController.Instance.UpdateLogType(logType); } - - public static void AddSettingLog(EventLogType logTypeKey, string idFieldName, int idValue, string settingName, string settingValue, int userId) - { - var log = new LogInfo() { LogUserID = userId, LogTypeKey = logTypeKey.ToString() }; - log.LogProperties.Add(new LogDetailInfo(idFieldName, idValue.ToString())); - log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); - log.LogProperties.Add(new LogDetailInfo("SettingValue", settingValue)); - - LogController.Instance.AddLog(log); - } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs b/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs index c433a2d8ccc..009d0e90b48 100644 --- a/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs @@ -114,10 +114,10 @@ public void AddLog(Exception objException, LogInfo log, ExceptionLogType logType var sqlException = objException as SqlException; if (sqlException != null && (uint)sqlException.ErrorCode == 0x80131904 && sqlException.Number == 4060) - { - // This is to avoid stack-overflow exception when a database connection exception occurs - // bercause the logger will try to write to the database and goes in a loop of failures. - Trace.TraceError(log.Serialize()); + { + // This is to avoid stack-overflow exception when a database connection exception occurs + // bercause the logger will try to write to the database and goes in a loop of failures. + Trace.TraceError(log.Serialize()); } else { diff --git a/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs b/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs index 75c376af442..b81f07fba02 100644 --- a/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs +++ b/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs @@ -8,8 +8,8 @@ namespace DotNetNuke.Services.Log.EventLog public interface ILogViewer { - void BindData(); - string EventFilter { get; set; } + + void BindData(); } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogController.cs b/DNN Platform/Library/Services/Log/EventLog/LogController.cs index a660a8824ad..d77df9efb0c 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogController.cs @@ -23,9 +23,157 @@ namespace DotNetNuke.Services.Log.EventLog public partial class LogController : ServiceLocator, ILogController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LogController)); private const int WriterLockTimeout = 10000; // milliseconds + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LogController)); private static readonly ReaderWriterLockSlim LockLog = new ReaderWriterLockSlim(); + + public void AddLog(LogInfo logInfo) + { + if (Globals.Status == Globals.UpgradeStatus.Install) + { + Logger.Info(logInfo); + } + else + { + try + { + logInfo.LogCreateDate = DateTime.Now; + logInfo.LogServerName = Globals.ServerName; + if (string.IsNullOrEmpty(logInfo.LogServerName)) + { + logInfo.LogServerName = "NA"; + } + + if (string.IsNullOrEmpty(logInfo.LogUserName)) + { + if (HttpContext.Current != null) + { + if (HttpContext.Current.Request.IsAuthenticated) + { + logInfo.LogUserName = UserController.Instance.GetCurrentUserInfo().Username; + } + } + } + + // Get portal name if name isn't set + if (logInfo.LogPortalID != Null.NullInteger && string.IsNullOrEmpty(logInfo.LogPortalName)) + { + logInfo.LogPortalName = PortalController.Instance.GetPortal(logInfo.LogPortalID).PortalName; + } + + // Check if Log Type exists + if (!this.GetLogTypeInfoDictionary().ContainsKey(logInfo.LogTypeKey)) + { + // Add new Log Type + var logType = new LogTypeInfo() + { + LogTypeKey = logInfo.LogTypeKey, + LogTypeFriendlyName = logInfo.LogTypeKey, + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + LogTypeCSSClass = "GeneralAdminOperation", + LogTypeDescription = string.Empty, + }; + this.AddLogType(logType); + + var logTypeConfigInfo = new LogTypeConfigInfo() + { + LogTypeKey = logInfo.LogTypeKey, + LogTypePortalID = "*", + LoggingIsActive = false, + KeepMostRecent = "-1", + EmailNotificationIsActive = false, + NotificationThreshold = 1, + NotificationThresholdTime = 1, + NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, + MailFromAddress = string.Empty, + MailToAddress = string.Empty, + }; + this.AddLogTypeConfigInfo(logTypeConfigInfo); + } + + if (LoggingProvider.Instance() != null) + { + try + { + LoggingProvider.Instance().AddLog(logInfo); + } + catch (Exception) + { + if (Globals.Status != Globals.UpgradeStatus.Upgrade) // this may caught exception during upgrade because old logging provider has problem in it. + { + throw; + } + } + } + } + catch (Exception exc) + { + Logger.Error(exc); + + AddLogToFile(logInfo); + } + } + } + + public void AddLogType(string configFile, string fallbackConfigFile) + { + var xmlDoc = new XmlDocument { XmlResolver = null }; + try + { + xmlDoc.Load(configFile); + } + catch (FileNotFoundException exc) + { + Logger.Debug(exc); + xmlDoc.Load(fallbackConfigFile); + } + + var logType = xmlDoc.SelectNodes("/LogConfig/LogTypes/LogType"); + if (logType != null) + { + foreach (XmlNode typeInfo in logType) + { + if (typeInfo.Attributes != null) + { + var objLogTypeInfo = new LogTypeInfo + { + LogTypeKey = typeInfo.Attributes["LogTypeKey"].Value, + LogTypeFriendlyName = typeInfo.Attributes["LogTypeFriendlyName"].Value, + LogTypeDescription = typeInfo.Attributes["LogTypeDescription"].Value, + LogTypeCSSClass = typeInfo.Attributes["LogTypeCSSClass"].Value, + LogTypeOwner = typeInfo.Attributes["LogTypeOwner"].Value, + }; + this.AddLogType(objLogTypeInfo); + } + } + } + + var logTypeConfig = xmlDoc.SelectNodes("/LogConfig/LogTypeConfig"); + if (logTypeConfig != null) + { + foreach (XmlNode typeConfigInfo in logTypeConfig) + { + if (typeConfigInfo.Attributes != null) + { + var logTypeConfigInfo = new LogTypeConfigInfo + { + EmailNotificationIsActive = typeConfigInfo.Attributes["EmailNotificationStatus"].Value == "On", + KeepMostRecent = typeConfigInfo.Attributes["KeepMostRecent"].Value, + LoggingIsActive = typeConfigInfo.Attributes["LoggingStatus"].Value == "On", + LogTypeKey = typeConfigInfo.Attributes["LogTypeKey"].Value, + 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), + NotificationThresholdTimeType = + (LogTypeConfigInfo.NotificationThresholdTimeTypes)Enum.Parse(typeof(LogTypeConfigInfo.NotificationThresholdTimeTypes), typeConfigInfo.Attributes["NotificationThresholdTimeType"].Value), + }; + this.AddLogTypeConfigInfo(logTypeConfigInfo); + } + } + } + } protected override Func GetFactory() { @@ -152,154 +300,6 @@ private static void WriteLog(string filePath, string message) LockLog.ExitWriteLock(); } } - - public void AddLog(LogInfo logInfo) - { - if (Globals.Status == Globals.UpgradeStatus.Install) - { - Logger.Info(logInfo); - } - else - { - try - { - logInfo.LogCreateDate = DateTime.Now; - logInfo.LogServerName = Globals.ServerName; - if (string.IsNullOrEmpty(logInfo.LogServerName)) - { - logInfo.LogServerName = "NA"; - } - - if (string.IsNullOrEmpty(logInfo.LogUserName)) - { - if (HttpContext.Current != null) - { - if (HttpContext.Current.Request.IsAuthenticated) - { - logInfo.LogUserName = UserController.Instance.GetCurrentUserInfo().Username; - } - } - } - - // Get portal name if name isn't set - if (logInfo.LogPortalID != Null.NullInteger && string.IsNullOrEmpty(logInfo.LogPortalName)) - { - logInfo.LogPortalName = PortalController.Instance.GetPortal(logInfo.LogPortalID).PortalName; - } - - // Check if Log Type exists - if (!this.GetLogTypeInfoDictionary().ContainsKey(logInfo.LogTypeKey)) - { - // Add new Log Type - var logType = new LogTypeInfo() - { - LogTypeKey = logInfo.LogTypeKey, - LogTypeFriendlyName = logInfo.LogTypeKey, - LogTypeOwner = "DotNetNuke.Logging.EventLogType", - LogTypeCSSClass = "GeneralAdminOperation", - LogTypeDescription = string.Empty, - }; - this.AddLogType(logType); - - var logTypeConfigInfo = new LogTypeConfigInfo() - { - LogTypeKey = logInfo.LogTypeKey, - LogTypePortalID = "*", - LoggingIsActive = false, - KeepMostRecent = "-1", - EmailNotificationIsActive = false, - NotificationThreshold = 1, - NotificationThresholdTime = 1, - NotificationThresholdTimeType = LogTypeConfigInfo.NotificationThresholdTimeTypes.Seconds, - MailFromAddress = string.Empty, - MailToAddress = string.Empty, - }; - this.AddLogTypeConfigInfo(logTypeConfigInfo); - } - - if (LoggingProvider.Instance() != null) - { - try - { - LoggingProvider.Instance().AddLog(logInfo); - } - catch (Exception) - { - if (Globals.Status != Globals.UpgradeStatus.Upgrade) // this may caught exception during upgrade because old logging provider has problem in it. - { - throw; - } - } - } - } - catch (Exception exc) - { - Logger.Error(exc); - - AddLogToFile(logInfo); - } - } - } - - public void AddLogType(string configFile, string fallbackConfigFile) - { - var xmlDoc = new XmlDocument { XmlResolver = null }; - try - { - xmlDoc.Load(configFile); - } - catch (FileNotFoundException exc) - { - Logger.Debug(exc); - xmlDoc.Load(fallbackConfigFile); - } - - var logType = xmlDoc.SelectNodes("/LogConfig/LogTypes/LogType"); - if (logType != null) - { - foreach (XmlNode typeInfo in logType) - { - if (typeInfo.Attributes != null) - { - var objLogTypeInfo = new LogTypeInfo - { - LogTypeKey = typeInfo.Attributes["LogTypeKey"].Value, - LogTypeFriendlyName = typeInfo.Attributes["LogTypeFriendlyName"].Value, - LogTypeDescription = typeInfo.Attributes["LogTypeDescription"].Value, - LogTypeCSSClass = typeInfo.Attributes["LogTypeCSSClass"].Value, - LogTypeOwner = typeInfo.Attributes["LogTypeOwner"].Value, - }; - this.AddLogType(objLogTypeInfo); - } - } - } - - var logTypeConfig = xmlDoc.SelectNodes("/LogConfig/LogTypeConfig"); - if (logTypeConfig != null) - { - foreach (XmlNode typeConfigInfo in logTypeConfig) - { - if (typeConfigInfo.Attributes != null) - { - var logTypeConfigInfo = new LogTypeConfigInfo - { - EmailNotificationIsActive = typeConfigInfo.Attributes["EmailNotificationStatus"].Value == "On", - KeepMostRecent = typeConfigInfo.Attributes["KeepMostRecent"].Value, - LoggingIsActive = typeConfigInfo.Attributes["LoggingStatus"].Value == "On", - LogTypeKey = typeConfigInfo.Attributes["LogTypeKey"].Value, - 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), - NotificationThresholdTimeType = - (LogTypeConfigInfo.NotificationThresholdTimeTypes)Enum.Parse(typeof(LogTypeConfigInfo.NotificationThresholdTimeTypes), typeConfigInfo.Attributes["NotificationThresholdTimeType"].Value), - }; - this.AddLogTypeConfigInfo(logTypeConfigInfo); - } - } - } - } public void AddLogType(LogTypeInfo logType) { diff --git a/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs index 16881333fc7..8e7a814232f 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs @@ -61,6 +61,27 @@ public LogInfo(string content) public string LogConfigID { get; set; } public ExceptionInfo Exception { get; set; } + + public static bool IsSystemType(string PropName) + { + switch (PropName) + { + case "LogGUID": + case "LogFileID": + case "LogTypeKey": + case "LogCreateDate": + case "LogCreateDateNum": + case "LogPortalID": + case "LogPortalName": + case "LogUserID": + case "LogUserName": + case "BypassBuffering": + case "LogServerName": + return true; + } + + return false; + } public void AddProperty(string PropertyName, string PropertyValue) { @@ -174,27 +195,6 @@ public void ReadXml(XmlReader reader) } } - public static bool IsSystemType(string PropName) - { - switch (PropName) - { - case "LogGUID": - case "LogFileID": - case "LogTypeKey": - case "LogCreateDate": - case "LogCreateDateNum": - case "LogPortalID": - case "LogPortalName": - case "LogUserID": - case "LogUserName": - case "BypassBuffering": - case "LogServerName": - return true; - } - - return false; - } - public string Serialize() { var settings = new XmlWriterSettings(); diff --git a/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs index 6b44e519f02..0ef91402ed4 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs @@ -11,6 +11,8 @@ namespace DotNetNuke.Services.Log.EventLog [Serializable] public class LogTypeConfigInfo : LogTypeInfo { + private string _mailFromAddress; + public enum NotificationThresholdTimeTypes { None = 0, @@ -19,8 +21,6 @@ public enum NotificationThresholdTimeTypes Hours = 3, Days = 4, } - - private string _mailFromAddress; public DateTime StartDateTime { diff --git a/DNN Platform/Library/Services/Mail/Mail.cs b/DNN Platform/Library/Services/Mail/Mail.cs index e14d7a9e6f6..be93f07def0 100644 --- a/DNN Platform/Library/Services/Mail/Mail.cs +++ b/DNN Platform/Library/Services/Mail/Mail.cs @@ -25,6 +25,27 @@ namespace DotNetNuke.Services.Mail public class Mail { private static readonly Regex SmtpServerRegex = new Regex("^[^:]+(:[0-9]{1,5})?$", RegexOptions.Compiled); + + public static string ConvertToText(string sHTML) + { + var formattedHtml = HtmlUtils.FormatText(sHTML, true); + var styleLessHtml = HtmlUtils.RemoveInlineStyle(formattedHtml); + return HtmlUtils.StripTags(styleLessHtml, true); + } + + public static bool IsValidEmailAddress(string Email, int portalid) + { + string pattern = Null.NullString; + + // During install Wizard we may not have a valid PortalID + if (portalid != Null.NullInteger) + { + pattern = Convert.ToString(UserController.GetUserSettings(portalid)["Security_EmailValidation"]); + } + + pattern = string.IsNullOrEmpty(pattern) ? Globals.glbEmailRegEx : pattern; + return Regex.Match(Email, pattern).Success; + } private static string SendMailInternal(MailMessage mailMessage, string subject, string body, MailPriority priority, MailFormat bodyFormat, Encoding bodyEncoding, IEnumerable attachments, @@ -176,27 +197,6 @@ private static string SendMailInternal(MailMessage mailMessage, string subject, return retValue; } - - public static string ConvertToText(string sHTML) - { - var formattedHtml = HtmlUtils.FormatText(sHTML, true); - var styleLessHtml = HtmlUtils.RemoveInlineStyle(formattedHtml); - return HtmlUtils.StripTags(styleLessHtml, true); - } - - public static bool IsValidEmailAddress(string Email, int portalid) - { - string pattern = Null.NullString; - - // During install Wizard we may not have a valid PortalID - if (portalid != Null.NullInteger) - { - pattern = Convert.ToString(UserController.GetUserSettings(portalid)["Security_EmailValidation"]); - } - - pattern = string.IsNullOrEmpty(pattern) ? Globals.glbEmailRegEx : pattern; - return Regex.Match(Email, pattern).Success; - } public static void SendEmail(string fromAddress, string toAddress, string subject, string body) { diff --git a/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs b/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs index 698ab9d86e6..829b1428f84 100644 --- a/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs +++ b/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs @@ -40,6 +40,11 @@ public class SendTokenizedBulkEmail : IDisposable { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SendTokenizedBulkEmail)); + // ReSharper restore InconsistentNaming + private readonly List _addressedRoles = new List(); + private readonly List _addressedUsers = new List(); + private readonly List _attachments = new List(); + /// /// Addressing Methods (personalized or hidden). /// @@ -51,11 +56,6 @@ public enum AddressMethods Send_BCC = 2, Send_Relay = 3, } - - // ReSharper restore InconsistentNaming - private readonly List _addressedRoles = new List(); - private readonly List _addressedUsers = new List(); - private readonly List _attachments = new List(); private UserInfo _replyToUser; private bool _smtpEnableSSL; private TokenReplace _tokenReplace; @@ -98,6 +98,11 @@ public SendTokenizedBulkEmail(List addressedRoles, List addres this.SuppressTokenReplace = this.SuppressTokenReplace; this.Initialize(); } + + ~SendTokenizedBulkEmail() + { + this.Dispose(false); + } /// /// Gets or sets priority of emails to be sent. @@ -176,18 +181,18 @@ public UserInfo ReplyTo { this._replyToUser = value; } - } - - /// Gets or sets a value indicating whether shall duplicate email addresses be ignored? (default value: false). - /// Duplicate Users (e.g. from multiple role selections) will always be ignored. - public bool RemoveDuplicates { get; set; } - - /// Gets or sets a value indicating whether shall automatic TokenReplace be prohibited?. - /// default value: false. - public bool SuppressTokenReplace { get; set; } - - /// Gets or sets a value indicating whether shall List of recipients appended to confirmation report?. - /// enabled by default. + } + + /// Gets or sets a value indicating whether shall duplicate email addresses be ignored? (default value: false). + /// Duplicate Users (e.g. from multiple role selections) will always be ignored. + public bool RemoveDuplicates { get; set; } + + /// Gets or sets a value indicating whether shall automatic TokenReplace be prohibited?. + /// default value: false. + public bool SuppressTokenReplace { get; set; } + + /// Gets or sets a value indicating whether shall List of recipients appended to confirmation report?. + /// enabled by default. public bool ReportRecipients { get; set; } public string RelayEmailAddress @@ -205,6 +210,35 @@ public string RelayEmailAddress public string[] LanguageFilter { get; set; } + /// Specify SMTP server to be used. + /// name of the SMTP server. + /// authentication string (0: anonymous, 1: basic, 2: NTLM). + /// username to log in SMTP server. + /// password to log in SMTP server. + /// SSL used to connect tp SMTP server. + /// always true. + /// if not called, values will be taken from host settings. + public bool SetSMTPServer(string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) + { + this.EnsureNotDisposed(); + + this._smtpServer = smtpServer; + this._smtpAuthenticationMethod = smtpAuthentication; + this._smtpUsername = smtpUsername; + this._smtpPassword = smtpPassword; + this._smtpEnableSSL = smtpEnableSSL; + return true; + } + + /// Add a single attachment file to the email. + /// path to file to attach. + /// only local stored files can be added with a path. + public void AddAttachment(string localPath) + { + this.EnsureNotDisposed(); + this._attachments.Add(new Attachment(localPath)); + } + /// internal method to initialize used objects, depending on parameters of construct method. private void Initialize() { @@ -348,35 +382,6 @@ private List LoadAttachments() return attachments; } - - /// Specify SMTP server to be used. - /// name of the SMTP server. - /// authentication string (0: anonymous, 1: basic, 2: NTLM). - /// username to log in SMTP server. - /// password to log in SMTP server. - /// SSL used to connect tp SMTP server. - /// always true. - /// if not called, values will be taken from host settings. - public bool SetSMTPServer(string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) - { - this.EnsureNotDisposed(); - - this._smtpServer = smtpServer; - this._smtpAuthenticationMethod = smtpAuthentication; - this._smtpUsername = smtpUsername; - this._smtpPassword = smtpPassword; - this._smtpEnableSSL = smtpEnableSSL; - return true; - } - - /// Add a single attachment file to the email. - /// path to file to attach. - /// only local stored files can be added with a path. - public void AddAttachment(string localPath) - { - this.EnsureNotDisposed(); - this._attachments.Add(new Attachment(localPath)); - } public void AddAttachment(Stream contentStream, ContentType contentType) { @@ -629,14 +634,6 @@ public void Send() this.EnsureNotDisposed(); this.SendMails(); } - - private void EnsureNotDisposed() - { - if (this._isDisposed) - { - throw new ObjectDisposedException("SharedDictionary"); - } - } public void Dispose() { @@ -661,10 +658,13 @@ protected virtual void Dispose(bool disposing) // get rid of unmanaged resources } } - - ~SendTokenizedBulkEmail() + + private void EnsureNotDisposed() { - this.Dispose(false); + if (this._isDisposed) + { + throw new ObjectDisposedException("SharedDictionary"); + } } } } diff --git a/DNN Platform/Library/Services/Messaging/Data/Message.cs b/DNN Platform/Library/Services/Messaging/Data/Message.cs index 97e70221bca..8141202eea8 100644 --- a/DNN Platform/Library/Services/Messaging/Data/Message.cs +++ b/DNN Platform/Library/Services/Messaging/Data/Message.cs @@ -37,15 +37,15 @@ public class Message : IHydratable private bool _allowReply; private bool _skipInbox; + private Guid _EmailSchedulerInstance; + private DateTime _EmailSentDate; + public Message() { this.Conversation = Guid.Empty; this.Status = MessageStatusType.Draft; this.MessageDate = DateTime.Now; } - - private Guid _EmailSchedulerInstance; - private DateTime _EmailSentDate; public string FromUserName { @@ -283,6 +283,19 @@ private set this._EmailSchedulerInstance = value; } } + + public int KeyID + { + get + { + return this.MessageID; + } + + set + { + this.MessageID = value; + } + } public Message GetReplyMessage() { @@ -327,18 +340,5 @@ public void Fill(IDataReader dr) // 'Conversation = New Guid(g) } - - public int KeyID - { - get - { - return this.MessageID; - } - - set - { - this.MessageID = value; - } - } } } diff --git a/DNN Platform/Library/Services/Mobile/Redirection.cs b/DNN Platform/Library/Services/Mobile/Redirection.cs index 1fa4e1ddea4..2b999f40065 100644 --- a/DNN Platform/Library/Services/Mobile/Redirection.cs +++ b/DNN Platform/Library/Services/Mobile/Redirection.cs @@ -18,6 +18,9 @@ public class Redirection : IRedirection, IHydratable { private int _id = -1; + [XmlIgnore] + private IList _matchRules; + /// /// Gets or sets redirection's primary key. /// @@ -67,9 +70,6 @@ public int Id [XmlAttribute] public RedirectionType Type { get; set; } - [XmlIgnore] - private IList _matchRules; - /// /// Gets or sets when redirection type is RedirectionType.Other, should use this collection to match the request by capability info. /// diff --git a/DNN Platform/Library/Services/Mobile/RedirectionController.cs b/DNN Platform/Library/Services/Mobile/RedirectionController.cs index 5f6de39ab7c..e565d1aef44 100644 --- a/DNN Platform/Library/Services/Mobile/RedirectionController.cs +++ b/DNN Platform/Library/Services/Mobile/RedirectionController.cs @@ -32,6 +32,14 @@ public class RedirectionController : IRedirectionController private const string MobileSiteUrlCacheKey = "MobileSiteUrl_{0}_{1}"; private const int UrlsCacheTimeout = 60; + private string AllRedirectionsCacheKey + { + get + { + return string.Format(DataCache.RedirectionsCacheKey, "All"); + } + } + /// /// Is Redirection Allowed for the session. Method analyzes the query string for special parameters to enable / disable redirects. /// Cookie is created to temporarily store those parameters so that they remain available till the interactions are active. @@ -168,7 +176,7 @@ public string GetRedirectUrl(string userAgent, int portalId, int currentTabId) checkFurther = true; } - // is child tabs to be included as well + // is child tabs to be included as well else if (redirection.IncludeChildTabs) { // Get all the descendents of the source tab and find out if current tab is in source tab's hierarchy or not. @@ -183,7 +191,7 @@ public string GetRedirectUrl(string userAgent, int portalId, int currentTabId) } } - // redirection is based on portal + // redirection is based on portal else if (redirection.SourceTabId == Null.NullInteger) { checkFurther = true; @@ -702,13 +710,5 @@ private bool DoesCapabilityMatchWithRule(IClientCapability clientCapability, IRe return match; } - - private string AllRedirectionsCacheKey - { - get - { - return string.Format(DataCache.RedirectionsCacheKey, "All"); - } - } } } diff --git a/DNN Platform/Library/Services/ModuleCache/FileProvider.cs b/DNN Platform/Library/Services/ModuleCache/FileProvider.cs index cffdd8e3845..d5eda6af7d7 100644 --- a/DNN Platform/Library/Services/ModuleCache/FileProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/FileProvider.cs @@ -22,14 +22,25 @@ public class FileProvider : ModuleCachingProvider private const string AttribFileExtension = ".attrib.resources"; private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); - private string GenerateCacheKeyHash(int tabModuleId, string cacheKey) + public override string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy) { - byte[] hash = Encoding.ASCII.GetBytes(cacheKey); - using (var sha256 = new SHA256CryptoServiceProvider()) + var cacheKey = new StringBuilder(); + if (varyBy != null) { - hash = sha256.ComputeHash(hash); - return tabModuleId + "_" + this.ByteArrayToString(hash); + SortedDictionary.Enumerator varyByParms = varyBy.GetEnumerator(); + while (varyByParms.MoveNext()) + { + string key = varyByParms.Current.Key.ToLowerInvariant(); + cacheKey.Append(string.Concat(key, "=", varyByParms.Current.Value, "|")); + } } + + return this.GenerateCacheKeyHash(tabModuleId, cacheKey.ToString()); + } + + public override int GetItemCount(int tabModuleId) + { + return GetCachedItemCount(tabModuleId); } private static string GetAttribFileName(int tabModuleId, string cacheKey) @@ -41,6 +52,16 @@ private static int GetCachedItemCount(int tabModuleId) { return Directory.GetFiles(GetCacheFolder(), string.Format("*{0}", DataFileExtension)).Length; } + + private string GenerateCacheKeyHash(int tabModuleId, string cacheKey) + { + byte[] hash = Encoding.ASCII.GetBytes(cacheKey); + using (var sha256 = new SHA256CryptoServiceProvider()) + { + hash = sha256.ComputeHash(hash); + return tabModuleId + "_" + this.ByteArrayToString(hash); + } + } private static string GetCachedOutputFileName(int tabModuleId, string cacheKey) { @@ -68,10 +89,10 @@ private static string GetCacheFolder(int portalId) string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath; - if (! string.IsNullOrEmpty(homeDirectoryMapPath)) + if (!string.IsNullOrEmpty(homeDirectoryMapPath)) { cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\"); - if (! Directory.Exists(cacheFolder)) + if (!Directory.Exists(cacheFolder)) { Directory.CreateDirectory(cacheFolder); } @@ -94,6 +115,11 @@ private static string GetCacheFolder() return GetCacheFolder(portalId); } + private static bool IsPathInApplication(string cacheFolder) + { + return cacheFolder.Contains(Globals.ApplicationMapPath); + } + private bool IsFileExpired(string file) { StreamReader oRead = null; @@ -146,32 +172,6 @@ private void PurgeCache(string folder) } } - private static bool IsPathInApplication(string cacheFolder) - { - return cacheFolder.Contains(Globals.ApplicationMapPath); - } - - public override string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy) - { - var cacheKey = new StringBuilder(); - if (varyBy != null) - { - SortedDictionary.Enumerator varyByParms = varyBy.GetEnumerator(); - while (varyByParms.MoveNext()) - { - string key = varyByParms.Current.Key.ToLowerInvariant(); - cacheKey.Append(string.Concat(key, "=", varyByParms.Current.Value, "|")); - } - } - - return this.GenerateCacheKeyHash(tabModuleId, cacheKey.ToString()); - } - - public override int GetItemCount(int tabModuleId) - { - return GetCachedItemCount(tabModuleId); - } - public override byte[] GetModule(int tabModuleId, string cacheKey) { string cachedModule = GetCachedOutputFileName(tabModuleId, cacheKey); diff --git a/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs b/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs index a51491f91a9..e0ebd4e6157 100644 --- a/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs @@ -16,21 +16,6 @@ public class MemoryProvider : ModuleCachingProvider { private const string cachePrefix = "ModuleCache:"; - private List GetCacheKeys(int tabModuleId) - { - var keys = new List(); - IDictionaryEnumerator CacheEnum = CachingProvider.Instance().GetEnumerator(); - while (CacheEnum.MoveNext()) - { - if (CacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix, "|", tabModuleId.ToString(), "|"))) - { - keys.Add(CacheEnum.Key.ToString()); - } - } - - return keys; - } - public override string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy) { var cacheKey = new StringBuilder(); @@ -50,6 +35,21 @@ public override int GetItemCount(int tabModuleId) return this.GetCacheKeys(tabModuleId).Count; } + private List GetCacheKeys(int tabModuleId) + { + var keys = new List(); + IDictionaryEnumerator CacheEnum = CachingProvider.Instance().GetEnumerator(); + while (CacheEnum.MoveNext()) + { + if (CacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix, "|", tabModuleId.ToString(), "|"))) + { + keys.Add(CacheEnum.Key.ToString()); + } + } + + return keys; + } + public override byte[] GetModule(int tabModuleId, string cacheKey) { return DataCache.GetCache(cacheKey); diff --git a/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs b/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs index 752fcfafea5..56a0fba715f 100644 --- a/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs @@ -28,6 +28,10 @@ public static void RemoveItemFromAllProviders(int tabModuleId) kvp.Value.Remove(tabModuleId); } } + + public abstract string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy); + + public abstract int GetItemCount(int tabModuleId); protected string ByteArrayToString(byte[] arrInput) { @@ -40,10 +44,6 @@ protected string ByteArrayToString(byte[] arrInput) return sOutput.ToString(); } - - public abstract string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy); - - public abstract int GetItemCount(int tabModuleId); public abstract byte[] GetModule(int tabModuleId, string cacheKey); diff --git a/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs index 7e993b71aad..6a6029ee462 100644 --- a/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs @@ -97,7 +97,7 @@ public override void Flush() return; } - if ( this._captureStream != null) + if (this._captureStream != null) { this._captureStream.Flush(); } @@ -111,7 +111,7 @@ public override void Write(byte[] buffer, int offset, int count) return; } - if ( this._captureStream != null) + if (this._captureStream != null) { this._captureStream.Write(buffer, offset, count); } @@ -131,14 +131,6 @@ public override void SetLength(long value) { throw new NotSupportedException(); } - - protected virtual void AddItemToCache(int itemId, string output) - { - } - - protected virtual void RemoveItemFromCache(int itemId) - { - } public virtual byte[] StopFiltering(int itemId, bool deleteData) { @@ -147,7 +139,7 @@ public virtual byte[] StopFiltering(int itemId, bool deleteData) return null; } - if ( this.CaptureStream != null) + if (this.CaptureStream != null) { this.CaptureStream.Position = 0; using (var reader = new StreamReader(this.CaptureStream, Encoding.Default)) @@ -167,5 +159,13 @@ public virtual byte[] StopFiltering(int itemId, bool deleteData) return null; } + + protected virtual void AddItemToCache(int itemId, string output) + { + } + + protected virtual void RemoveItemFromCache(int itemId) + { + } } } diff --git a/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs b/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs index 138ffc99516..50a4b907126 100644 --- a/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs @@ -15,6 +15,16 @@ namespace DotNetNuke.Services.OutputCache public abstract class OutputCachingProvider { + public static Dictionary GetProviderList() + { + return ComponentFactory.GetComponents(); + } + + public static OutputCachingProvider Instance(string FriendlyName) + { + return ComponentFactory.GetComponent(FriendlyName); + } + protected string ByteArrayToString(byte[] arrInput) { int i = 0; @@ -58,16 +68,6 @@ protected void WriteStreamAsText(HttpContext context, Stream stream, long offset context.Response.Output.Write(output); } } - - public static Dictionary GetProviderList() - { - return ComponentFactory.GetComponents(); - } - - public static OutputCachingProvider Instance(string FriendlyName) - { - return ComponentFactory.GetComponent(FriendlyName); - } public static void RemoveItemFromAllProviders(int tabId) { diff --git a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs index d9da08e0673..6a2fcfaba16 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs @@ -34,7 +34,7 @@ public override byte[] GetOutput(int tabId, string cacheKey) } else { - if (! dr.Read()) + if (!dr.Read()) { return null; } @@ -89,7 +89,7 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex } else { - if (! dr.Read()) + if (!dr.Read()) { return false; } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs index 28a29ef74c8..6c620f5e368 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs @@ -26,6 +26,38 @@ public class FileProvider : OutputCachingProvider private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); + public override int GetItemCount(int tabId) + { + return GetCachedItemCount(tabId); + } + + public override byte[] GetOutput(int tabId, string cacheKey) + { + string cachedOutput = GetCachedOutputFileName(tabId, cacheKey); + if (!File.Exists(cachedOutput)) + { + return null; + } + + var fInfo = new FileInfo(cachedOutput); + long numBytes = fInfo.Length; + using (var fStream = new FileStream(cachedOutput, FileMode.Open, FileAccess.Read)) + using (var br = new BinaryReader(fStream)) + { + return br.ReadBytes(Convert.ToInt32(numBytes)); + } + } + + internal static string GetAttribFileName(int tabId, string cacheKey) + { + return string.Concat(GetCacheFolder(), cacheKey, AttribFileExtension); + } + + internal static int GetCachedItemCount(int tabId) + { + return Directory.GetFiles(GetCacheFolder(), $"{tabId}_*{DataFileExtension}").Length; + } + private static string GetCacheFolder() { int portalId = PortalController.Instance.GetCurrentPortalSettings().PortalId; @@ -48,10 +80,10 @@ private static string GetCacheFolder(int portalId) string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath; - if (! string.IsNullOrEmpty(homeDirectoryMapPath)) + if (!string.IsNullOrEmpty(homeDirectoryMapPath)) { cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\"); - if (! Directory.Exists(cacheFolder)) + if (!Directory.Exists(cacheFolder)) { Directory.CreateDirectory(cacheFolder); } @@ -98,7 +130,7 @@ private void PurgeCache(string folder) int i = 0; foreach (string file in Directory.GetFiles(folder, "*.resources")) { - if (! FileSystemUtils.DeleteFileWithWait(file, 100, 200)) + if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200)) { filesNotDeleted.Append(file + ";"); } @@ -118,16 +150,6 @@ private void PurgeCache(string folder) Exceptions.Exceptions.LogException(ex); } } - - internal static string GetAttribFileName(int tabId, string cacheKey) - { - return string.Concat(GetCacheFolder(), cacheKey, AttribFileExtension); - } - - internal static int GetCachedItemCount(int tabId) - { - return Directory.GetFiles(GetCacheFolder(), $"{tabId}_*{DataFileExtension}").Length; - } internal static string GetCachedOutputFileName(int tabId, string cacheKey) { @@ -138,28 +160,6 @@ internal static string GetTempFileName(int tabId, string cacheKey) { return string.Concat(GetCacheFolder(), cacheKey, TempFileExtension); } - - public override int GetItemCount(int tabId) - { - return GetCachedItemCount(tabId); - } - - public override byte[] GetOutput(int tabId, string cacheKey) - { - string cachedOutput = GetCachedOutputFileName(tabId, cacheKey); - if (! File.Exists(cachedOutput)) - { - return null; - } - - var fInfo = new FileInfo(cachedOutput); - long numBytes = fInfo.Length; - using (var fStream = new FileStream(cachedOutput, FileMode.Open, FileAccess.Read)) - using (var br = new BinaryReader(fStream)) - { - return br.ReadBytes(Convert.ToInt32(numBytes)); - } - } public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVaryByCount, Stream responseFilter, string cacheKey, TimeSpan cacheDuration) { @@ -169,7 +169,7 @@ public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVa public override void PurgeCache(int portalId) { string cacheFolder = GetCacheFolder(portalId); - if (! string.IsNullOrEmpty(cacheFolder)) + if (!string.IsNullOrEmpty(cacheFolder)) { this.PurgeCache(cacheFolder); } @@ -181,14 +181,14 @@ public override void PurgeExpiredItems(int portalId) int i = 0; string cacheFolder = GetCacheFolder(portalId); - if (! string.IsNullOrEmpty(cacheFolder)) + if (!string.IsNullOrEmpty(cacheFolder)) { foreach (string file in Directory.GetFiles(cacheFolder, "*" + AttribFileExtension)) { if (this.IsFileExpired(file)) { string fileToDelete = file.Replace(AttribFileExtension, DataFileExtension); - if (! FileSystemUtils.DeleteFileWithWait(fileToDelete, 100, 200)) + if (!FileSystemUtils.DeleteFileWithWait(fileToDelete, 100, 200)) { filesNotDeleted.Append(fileToDelete + ";"); } @@ -217,11 +217,11 @@ public override void Remove(int tabId) int i = 0; string cacheFolder = GetCacheFolder(portals[tabId]); - if (! string.IsNullOrEmpty(cacheFolder)) + if (!string.IsNullOrEmpty(cacheFolder)) { foreach (string file in Directory.GetFiles(cacheFolder, string.Concat(tabId, "_*.*"))) { - if (! FileSystemUtils.DeleteFileWithWait(file, 100, 200)) + if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200)) { filesNotDeleted.Append(string.Concat(file, ";")); } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs index 00532883829..272b68e872c 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs @@ -43,15 +43,15 @@ internal static string CachePrefix } } - private string GetCacheKey(string CacheKey) + public override string GenerateCacheKey(int tabId, System.Collections.Specialized.StringCollection includeVaryByKeys, System.Collections.Specialized.StringCollection excludeVaryByKeys, SortedDictionary varyBy) { - if (string.IsNullOrEmpty(CacheKey)) - { - throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); - } - - return string.Concat(cachePrefix, CacheKey); - } + return this.GetCacheKey(base.GenerateCacheKey(tabId, includeVaryByKeys, excludeVaryByKeys, varyBy)); + } + + public override int GetItemCount(int tabId) + { + return GetCacheKeys(tabId).Count(); + } internal static List GetCacheKeys() { @@ -83,15 +83,15 @@ internal static List GetCacheKeys(int tabId) return keys; } - public override string GenerateCacheKey(int tabId, System.Collections.Specialized.StringCollection includeVaryByKeys, System.Collections.Specialized.StringCollection excludeVaryByKeys, SortedDictionary varyBy) - { - return this.GetCacheKey(base.GenerateCacheKey(tabId, includeVaryByKeys, excludeVaryByKeys, varyBy)); - } - - public override int GetItemCount(int tabId) + private string GetCacheKey(string CacheKey) { - return GetCacheKeys(tabId).Count(); - } + if (string.IsNullOrEmpty(CacheKey)) + { + throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); + } + + return string.Concat(cachePrefix, CacheKey); + } public override byte[] GetOutput(int tabId, string cacheKey) { diff --git a/DNN Platform/Library/Services/Personalization/Personalization.cs b/DNN Platform/Library/Services/Personalization/Personalization.cs index b1219810d70..c13203b9a87 100644 --- a/DNN Platform/Library/Services/Personalization/Personalization.cs +++ b/DNN Platform/Library/Services/Personalization/Personalization.cs @@ -12,6 +12,29 @@ namespace DotNetNuke.Services.Personalization public class Personalization { + /// + /// load users profile and extract value base on naming container and key. + /// + /// Container for related set of values. + /// Individual profile key. + /// + public static object GetProfile(string namingContainer, string key) + { + return GetProfile(LoadProfile(), namingContainer, key); + } + + /// + /// extract value base on naming container and key from PersonalizationInfo object. + /// + /// Object containing user personalization info. + /// Container for related set of values. + /// Individual profile key. + /// + public static object GetProfile(PersonalizationInfo personalization, string namingContainer, string key) + { + return personalization != null ? personalization.Profile[namingContainer + ":" + key] : string.Empty; + } + private static PersonalizationInfo LoadProfile() { HttpContext context = HttpContext.Current; @@ -37,29 +60,6 @@ private static PersonalizationInfo LoadProfile() return personalization; } - - /// - /// load users profile and extract value base on naming container and key. - /// - /// Container for related set of values. - /// Individual profile key. - /// - public static object GetProfile(string namingContainer, string key) - { - return GetProfile(LoadProfile(), namingContainer, key); - } - - /// - /// extract value base on naming container and key from PersonalizationInfo object. - /// - /// Object containing user personalization info. - /// Container for related set of values. - /// Individual profile key. - /// - public static object GetProfile(PersonalizationInfo personalization, string namingContainer, string key) - { - return personalization != null ? personalization.Profile[namingContainer + ":" + key] : string.Empty; - } /// /// load users profile and extract secure value base on naming container and key. diff --git a/DNN Platform/Library/Services/Personalization/PersonalizationController.cs b/DNN Platform/Library/Services/Personalization/PersonalizationController.cs index 229eb473a6d..cf43f8cba2d 100644 --- a/DNN Platform/Library/Services/Personalization/PersonalizationController.cs +++ b/DNN Platform/Library/Services/Personalization/PersonalizationController.cs @@ -37,11 +37,11 @@ public PersonalizationInfo LoadProfile(int userId, int portalId) 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); - profileData = CBO.GetCachedObject( - new CacheItemArgs(cacheKey, DataCache.UserPersonalizationCacheTimeout, - DataCache.UserPersonalizationCachePriority, portalId, userId), GetCachedUserPersonalizationCallback); + { + var cacheKey = string.Format(DataCache.UserPersonalizationCacheKey, portalId, userId); + profileData = CBO.GetCachedObject( + new CacheItemArgs(cacheKey, DataCache.UserPersonalizationCacheTimeout, + DataCache.UserPersonalizationCachePriority, portalId, userId), GetCachedUserPersonalizationCallback); } else { @@ -68,6 +68,18 @@ public PersonalizationInfo LoadProfile(int userId, int portalId) return personalization; } + public void SaveProfile(PersonalizationInfo personalization) + { + this.SaveProfile(personalization, personalization.UserId, personalization.PortalId); + } + + // default implementation relies on HTTPContext + public void SaveProfile(HttpContext httpContext, int userId, int portalId) + { + var objPersonalization = (PersonalizationInfo)httpContext.Items["Personalization"]; + this.SaveProfile(objPersonalization, userId, portalId); + } + private static object GetCachedUserPersonalizationCallback(CacheItemArgs cacheItemArgs) { var portalId = (int)cacheItemArgs.ParamList[0]; @@ -98,18 +110,6 @@ private static object GetCachedUserPersonalizationCallback(CacheItemArgs cacheIt return returnValue; } - public void SaveProfile(PersonalizationInfo personalization) - { - this.SaveProfile(personalization, personalization.UserId, personalization.PortalId); - } - - // default implementation relies on HTTPContext - public void SaveProfile(HttpContext httpContext, int userId, int portalId) - { - var objPersonalization = (PersonalizationInfo)httpContext.Items["Personalization"]; - this.SaveProfile(objPersonalization, userId, portalId); - } - // override allows for manipulation of PersonalizationInfo outside of HTTPContext public void SaveProfile(PersonalizationInfo personalization, int userId, int portalId) { diff --git a/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs b/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs index 76e9c9efe83..ca6fbb84911 100644 --- a/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs +++ b/DNN Platform/Library/Services/Registration/RegistrationProfileController.cs @@ -39,6 +39,11 @@ public IEnumerable Search(int portalId, string searchTerm) return results; } + protected override Func GetFactory() + { + return () => new RegistrationProfileController(); + } + private void AddProperty(List results, string field, string searchTerm) { if (field.ToLowerInvariant().Contains(searchTerm.ToLowerInvariant().Trim())) @@ -46,10 +51,5 @@ private void AddProperty(List results, string field, string searchTerm) results.Add(field); } } - - protected override Func GetFactory() - { - return () => new RegistrationProfileController(); - } } } diff --git a/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs b/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs index 2e6b968becb..d64380637d8 100644 --- a/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs +++ b/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs @@ -16,17 +16,19 @@ 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; + // '''''''''''''''''''''''''''''''''''''''''''''''''' // This class represents a process group for // our threads to run in. // '''''''''''''''''''''''''''''''''''''''''''''''''' public delegate void CompletedEventHandler(); - - private static int numberOfProcessesInQueue; - private static int numberOfProcesses; - private static int processesCompleted; private static int ticksElapsed; + public event CompletedEventHandler Completed; + private static int GetTicksElapsed { get @@ -51,8 +53,6 @@ private static int GetProcessesInQueue } } - public event CompletedEventHandler Completed; - public void Run(ScheduleHistoryItem objScheduleHistoryItem) { IServiceScope serviceScope = null; @@ -154,22 +154,6 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) } } - private SchedulerClient GetSchedulerClient(IServiceProvider services, string strProcess, ScheduleHistoryItem objScheduleHistoryItem) - { - // This is a method to encapsulate returning - // an object whose class inherits SchedulerClient. - Type t = BuildManager.GetType(strProcess, true, true); - return (SchedulerClient)ActivatorUtilities.CreateInstance(services, t, objScheduleHistoryItem); - } - - // This subroutine is callback for Threadpool.QueueWorkItem. This is the necessary - // subroutine signature for QueueWorkItem, and Run() is proper for creating a Thread - // so the two subroutines cannot be combined, so instead just call Run from here. - private void RunPooledThread(object objScheduleHistoryItem) - { - this.Run((ScheduleHistoryItem)objScheduleHistoryItem); - } - // Add a queue request to Threadpool with a // callback to RunPooledThread which calls Run() public void AddQueueUserWorkItem(ScheduleItem s) @@ -190,5 +174,21 @@ public void AddQueueUserWorkItem(ScheduleItem s) Exceptions.Exceptions.ProcessSchedulerException(exc); } } + + private SchedulerClient GetSchedulerClient(IServiceProvider services, string strProcess, ScheduleHistoryItem objScheduleHistoryItem) + { + // This is a method to encapsulate returning + // an object whose class inherits SchedulerClient. + Type t = BuildManager.GetType(strProcess, true, true); + return (SchedulerClient)ActivatorUtilities.CreateInstance(services, t, objScheduleHistoryItem); + } + + // This subroutine is callback for Threadpool.QueueWorkItem. This is the necessary + // subroutine signature for QueueWorkItem, and Run() is proper for creating a Thread + // so the two subroutines cannot be combined, so instead just call Run from here. + private void RunPooledThread(object objScheduleHistoryItem) + { + this.Run((ScheduleHistoryItem)objScheduleHistoryItem); + } } } diff --git a/DNN Platform/Library/Services/Scheduling/Scheduler.cs b/DNN Platform/Library/Services/Scheduling/Scheduler.cs index bc1f2214865..2102667baa0 100644 --- a/DNN Platform/Library/Services/Scheduling/Scheduler.cs +++ b/DNN Platform/Library/Services/Scheduling/Scheduler.cs @@ -24,6 +24,11 @@ internal static class Scheduler internal static class CoreScheduler { + // If KeepRunning gets switched to false, + // the scheduler stops running. + public static bool KeepThreadAlive = true; + public static bool KeepRunning = true; + // This is the heart of the scheduler mechanism. // This class manages running new events according // to the schedule. @@ -63,11 +68,6 @@ internal static class CoreScheduler private static readonly ReaderWriterLockSlim StatusLock = new ReaderWriterLockSlim(); private static ScheduleStatus _status = ScheduleStatus.STOPPED; - // If KeepRunning gets switched to false, - // the scheduler stops running. - public static bool KeepThreadAlive = true; - public static bool KeepRunning = true; - static CoreScheduler() { var lockStrategy = new ReaderWriterLockStrategy(LockRecursionPolicy.SupportsRecursion); @@ -76,6 +76,8 @@ static CoreScheduler() ScheduleInProgress = new SharedList(lockStrategy); } + private delegate void AddToScheduleInProgressDelegate(ScheduleHistoryItem item); + /// /// Gets tracks how many threads we have free to work with at any given time. /// @@ -87,6 +89,85 @@ public static int FreeThreads } } + public static ScheduleHistoryItem AddScheduleHistory(ScheduleHistoryItem scheduleHistoryItem) + { + try + { + int scheduleHistoryID = SchedulingController.AddScheduleHistory(scheduleHistoryItem); + scheduleHistoryItem.ScheduleHistoryID = scheduleHistoryID; + } + catch (Exception exc) + { + Exceptions.Exceptions.ProcessSchedulerException(exc); + } + + return scheduleHistoryItem; + } + + /// + /// Adds an item to the collection of schedule items in queue. + /// + /// + /// Thread Safe. + public static void AddToScheduleQueue(ScheduleHistoryItem scheduleHistoryItem) + { + if (!ScheduleQueueContains(scheduleHistoryItem)) + { + try + { + // objQueueReadWriteLock.EnterWriteLock(WriteTimeout) + using (ScheduleQueue.GetWriteLock(LockTimeout)) + { + // Do a second check just in case + if (!ScheduleQueueContains(scheduleHistoryItem) && + !IsInProgress(scheduleHistoryItem)) + { + // It is safe for this thread to read or write + // from the shared resource. + ScheduleQueue.Add(scheduleHistoryItem); + } + } + } + catch (ApplicationException ex) + { + // The writer lock request timed out. + Interlocked.Increment(ref _writerTimeouts); + Exceptions.Exceptions.LogException(ex); + } + } + } + + internal static bool IsInQueue(ScheduleItem scheduleItem) + { + try + { + using (ScheduleQueue.GetReadLock(LockTimeout)) + { + return ScheduleQueue.Any(si => si.ScheduleID == scheduleItem.ScheduleID); + } + } + catch (ApplicationException) + { + // The reader lock request timed out. + Interlocked.Increment(ref _readerTimeouts); + return false; + } + } + + internal static ServerInfo GetServer(string executingServer) + { + try + { + return ServerController.GetServers().FirstOrDefault( + s => ServerController.GetServerName(s).Equals(executingServer, StringComparison.OrdinalIgnoreCase) && s.Enabled); + } + catch (Exception) + { + // catches edge-case where schedule runs before webserver registration + return null; + } + } + /// /// adds an item to the collection of schedule items in progress. /// @@ -94,13 +175,13 @@ public static int FreeThreads /// Thread Safe. private static void AddToScheduleInProgress(ScheduleHistoryItem scheduleHistoryItem) { - if (! ScheduleInProgressContains(scheduleHistoryItem)) + if (!ScheduleInProgressContains(scheduleHistoryItem)) { try { using (ScheduleInProgress.GetWriteLock(LockTimeout)) { - if (! ScheduleInProgressContains(scheduleHistoryItem)) + if (!ScheduleInProgressContains(scheduleHistoryItem)) { ScheduleInProgress.Add(scheduleHistoryItem); } @@ -228,87 +309,6 @@ private static bool ScheduleQueueContains(ScheduleItem objScheduleItem) return false; } } - - internal static bool IsInQueue(ScheduleItem scheduleItem) - { - try - { - using (ScheduleQueue.GetReadLock(LockTimeout)) - { - return ScheduleQueue.Any(si => si.ScheduleID == scheduleItem.ScheduleID); - } - } - catch (ApplicationException) - { - // The reader lock request timed out. - Interlocked.Increment(ref _readerTimeouts); - return false; - } - } - - internal static ServerInfo GetServer(string executingServer) - { - try - { - return ServerController.GetServers().FirstOrDefault( - s => ServerController.GetServerName(s).Equals(executingServer, StringComparison.OrdinalIgnoreCase) && s.Enabled); - } - catch (Exception) - { - // catches edge-case where schedule runs before webserver registration - return null; - } - } - - public static ScheduleHistoryItem AddScheduleHistory(ScheduleHistoryItem scheduleHistoryItem) - { - try - { - int scheduleHistoryID = SchedulingController.AddScheduleHistory(scheduleHistoryItem); - scheduleHistoryItem.ScheduleHistoryID = scheduleHistoryID; - } - catch (Exception exc) - { - Exceptions.Exceptions.ProcessSchedulerException(exc); - } - - return scheduleHistoryItem; - } - - /// - /// Adds an item to the collection of schedule items in queue. - /// - /// - /// Thread Safe. - public static void AddToScheduleQueue(ScheduleHistoryItem scheduleHistoryItem) - { - if (!ScheduleQueueContains(scheduleHistoryItem)) - { - try - { - // objQueueReadWriteLock.EnterWriteLock(WriteTimeout) - using (ScheduleQueue.GetWriteLock(LockTimeout)) - { - // Do a second check just in case - if (!ScheduleQueueContains(scheduleHistoryItem) && - !IsInProgress(scheduleHistoryItem)) - { - // It is safe for this thread to read or write - // from the shared resource. - ScheduleQueue.Add(scheduleHistoryItem); - } - } - } - catch (ApplicationException ex) - { - // The writer lock request timed out. - Interlocked.Increment(ref _writerTimeouts); - Exceptions.Exceptions.LogException(ex); - } - } - } - - private delegate void AddToScheduleInProgressDelegate(ScheduleHistoryItem item); public static void FireEvents() { @@ -383,6 +383,16 @@ public static void FireEvents() } } + public static int GetActiveThreadCount() + { + return _activeThreadCount; + } + + public static int GetFreeThreadCount() + { + return FreeThreads; + } + private static void LogWhyTaskNotRun(ScheduleItem scheduleItem) { if (_debug) @@ -448,16 +458,6 @@ private static void LogEventAddedToProcessGroup(ScheduleItem scheduleItem) } } - public static int GetActiveThreadCount() - { - return _activeThreadCount; - } - - public static int GetFreeThreadCount() - { - return FreeThreads; - } - public static int GetMaxThreadCount() { return _maxThreadCount; @@ -756,13 +756,6 @@ public static void LoadQueueFromTimer() } } - private static string ServerGroupServers(ServerInfo thisServer) - { - // Get the servers - var servers = ServerController.GetEnabledServers().Where(s => s.ServerGroup == thisServer.ServerGroup); - return servers.Aggregate(string.Empty, (current, serverInfo) => current + ServerController.GetServerName(serverInfo) + ","); - } - public static void PurgeScheduleHistory() { SchedulingController.PurgeScheduleHistory(); @@ -773,6 +766,13 @@ public static void ReloadSchedule() _forceReloadSchedule = true; } + private static string ServerGroupServers(ServerInfo thisServer) + { + // Get the servers + var servers = ServerController.GetEnabledServers().Where(s => s.ServerGroup == thisServer.ServerGroup); + return servers.Aggregate(string.Empty, (current, serverInfo) => current + ServerController.GetServerName(serverInfo) + ","); + } + /// /// Removes an item from the collection of schedule items in queue. /// @@ -1347,30 +1347,6 @@ public static void WorkStarted(ScheduleHistoryItem scheduleHistoryItem) } } - internal static void InitializeThreadPool(bool boolDebug, int maxThreads) - { - _debug = boolDebug; - lock (typeof(CoreScheduler)) - { - if (!_threadPoolInitialized) - { - _threadPoolInitialized = true; - if (maxThreads == -1) - { - maxThreads = 1; - } - - _numberOfProcessGroups = maxThreads; - _maxThreadCount = maxThreads; - for (int i = 0; i < _numberOfProcessGroups; i++) - { - Array.Resize(ref _processGroup, i + 1); - _processGroup[i] = new ProcessGroup(); - } - } - } - } - // DNN-5001 public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHistoryItem runningscheduleHistoryItem) { @@ -1498,6 +1474,30 @@ public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHis Exceptions.Exceptions.ProcessSchedulerException(exc); } } + + internal static void InitializeThreadPool(bool boolDebug, int maxThreads) + { + _debug = boolDebug; + lock (typeof(CoreScheduler)) + { + if (!_threadPoolInitialized) + { + _threadPoolInitialized = true; + if (maxThreads == -1) + { + maxThreads = 1; + } + + _numberOfProcessGroups = maxThreads; + _maxThreadCount = maxThreads; + for (int i = 0; i < _numberOfProcessGroups; i++) + { + Array.Resize(ref _processGroup, i + 1); + _processGroup[i] = new ProcessGroup(); + } + } + } + } } } } diff --git a/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs b/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs index 73de94c9fd0..e8fc213f58c 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs @@ -22,6 +22,12 @@ public SchedulerClient() this.ScheduleHistoryItem = new ScheduleHistoryItem(); } + public event WorkStarted ProcessStarted; + + public event WorkProgressing ProcessProgressing; + + public event WorkCompleted ProcessCompleted; + public ScheduleHistoryItem ScheduleHistoryItem { get; set; } public string SchedulerEventGUID { get; set; } @@ -37,12 +43,6 @@ public int ThreadID return Thread.CurrentThread.ManagedThreadId; } } - - public event WorkStarted ProcessStarted; - - public event WorkProgressing ProcessProgressing; - - public event WorkCompleted ProcessCompleted; public event WorkErrored ProcessErrored; diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs index 5658a0a9a5c..b0fd2d1cc2a 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs @@ -15,6 +15,15 @@ namespace DotNetNuke.Services.Scheduling using Globals = DotNetNuke.Common.Globals; + // ReSharper restore InconsistentNaming + + // set up our delegates so we can track and react to events of the scheduler clients + public delegate void WorkStarted(SchedulerClient objSchedulerClient); + + public delegate void WorkProgressing(SchedulerClient objSchedulerClient); + + public delegate void WorkCompleted(SchedulerClient objSchedulerClient); + // ReSharper disable InconsistentNaming public enum EventName { @@ -50,15 +59,6 @@ public enum SchedulerMode TIMER_METHOD = 1, REQUEST_METHOD = 2, } - - // ReSharper restore InconsistentNaming - - // set up our delegates so we can track and react to events of the scheduler clients - public delegate void WorkStarted(SchedulerClient objSchedulerClient); - - public delegate void WorkProgressing(SchedulerClient objSchedulerClient); - - public delegate void WorkCompleted(SchedulerClient objSchedulerClient); public delegate void WorkErrored(SchedulerClient objSchedulerClient, Exception objException); @@ -136,8 +136,6 @@ public static bool Enabled public static int MaxThreads { get; private set; } - public string ProviderPath { get; private set; } - public static bool ReadyForPoll { get @@ -163,6 +161,8 @@ public static DateTime ScheduleLastPolled } } + public string ProviderPath { get; private set; } + public static SchedulerMode SchedulerMode { get diff --git a/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs b/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs index 7a0a3ff37a6..b7da74f764d 100644 --- a/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs @@ -15,6 +15,11 @@ namespace DotNetNuke.Services.Search.Controllers [Serializable] public abstract class BaseResultController { + /// + /// Gets the localized search type name. + /// + public virtual string LocalizedSearchTypeName => string.Empty; + /// /// Does the user in the Context have View Permission on the Document. /// @@ -29,10 +34,5 @@ public abstract class BaseResultController /// Url. /// The Query Strings in the Document (if present) should be appended while returning the Url. public abstract string GetDocUrl(SearchResult searchResult); - - /// - /// Gets the localized search type name. - /// - public virtual string LocalizedSearchTypeName => string.Empty; } } diff --git a/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs b/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs index bb04718f014..acf8cc316f9 100644 --- a/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/ModuleResultController.cs @@ -31,6 +31,10 @@ namespace DotNetNuke.Services.Search.Controllers [Serializable] public class ModuleResultController : BaseResultController { + private const string ModuleByIdCacheKey = "ModuleById{0}"; + private const CacheItemPriority ModuleByIdCachePriority = CacheItemPriority.Normal; + private const int ModuleByIdCacheTimeOut = 20; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleResultController)); private static Hashtable _moduleSearchControllers = new Hashtable(); @@ -127,10 +131,6 @@ public override string GetDocUrl(SearchResult searchResult) return url; } - private const string ModuleByIdCacheKey = "ModuleById{0}"; - private const CacheItemPriority ModuleByIdCachePriority = CacheItemPriority.Normal; - private const int ModuleByIdCacheTimeOut = 20; - private static ArrayList GetModuleTabs(int moduleID) { // no manual clearing of the cache exists; let is just expire diff --git a/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs b/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs index b92328586f2..3ac5f12c07d 100644 --- a/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs @@ -45,6 +45,169 @@ public SearchResults ModuleSearch(SearchQuery searchQuery) var results = this.GetResults(searchQuery); return new SearchResults { TotalHits = results.Item1, Results = results.Item2 }; } + + private static void FillTagsValues(Document doc, SearchResult result) + { + foreach (var field in doc.GetFields()) + { + if (field.StringValue == null) + { + continue; + } + + int intField; + switch (field.Name) + { + case Constants.UniqueKeyTag: + result.UniqueKey = field.StringValue; + break; + case Constants.TitleTag: + var title = field.StringValue; + result.Title = title; + break; + case Constants.BodyTag: + result.Body = field.StringValue; + break; + case Constants.DescriptionTag: + result.Description = field.StringValue; + break; + case Constants.Tag: + result.Tags = result.Tags.Concat(new[] { field.StringValue }); + break; + case Constants.PermissionsTag: + result.Permissions = field.StringValue; + break; + case Constants.QueryStringTag: + result.QueryString = field.StringValue; + break; + case Constants.UrlTag: + result.Url = field.StringValue; + break; + case Constants.SearchTypeTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.SearchTypeId = intField; + } + + break; + case Constants.ModuleIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.ModuleId = intField; + } + + break; + case Constants.ModuleDefIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.ModuleDefId = intField; + } + + break; + case Constants.PortalIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.PortalId = intField; + } + + break; + case Constants.AuthorIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.AuthorUserId = intField; + } + + break; + case Constants.RoleIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.RoleId = intField; + } + + break; + case Constants.AuthorNameTag: + result.AuthorName = field.StringValue; + break; + case Constants.TabIdTag: + if (int.TryParse(field.StringValue, out intField)) + { + result.TabId = intField; + } + + break; + case Constants.ModifiedTimeTag: + DateTime modifiedTimeUtc; + DateTime.TryParseExact(field.StringValue, Constants.DateTimeFormat, null, DateTimeStyles.None, out modifiedTimeUtc); + result.ModifiedTimeUtc = modifiedTimeUtc; + break; + default: + if (field.Name.StartsWith(Constants.NumericKeyPrefixTag)) + { + var key = field.Name.Substring(Constants.NumericKeyPrefixTag.Length); + if (int.TryParse(field.StringValue, out intField)) + { + if (!result.NumericKeys.ContainsKey(key)) + { + result.NumericKeys.Add(key, intField); + } + } + } + else if (field.Name.StartsWith(Constants.KeywordsPrefixTag)) + { + var key = field.Name.Substring(Constants.KeywordsPrefixTag.Length); + if (!result.Keywords.ContainsKey(key)) + { + result.Keywords.Add(key, field.StringValue); + } + } + + break; + } + } + } + + private static string GetSnippet(SearchResult searchResult, LuceneResult luceneResult) + { + var sb = new StringBuilder(); + + if (!string.IsNullOrEmpty(luceneResult.TitleSnippet)) + { + sb.Append(luceneResult.TitleSnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.DescriptionSnippet)) + { + sb.Append(luceneResult.DescriptionSnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.TagSnippet)) + { + sb.Append(luceneResult.TagSnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.BodySnippet)) + { + sb.Append(luceneResult.BodySnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.AuthorSnippet)) + { + sb.Append(luceneResult.AuthorSnippet + "..."); + } + + if (!string.IsNullOrEmpty(luceneResult.ContentSnippet)) + { + sb.Append(luceneResult.ContentSnippet + "..."); + } + + var snippet = sb.ToString(); + if (string.IsNullOrEmpty(snippet)) + { + snippet = searchResult.Title; + } + + return snippet; + } private Tuple> GetResults(SearchQuery searchQuery) { @@ -235,13 +398,13 @@ private void ApplySearchTypeIdFilter(BooleanQuery query, SearchQuery searchQuery foreach (var searchTypeId in searchQuery.SearchTypeIds) { if (searchTypeId == this._moduleSearchTypeId) - { - foreach (var moduleDefId in searchQuery.ModuleDefIds.OrderBy(id => id)) + { + foreach (var moduleDefId in searchQuery.ModuleDefIds.OrderBy(id => id)) { searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.ModuleDefIdTag, moduleDefId, moduleDefId, true, true), Occur.SHOULD); - } + } - if (!searchQuery.ModuleDefIds.Any()) + if (!searchQuery.ModuleDefIds.Any()) { searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD); } @@ -284,168 +447,21 @@ private SearchResult GetSearchResultFromLuceneResult(LuceneResult luceneResult) return result; } - private static void FillTagsValues(Document doc, SearchResult result) + private static SearchResult GetPartialSearchResult(Document doc, SearchQuery searchQuery) { - foreach (var field in doc.GetFields()) + var result = new SearchResult { SearchContext = searchQuery.SearchContext }; + var localeField = doc.GetField(Constants.LocaleTag); + + if (localeField != null) { - if (field.StringValue == null) - { - continue; - } - - int intField; - switch (field.Name) - { - case Constants.UniqueKeyTag: - result.UniqueKey = field.StringValue; - break; - case Constants.TitleTag: - var title = field.StringValue; - result.Title = title; - break; - case Constants.BodyTag: - result.Body = field.StringValue; - break; - case Constants.DescriptionTag: - result.Description = field.StringValue; - break; - case Constants.Tag: - result.Tags = result.Tags.Concat(new[] { field.StringValue }); - break; - case Constants.PermissionsTag: - result.Permissions = field.StringValue; - break; - case Constants.QueryStringTag: - result.QueryString = field.StringValue; - break; - case Constants.UrlTag: - result.Url = field.StringValue; - break; - case Constants.SearchTypeTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.SearchTypeId = intField; - } - - break; - case Constants.ModuleIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.ModuleId = intField; - } - - break; - case Constants.ModuleDefIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.ModuleDefId = intField; - } - - break; - case Constants.PortalIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.PortalId = intField; - } - - break; - case Constants.AuthorIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.AuthorUserId = intField; - } - - break; - case Constants.RoleIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.RoleId = intField; - } - - break; - case Constants.AuthorNameTag: - result.AuthorName = field.StringValue; - break; - case Constants.TabIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.TabId = intField; - } - - break; - case Constants.ModifiedTimeTag: - DateTime modifiedTimeUtc; - DateTime.TryParseExact(field.StringValue, Constants.DateTimeFormat, null, DateTimeStyles.None, out modifiedTimeUtc); - result.ModifiedTimeUtc = modifiedTimeUtc; - break; - default: - if (field.Name.StartsWith(Constants.NumericKeyPrefixTag)) - { - var key = field.Name.Substring(Constants.NumericKeyPrefixTag.Length); - if (int.TryParse(field.StringValue, out intField)) - { - if (!result.NumericKeys.ContainsKey(key)) - { - result.NumericKeys.Add(key, intField); - } - } - } - else if (field.Name.StartsWith(Constants.KeywordsPrefixTag)) - { - var key = field.Name.Substring(Constants.KeywordsPrefixTag.Length); - if (!result.Keywords.ContainsKey(key)) - { - result.Keywords.Add(key, field.StringValue); - } - } - - break; - } + int id; + result.CultureCode = int.TryParse(localeField.StringValue, out id) && id >= 0 + ? LocaleController.Instance.GetLocale(id).Code : Null.NullString; } - } - private static string GetSnippet(SearchResult searchResult, LuceneResult luceneResult) - { - var sb = new StringBuilder(); - - if (!string.IsNullOrEmpty(luceneResult.TitleSnippet)) - { - sb.Append(luceneResult.TitleSnippet + "..."); - } - - if (!string.IsNullOrEmpty(luceneResult.DescriptionSnippet)) - { - sb.Append(luceneResult.DescriptionSnippet + "..."); - } - - if (!string.IsNullOrEmpty(luceneResult.TagSnippet)) - { - sb.Append(luceneResult.TagSnippet + "..."); - } - - if (!string.IsNullOrEmpty(luceneResult.BodySnippet)) - { - sb.Append(luceneResult.BodySnippet + "..."); - } - - if (!string.IsNullOrEmpty(luceneResult.AuthorSnippet)) - { - sb.Append(luceneResult.AuthorSnippet + "..."); - } - - if (!string.IsNullOrEmpty(luceneResult.ContentSnippet)) - { - sb.Append(luceneResult.ContentSnippet + "..."); - } - - var snippet = sb.ToString(); - if (string.IsNullOrEmpty(snippet)) - { - snippet = searchResult.Title; - } - - return snippet; - } + FillTagsValues(doc, result); + return result; + } private Dictionary GetSearchResultControllers() { @@ -486,12 +502,12 @@ private Tuple> GetSecurityTrimmedResults(SearchQuery se // **************************************************************************** if (searchQuery.PageSize > 0) { - var luceneResults = LuceneController.Instance.Search(new LuceneSearchContext - { - LuceneQuery = luceneQuery, - SearchQuery = searchQuery, - SecurityCheckerDelegate = this.HasPermissionToViewDoc, - }); + var luceneResults = LuceneController.Instance.Search(new LuceneSearchContext + { + LuceneQuery = luceneQuery, + SearchQuery = searchQuery, + SecurityCheckerDelegate = this.HasPermissionToViewDoc, + }); results = luceneResults.Results.Select(this.GetSearchResultFromLuceneResult).ToList(); totalHits = luceneResults.TotalHits; @@ -518,21 +534,5 @@ private bool HasPermissionToViewDoc(Document document, SearchQuery searchQuery) var resultController = this.GetSearchResultControllers().SingleOrDefault(sc => sc.Key == result.SearchTypeId).Value; return resultController != null && resultController.HasViewPermission(result); } - - private static SearchResult GetPartialSearchResult(Document doc, SearchQuery searchQuery) - { - var result = new SearchResult { SearchContext = searchQuery.SearchContext }; - var localeField = doc.GetField(Constants.LocaleTag); - - if (localeField != null) - { - int id; - result.CultureCode = int.TryParse(localeField.StringValue, out id) && id >= 0 - ? LocaleController.Instance.GetLocale(id).Code : Null.NullString; - } - - FillTagsValues(doc, result); - return result; - } } } diff --git a/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs b/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs index 234c7c0dfd2..2d644ad3cbb 100644 --- a/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs @@ -22,6 +22,8 @@ namespace DotNetNuke.Services.Search.Controllers public class TabResultController : BaseResultController { private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + + public override string LocalizedSearchTypeName => Localization.GetString("Crawler_tab", LocalizedResxFile); public override bool HasViewPermission(SearchResult searchResult) { @@ -63,7 +65,5 @@ public override string GetDocUrl(SearchResult searchResult) return url; } - - public override string LocalizedSearchTypeName => Localization.GetString("Crawler_tab", LocalizedResxFile); } } diff --git a/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs b/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs index 493d8a4adf0..0ebb532542d 100644 --- a/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs @@ -24,9 +24,11 @@ namespace DotNetNuke.Services.Search.Controllers [Serializable] public class UserResultController : BaseResultController { + private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + private static readonly Regex SearchResultMatchRegex = new Regex(@"^(\d+)_", RegexOptions.Compiled); - private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + public override string LocalizedSearchTypeName => Localization.GetString("Crawler_user", LocalizedResxFile); private PortalSettings PortalSettings { @@ -96,7 +98,11 @@ public override string GetDocUrl(SearchResult searchResult) return url; } - public override string LocalizedSearchTypeName => Localization.GetString("Crawler_user", LocalizedResxFile); + private static int GetUserId(SearchDocumentToDelete searchResult) + { + var match = SearchResultMatchRegex.Match(searchResult.UniqueKey); + return match.Success ? Convert.ToInt32(match.Groups[1].Value) : Null.NullInteger; + } private bool HasSocialReplationship(UserInfo targetUser, UserInfo accessingUser, string extendedVisibility) { @@ -144,11 +150,5 @@ private bool HasSocialReplationship(UserInfo targetUser, UserInfo accessingUser, return isVisible; } - - private static int GetUserId(SearchDocumentToDelete searchResult) - { - var match = SearchResultMatchRegex.Match(searchResult.UniqueKey); - return match.Success ? Convert.ToInt32(match.Groups[1].Value) : Null.NullInteger; - } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs b/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs index eed4b81022f..46bdccfd6d3 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs @@ -13,6 +13,12 @@ namespace DotNetNuke.Services.Search.Entities [Serializable] public class SearchDocument : SearchDocumentToDelete { + public SearchDocument() + { + this.Tags = new string[0]; + this.IsActive = true; + } + /// /// Gets or sets content's Title. /// @@ -70,12 +76,6 @@ public class SearchDocument : SearchDocumentToDelete /// public IEnumerable Tags { get; set; } - public SearchDocument() - { - this.Tags = new string[0]; - this.IsActive = true; - } - public override string ToString() { return string.Join(", ", new[] diff --git a/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs b/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs index 0f1ea843e51..6e1f650d079 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs @@ -15,6 +15,20 @@ namespace DotNetNuke.Services.Search.Entities [Serializable] public class SearchDocumentToDelete { + public SearchDocumentToDelete() + { + this.Keywords = new Dictionary(); + this.NumericKeys = new Dictionary(); + this.CultureCode = string.Empty; + this.SearchTypeId = + this.PortalId = + this.RoleId = -1; + this.ModuleDefId = + this.ModuleId = + this.TabId = + this.AuthorUserId = 0; + } + /// /// Gets or sets a key to uniquely identify a document in the Index. /// @@ -95,20 +109,6 @@ public class SearchDocumentToDelete /// A value of NULL/EMPTY means this is property is not used. public string CultureCode { get; set; } - public SearchDocumentToDelete() - { - this.Keywords = new Dictionary(); - this.NumericKeys = new Dictionary(); - this.CultureCode = string.Empty; - this.SearchTypeId = - this.PortalId = - this.RoleId = -1; - this.ModuleDefId = - this.ModuleId = - this.TabId = - this.AuthorUserId = 0; - } - /// /// This is to allow saving current instance into DB as JSON entity. /// diff --git a/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs b/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs index f5d5b156b51..0f1853fbc06 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs @@ -14,6 +14,21 @@ namespace DotNetNuke.Services.Search.Entities [Serializable] public class SearchQuery { + public SearchQuery() + { + this.Tags = new string[0]; + this.PortalIds = new int[0]; + this.SearchTypeIds = new int[0]; + this.ModuleDefIds = new int[0]; + this.TitleSnippetLength = 60; + this.BodySnippetLength = 100; + this.PageSize = 10; + this.PageIndex = 1; + this.SearchContext = new Dictionary(); + this.CustomKeywords = new Dictionary(); + this.NumericKeys = new Dictionary(); + } + /// /// Gets or sets a key to uniquely identify a document in the Index. /// @@ -155,20 +170,5 @@ public class SearchQuery /// /// When host setting "Search_AllowLeadingWildcard" set to true, it will always allow search in word but ignore this value. public bool AllowLeadingWildcard { get; set; } - - public SearchQuery() - { - this.Tags = new string[0]; - this.PortalIds = new int[0]; - this.SearchTypeIds = new int[0]; - this.ModuleDefIds = new int[0]; - this.TitleSnippetLength = 60; - this.BodySnippetLength = 100; - this.PageSize = 10; - this.PageIndex = 1; - this.SearchContext = new Dictionary(); - this.CustomKeywords = new Dictionary(); - this.NumericKeys = new Dictionary(); - } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchResult.cs b/DNN Platform/Library/Services/Search/Entities/SearchResult.cs index 80c0b049d5b..5f345cd2d0f 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchResult.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchResult.cs @@ -17,6 +17,18 @@ namespace DotNetNuke.Services.Search.Entities [Serializable] public class SearchResult : SearchDocument { + /// + /// Initializes a new instance of the class. + /// Empty Constructor. + /// + public SearchResult() + { + this.Tags = new string[0]; + this.NumericKeys = new Dictionary(); + this.Keywords = new Dictionary(); + this.SearchContext = new Dictionary(); + } + /// /// Gets time when Content was last modified (in friendly format). /// @@ -53,17 +65,5 @@ public string DisplayModifiedTime /// This is key-value pair, e.g. "SearchSource","SiteSearch" /// public IDictionary SearchContext { get; set; } - - /// - /// Initializes a new instance of the class. - /// Empty Constructor. - /// - public SearchResult() - { - this.Tags = new string[0]; - this.NumericKeys = new Dictionary(); - this.Keywords = new Dictionary(); - this.SearchContext = new Dictionary(); - } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchResults.cs b/DNN Platform/Library/Services/Search/Entities/SearchResults.cs index 2eb173cdfb8..c1a48fe5e0d 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchResults.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchResults.cs @@ -14,6 +14,11 @@ namespace DotNetNuke.Services.Search.Entities [Serializable] public class SearchResults { + public SearchResults() + { + this.Results = new List(); + } + /// /// Gets or sets total Hits found in Lucene. /// @@ -24,10 +29,5 @@ public class SearchResults /// Gets or sets collection of Results. /// public IList Results { get; set; } - - public SearchResults() - { - this.Results = new List(); - } } } diff --git a/DNN Platform/Library/Services/Search/IndexingProvider.cs b/DNN Platform/Library/Services/Search/IndexingProvider.cs index 991912afdeb..9f54a30f30b 100644 --- a/DNN Platform/Library/Services/Search/IndexingProvider.cs +++ b/DNN Platform/Library/Services/Search/IndexingProvider.cs @@ -16,6 +16,9 @@ namespace DotNetNuke.Services.Search [Obsolete("Legacy Indexing base class -- Deprecated in DNN 7.1. Use 'IndexingProviderBase' instead.. Scheduled removal in v10.0.0.")] public abstract class IndexingProvider { + private const string TimePostfix = "UtcTime"; + private const string DataPostfix = "Data"; + /// This method must save search documents in batches to minimize memory usage instead of returning all documents at once. /// ID of the portal for which to index items. /// Minimum modification date of items that need to be indexed. @@ -37,9 +40,6 @@ public virtual IEnumerable GetSearchDocuments(int portalId, Date [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] public abstract SearchItemInfoCollection GetSearchIndexItems(int portalId); - private const string TimePostfix = "UtcTime"; - private const string DataPostfix = "Data"; - /// Retrieves the date/time of the last item to be indexed. /// The portal ID. /// The schedule ID. diff --git a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs index 27359238a27..a97022931fc 100644 --- a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs +++ b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs @@ -15,6 +15,9 @@ namespace DotNetNuke.Services.Search /// A base class for search indexers. public abstract class IndexingProviderBase { + private const string TimePostfix = "UtcTime"; + private const string DataPostfix = "Data"; + /// This method must save search documents in batches to minimize memory usage instead of returning all documents at once. /// ID of the portal for which to index items. /// Minimum modification date of items that need to be indexed. @@ -24,8 +27,17 @@ public abstract int IndexSearchDocuments( int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer); - private const string TimePostfix = "UtcTime"; - private const string DataPostfix = "Data"; + [Obsolete("Deprecated in DNN 7.4.2 Use 'IndexSearchDocuments' instead for lower memory footprint during search.. Scheduled removal in v10.0.0.")] + public virtual IEnumerable GetSearchDocuments(int portalId, DateTime startDateLocal) + { + return Enumerable.Empty(); + } + + [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] + public virtual SearchItemInfoCollection GetSearchIndexItems(int portalId) + { + return new SearchItemInfoCollection(); + } /// Retrieves the date/time of the last item to be indexed. /// The portal ID. @@ -67,18 +79,6 @@ protected void SetLastCheckpointData(int portalId, int scheduleId, string data) SearchHelper.Instance.SetIndexerCheckpointData(scheduleId, this.ScheduleItemSettingKey(portalId, DataPostfix), data); } - [Obsolete("Deprecated in DNN 7.4.2 Use 'IndexSearchDocuments' instead for lower memory footprint during search.. Scheduled removal in v10.0.0.")] - public virtual IEnumerable GetSearchDocuments(int portalId, DateTime startDateLocal) - { - return Enumerable.Empty(); - } - - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - public virtual SearchItemInfoCollection GetSearchIndexItems(int portalId) - { - return new SearchItemInfoCollection(); - } - /// /// Creates a unique name for the IndexingProvider implementation that can be used /// to save/retrieve scheduler item {key,name} setting pairs per portal and feature. diff --git a/DNN Platform/Library/Services/Search/Internals/Constants.cs b/DNN Platform/Library/Services/Search/Internals/Constants.cs index 10fcec62b6e..81642b88dd1 100644 --- a/DNN Platform/Library/Services/Search/Internals/Constants.cs +++ b/DNN Platform/Library/Services/Search/Internals/Constants.cs @@ -49,11 +49,11 @@ internal static class Constants internal const string DateTimeFormat = "yyyyMMddHHmmssfff"; internal const string ReindexDateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; - internal static Version LuceneVersion = Version.LUCENE_30; - // Field Boost Settings - they are scaled down by 10. internal const int DefaultSearchTitleBoost = 50; internal const int DefaultSearchTagBoost = 40; + + internal static Version LuceneVersion = Version.LUCENE_30; internal const int DefaultSearchKeywordBoost = 35; internal const int DefaultSearchDescriptionBoost = 20; internal const int DefaultSearchAuthorBoost = 15; @@ -69,6 +69,10 @@ internal static class Constants // If weighted sum of Likes, Comment and Weight is the number below, Document gets a boost of 1.0 internal const int DefaultDocumentBoostScale = 1000; + // search index tokenizers word lengths + internal const int MinimumMinLen = 1; + internal const int DefaultMinLen = 3; + internal static readonly string[] FieldsNeedAnalysis = { TitleTag, SubjectTag, CommentsTag, AuthorNameTag, StatusTag, CategoryTag }; internal static readonly string[] KeyWordSearchFields = @@ -83,10 +87,6 @@ internal static class Constants KeywordsPrefixTag + CommentsTag, KeywordsPrefixTag + AuthorNameTag, }; - - // search index tokenizers word lengths - internal const int MinimumMinLen = 1; - internal const int DefaultMinLen = 3; internal const int MaximumMinLen = 10; internal const int MinimumMaxLen = 10; diff --git a/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs b/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs index cbb1fbe5210..fc820ea17a1 100644 --- a/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs @@ -38,23 +38,29 @@ namespace DotNetNuke.Services.Search.Internals /// ----------------------------------------------------------------------------- internal class InternalSearchControllerImpl : IInternalSearchController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InternalSearchControllerImpl)); private const string SearchableModuleDefsKey = "{0}-{1}"; private const string SearchableModuleDefsCacheKey = "SearchableModuleDefs"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InternalSearchControllerImpl)); private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + private const string HtmlTagsWithAttrs = "<[a-z_:][\\w:.-]*(\\s+(?\\w+\\s*?=\\s*?[\"'].*?[\"']))+\\s*/?>"; + + private const string AttrText = "[\"'](?.*?)[\"']"; + private static readonly string[] HtmlAttributesToRetain = { "alt", "title" }; + private static readonly DataProvider DataProvider = DataProvider.Instance(); + + private static readonly Regex StripOpeningTagsRegex = new Regex(@"<\w*\s*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private readonly int _titleBoost; private readonly int _tagBoost; private readonly int _contentBoost; private readonly int _descriptionBoost; private readonly int _authorBoost; private readonly int _moduleSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; - - private static readonly DataProvider DataProvider = DataProvider.Instance(); - - private static readonly Regex StripOpeningTagsRegex = new Regex(@"<\w*\s*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex StripClosingTagsRegex = new Regex(@"", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex HtmlTagsRegex = new Regex(HtmlTagsWithAttrs, RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex AttrTextRegex = new Regex(AttrText, RegexOptions.Compiled); public InternalSearchControllerImpl() { @@ -65,6 +71,33 @@ public InternalSearchControllerImpl() this._descriptionBoost = hostController.GetInteger(Constants.SearchDescriptionBoostSetting, Constants.DefaultSearchDescriptionBoost); this._authorBoost = hostController.GetInteger(Constants.SearchAuthorBoostSetting, Constants.DefaultSearchAuthorBoost); } + + public IEnumerable GetSearchContentSourceList(int portalId) + { + var searchableModuleDefsCacheArgs = new CacheItemArgs( + string.Format(SearchableModuleDefsKey, SearchableModuleDefsCacheKey, portalId), + 120, CacheItemPriority.Default); + + var list = CBO.GetCachedObject>( + searchableModuleDefsCacheArgs, this.SearchContentSourceCallback); + + return list; + } + + public string GetSearchDocumentTypeDisplayName(SearchResult searchResult) + { + // ModuleDefId will be zero for non-module + var key = string.Format("{0}-{1}", searchResult.SearchTypeId, searchResult.ModuleDefId); + var keys = CBO.Instance.GetCachedObject>( + new CacheItemArgs(key, 120, CacheItemPriority.Default), this.SearchDocumentTypeDisplayNameCallBack, false); + + return keys.ContainsKey(key) ? keys[key] : string.Empty; + } + + public void AddSearchDocument(SearchDocument searchDocument) + { + this.AddSearchDocumentInternal(searchDocument, false); + } internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) { @@ -136,18 +169,6 @@ internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) return results; } - public IEnumerable GetSearchContentSourceList(int portalId) - { - var searchableModuleDefsCacheArgs = new CacheItemArgs( - string.Format(SearchableModuleDefsKey, SearchableModuleDefsCacheKey, portalId), - 120, CacheItemPriority.Default); - - var list = CBO.GetCachedObject>( - searchableModuleDefsCacheArgs, this.SearchContentSourceCallback); - - return list; - } - private object SearchDocumentTypeDisplayNameCallBack(CacheItemArgs cacheItem) { var data = new Dictionary(); @@ -167,19 +188,41 @@ private object SearchDocumentTypeDisplayNameCallBack(CacheItemArgs cacheItem) return data; } - public string GetSearchDocumentTypeDisplayName(SearchResult searchResult) + public void AddSearchDocuments(IEnumerable searchDocuments) { - // ModuleDefId will be zero for non-module - var key = string.Format("{0}-{1}", searchResult.SearchTypeId, searchResult.ModuleDefId); - var keys = CBO.Instance.GetCachedObject>( - new CacheItemArgs(key, 120, CacheItemPriority.Default), this.SearchDocumentTypeDisplayNameCallBack, false); - - return keys.ContainsKey(key) ? keys[key] : string.Empty; - } + var searchDocs = searchDocuments as IList ?? searchDocuments.ToList(); + if (searchDocs.Any()) + { + const int commitBatchSize = 1024 * 16; + var idx = 0; - public void AddSearchDocument(SearchDocument searchDocument) + // var added = false; + foreach (var searchDoc in searchDocs) + { + try + { + this.AddSearchDocumentInternal(searchDoc, (++idx % commitBatchSize) == 0); + + // added = true; + } + catch (Exception ex) + { + Logger.ErrorFormat("Search Document error: {0}{1}{2}", searchDoc, Environment.NewLine, ex); + } + } + + // Note: modified to do commit only once at the end of scheduler job + // check so we don't commit again + // if (added && (idx % commitBatchSize) != 0) + // { + // Commit(); + // } + } + } + + public void DeleteSearchDocument(SearchDocument searchDocument) { - this.AddSearchDocumentInternal(searchDocument, false); + this.DeleteSearchDocumentInternal(searchDocument, false); } private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoCommit) @@ -256,41 +299,33 @@ private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoC } } - public void AddSearchDocuments(IEnumerable searchDocuments) + public void DeleteSearchDocumentsByModule(int portalId, int moduleId, int moduleDefId) { - var searchDocs = searchDocuments as IList ?? searchDocuments.ToList(); - if (searchDocs.Any()) + Requires.NotNegative("PortalId", portalId); + + this.DeleteSearchDocument(new SearchDocument { - const int commitBatchSize = 1024 * 16; - var idx = 0; - - // var added = false; - foreach (var searchDoc in searchDocs) - { - try - { - this.AddSearchDocumentInternal(searchDoc, (++idx % commitBatchSize) == 0); - - // added = true; - } - catch (Exception ex) - { - Logger.ErrorFormat("Search Document error: {0}{1}{2}", searchDoc, Environment.NewLine, ex); - } - } + PortalId = portalId, + ModuleId = moduleId, + ModuleDefId = moduleDefId, + SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, + }); + } - // Note: modified to do commit only once at the end of scheduler job - // check so we don't commit again - // if (added && (idx % commitBatchSize) != 0) - // { - // Commit(); - // } - } + public void DeleteAllDocuments(int portalId, int searchTypeId) + { + Requires.NotNegative("SearchTypeId", searchTypeId); + + this.DeleteSearchDocument(new SearchDocument + { + PortalId = portalId, + SearchTypeId = searchTypeId, + }); } - public void DeleteSearchDocument(SearchDocument searchDocument) + private static Query NumericValueQuery(string numericName, int numericVal) { - this.DeleteSearchDocumentInternal(searchDocument, false); + return NumericRangeQuery.NewIntRange(numericName, numericVal, numericVal, true, true); } private void DeleteSearchDocumentInternal(SearchDocument searchDocument, bool autoCommit) @@ -355,35 +390,6 @@ private void DeleteSearchDocumentInternal(SearchDocument searchDocument, bool au } } - private static Query NumericValueQuery(string numericName, int numericVal) - { - return NumericRangeQuery.NewIntRange(numericName, numericVal, numericVal, true, true); - } - - public void DeleteSearchDocumentsByModule(int portalId, int moduleId, int moduleDefId) - { - Requires.NotNegative("PortalId", portalId); - - this.DeleteSearchDocument(new SearchDocument - { - PortalId = portalId, - ModuleId = moduleId, - ModuleDefId = moduleDefId, - SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, - }); - } - - public void DeleteAllDocuments(int portalId, int searchTypeId) - { - Requires.NotNegative("SearchTypeId", searchTypeId); - - this.DeleteSearchDocument(new SearchDocument - { - PortalId = portalId, - SearchTypeId = searchTypeId, - }); - } - public void Commit() { LuceneController.Instance.Commit(); @@ -399,6 +405,17 @@ public SearchStatistics GetSearchStatistics() { return LuceneController.Instance.GetSearchStatistics(); } + + /// + /// Add Field to Doc when supplied fieldValue > 0. + /// + private static void AddIntField(Document doc, int fieldValue, string fieldTag) + { + if (fieldValue > 0) + { + doc.Add(new NumericField(fieldTag, Field.Store.YES, true).SetIntValue(fieldValue)); + } + } private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocument, StringBuilder sb) { @@ -548,23 +565,6 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum } } - /// - /// Add Field to Doc when supplied fieldValue > 0. - /// - private static void AddIntField(Document doc, int fieldValue, string fieldTag) - { - if (fieldValue > 0) - { - doc.Add(new NumericField(fieldTag, Field.Store.YES, true).SetIntValue(fieldValue)); - } - } - - private const string HtmlTagsWithAttrs = "<[a-z_:][\\w:.-]*(\\s+(?\\w+\\s*?=\\s*?[\"'].*?[\"']))+\\s*/?>"; - private static readonly Regex HtmlTagsRegex = new Regex(HtmlTagsWithAttrs, RegexOptions.IgnoreCase | RegexOptions.Compiled); - - private const string AttrText = "[\"'](?.*?)[\"']"; - private static readonly Regex AttrTextRegex = new Regex(AttrText, RegexOptions.Compiled); - private static string StripTagsRetainAttributes(string html, IEnumerable attributes, bool decoded, bool retainSpace) { var attributesList = attributes as IList ?? attributes.ToList(); diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs b/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs index 29b7f22e7f6..39e82eccba2 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs @@ -35,19 +35,22 @@ namespace DotNetNuke.Services.Search.Internals /// ----------------------------------------------------------------------------- internal class LuceneControllerImpl : ILuceneController, IDisposable { + internal const int DefaultRereadTimeSpan = 30; // in seconds private const string DefaultSearchFolder = @"App_Data\Search"; private const string WriteLockFile = "write.lock"; - internal const int DefaultRereadTimeSpan = 30; // in seconds private const int DefaultSearchRetryTimes = 5; private const int DISPOSED = 1; private const int UNDISPOSED = 0; + private const string HighlightPreTag = "[b]"; + private const string HighlightPostTag = "[/b]"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LuceneControllerImpl)); - internal string IndexFolder { get; private set; } - private IndexWriter _writer; private IndexReader _idxReader; private CachedReader _reader; + + internal string IndexFolder { get; private set; } private FastVectorHighlighter _fastHighlighter; private readonly object _writerLock = new object(); private readonly double _readerTimeSpan; // in seconds @@ -55,11 +58,11 @@ internal class LuceneControllerImpl : ILuceneController, IDisposable private readonly List _oldReaders = new List(); private int _isDisposed = UNDISPOSED; - private const string HighlightPreTag = "[b]"; - private const string HighlightPostTag = "[/b]"; - private const string HtmlPreTag = ""; private const string HtmlPostTag = ""; + + private DateTime _lastReadTimeUtc; + private DateTime _lastDirModifyTimeUtc; public LuceneControllerImpl() { @@ -75,14 +78,6 @@ public LuceneControllerImpl() this._readerTimeSpan = hostController.GetDouble(Constants.SearchReaderRefreshTimeKey, DefaultRereadTimeSpan); this._searchRetryTimes = hostController.GetInteger(Constants.SearchRetryTimesKey, DefaultSearchRetryTimes); } - - private void CheckDisposed() - { - if (Thread.VolatileRead(ref this._isDisposed) == DISPOSED) - { - throw new ObjectDisposedException(Localization.GetExceptionMessage("LuceneControlerIsDisposed", "LuceneController is disposed and cannot be used anymore")); - } - } private IndexWriter Writer { @@ -128,6 +123,16 @@ private IndexWriter Writer } } + private bool MustRereadIndex + { + get + { + return (DateTime.UtcNow - this._lastReadTimeUtc).TotalSeconds >= this._readerTimeSpan && + System.IO.Directory.Exists(this.IndexFolder) && + System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder) != this._lastDirModifyTimeUtc; + } + } + // made internal to be used in unit tests only; otherwise could be made private internal IndexSearcher GetSearcher() { @@ -141,6 +146,14 @@ internal IndexSearcher GetSearcher() return this._reader.GetSearcher(); } + private void CheckDisposed() + { + if (Thread.VolatileRead(ref this._isDisposed) == DISPOSED) + { + throw new ObjectDisposedException(Localization.GetExceptionMessage("LuceneControlerIsDisposed", "LuceneController is disposed and cannot be used anymore")); + } + } + private void InstantiateReader() { IndexSearcher searcher; @@ -174,52 +187,6 @@ private void InstantiateReader() } } - private DateTime _lastReadTimeUtc; - private DateTime _lastDirModifyTimeUtc; - - private bool MustRereadIndex - { - get - { - return (DateTime.UtcNow - this._lastReadTimeUtc).TotalSeconds >= this._readerTimeSpan && - System.IO.Directory.Exists(this.IndexFolder) && - System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder) != this._lastDirModifyTimeUtc; - } - } - - private void UpdateLastAccessTimes() - { - this._lastReadTimeUtc = DateTime.UtcNow; - if (System.IO.Directory.Exists(this.IndexFolder)) - { - this._lastDirModifyTimeUtc = System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder); - } - } - - private void RescheduleAccessTimes() - { - // forces re-opening the reader within 30 seconds from now (used mainly by commit) - var now = DateTime.UtcNow; - if (this._readerTimeSpan > DefaultRereadTimeSpan && (now - this._lastReadTimeUtc).TotalSeconds > DefaultRereadTimeSpan) - { - this._lastReadTimeUtc = now - TimeSpan.FromSeconds(this._readerTimeSpan - DefaultRereadTimeSpan); - } - } - - private void CheckValidIndexFolder() - { - if (!this.ValidateIndexFolder()) - { - throw new SearchIndexEmptyException(Localization.GetExceptionMessage("SearchIndexingDirectoryNoValid", "Search indexing directory is either empty or does not exist")); - } - } - - private bool ValidateIndexFolder() - { - return System.IO.Directory.Exists(this.IndexFolder) && - System.IO.Directory.GetFiles(this.IndexFolder, "*.*").Length > 0; - } - private FastVectorHighlighter FastHighlighter { get @@ -318,15 +285,31 @@ public LuceneResults Search(LuceneSearchContext searchContext) return luceneResults; } - private string GetHighlightedText(FastVectorHighlighter highlighter, FieldQuery fieldQuery, IndexSearcher searcher, ScoreDoc match, string tag, int length) + public void Add(Document doc) { - var s = highlighter.GetBestFragment(fieldQuery, searcher.IndexReader, match.Doc, tag, length); - if (!string.IsNullOrEmpty(s)) + Requires.NotNull("searchDocument", doc); + if (doc.GetFields().Count > 0) { - s = HttpUtility.HtmlEncode(s).Replace(HighlightPreTag, HtmlPreTag).Replace(HighlightPostTag, HtmlPostTag); + try + { + this.Writer.AddDocument(doc); + } + catch (OutOfMemoryException) + { + lock (this._writerLock) + { + // as suggested by Lucene's doc + this.DisposeWriter(); + this.Writer.AddDocument(doc); + } + } } - - return s; + } + + public void Delete(Query query) + { + Requires.NotNull("luceneQuery", query); + this.Writer.DeleteDocuments(query); } private static StringBuilder GetSearcResultExplanation(LuceneQuery luceneQuery, IEnumerable scoreDocs, IndexSearcher searcher) @@ -345,6 +328,50 @@ private static StringBuilder GetSearcResultExplanation(LuceneQuery luceneQuery, return sb; } + private void UpdateLastAccessTimes() + { + this._lastReadTimeUtc = DateTime.UtcNow; + if (System.IO.Directory.Exists(this.IndexFolder)) + { + this._lastDirModifyTimeUtc = System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder); + } + } + + private void RescheduleAccessTimes() + { + // forces re-opening the reader within 30 seconds from now (used mainly by commit) + var now = DateTime.UtcNow; + if (this._readerTimeSpan > DefaultRereadTimeSpan && (now - this._lastReadTimeUtc).TotalSeconds > DefaultRereadTimeSpan) + { + this._lastReadTimeUtc = now - TimeSpan.FromSeconds(this._readerTimeSpan - DefaultRereadTimeSpan); + } + } + + private void CheckValidIndexFolder() + { + if (!this.ValidateIndexFolder()) + { + throw new SearchIndexEmptyException(Localization.GetExceptionMessage("SearchIndexingDirectoryNoValid", "Search indexing directory is either empty or does not exist")); + } + } + + private bool ValidateIndexFolder() + { + return System.IO.Directory.Exists(this.IndexFolder) && + System.IO.Directory.GetFiles(this.IndexFolder, "*.*").Length > 0; + } + + private string GetHighlightedText(FastVectorHighlighter highlighter, FieldQuery fieldQuery, IndexSearcher searcher, ScoreDoc match, string tag, int length) + { + var s = highlighter.GetBestFragment(fieldQuery, searcher.IndexReader, match.Doc, tag, length); + if (!string.IsNullOrEmpty(s)) + { + s = HttpUtility.HtmlEncode(s).Replace(HighlightPreTag, HtmlPreTag).Replace(HighlightPostTag, HtmlPostTag); + } + + return s; + } + /// /// Extract the Score portion of the match.ToString(). /// @@ -364,33 +391,6 @@ private string GetDisplayScoreFromMatch(string match) return displayScore; } - public void Add(Document doc) - { - Requires.NotNull("searchDocument", doc); - if (doc.GetFields().Count > 0) - { - try - { - this.Writer.AddDocument(doc); - } - catch (OutOfMemoryException) - { - lock (this._writerLock) - { - // as suggested by Lucene's doc - this.DisposeWriter(); - this.Writer.AddDocument(doc); - } - } - } - } - - public void Delete(Query query) - { - Requires.NotNull("luceneQuery", query); - this.Writer.DeleteDocuments(query); - } - public void Commit() { if (this._writer != null) @@ -464,15 +464,15 @@ public SearchStatistics GetSearchStatistics() var files = System.IO.Directory.GetFiles(this.IndexFolder, "*.*"); var size = files.Select(name => new FileInfo(name)).Select(fInfo => fInfo.Length).Sum(); - return new SearchStatistics - { - // Hack: seems that NumDocs/MaxDoc are buggy and return incorrect/swapped values - TotalActiveDocuments = searcher.IndexReader.NumDocs(), - TotalDeletedDocuments = searcher.IndexReader.NumDeletedDocs, - IndexLocation = this.IndexFolder, - LastModifiedOn = System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder), - IndexDbSize = size, - }; + return new SearchStatistics + { + // Hack: seems that NumDocs/MaxDoc are buggy and return incorrect/swapped values + TotalActiveDocuments = searcher.IndexReader.NumDocs(), + TotalDeletedDocuments = searcher.IndexReader.NumDeletedDocs, + IndexLocation = this.IndexFolder, + LastModifiedOn = System.IO.Directory.GetLastWriteTimeUtc(this.IndexFolder), + IndexDbSize = size, + }; } public void Dispose() @@ -557,8 +557,6 @@ private void DisposeReaders() private class CachedReader : IDisposable { - public DateTime LastUsed { get; private set; } - private readonly IndexSearcher _searcher; public CachedReader(IndexSearcher searcher) @@ -566,6 +564,8 @@ public CachedReader(IndexSearcher searcher) this._searcher = searcher; this.UpdateLastUsed(); } + + public DateTime LastUsed { get; private set; } public IndexSearcher GetSearcher() { @@ -573,16 +573,16 @@ public IndexSearcher GetSearcher() return this._searcher; } - private void UpdateLastUsed() - { - this.LastUsed = DateTime.Now; - } - public void Dispose() { this._searcher.Dispose(); this._searcher.IndexReader.Dispose(); } + + private void UpdateLastUsed() + { + this.LastUsed = DateTime.Now; + } } } } diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs b/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs index 5e57c1083fd..fc0fbc1964d 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs @@ -14,6 +14,15 @@ namespace DotNetNuke.Services.Search.Internals /// internal class LuceneQuery { + public LuceneQuery() + { + this.PageIndex = 1; + this.TitleSnippetLength = 60; + this.BodySnippetLength = 100; + this.PageSize = 10; + this.Sort = Sort.RELEVANCE; + } + /// /// Gets or sets lucene's original Query Object. /// @@ -43,14 +52,5 @@ internal class LuceneQuery /// Gets or sets maximum length of highlighted title field in the results. /// public int BodySnippetLength { get; set; } - - public LuceneQuery() - { - this.PageIndex = 1; - this.TitleSnippetLength = 60; - this.BodySnippetLength = 100; - this.PageSize = 10; - this.Sort = Sort.RELEVANCE; - } } } diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneResults.cs b/DNN Platform/Library/Services/Search/Internals/LuceneResults.cs index 843eec3ea61..d9498b88c17 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneResults.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneResults.cs @@ -8,13 +8,13 @@ namespace DotNetNuke.Services.Search.Internals internal class LuceneResults { - public IEnumerable Results { get; set; } - - public int TotalHits { get; set; } - public LuceneResults() { this.Results = new List(); } + + public IEnumerable Results { get; set; } + + public int TotalHits { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs b/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs index 59e3460c7e4..11e3c31b1a3 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs @@ -52,13 +52,6 @@ public SearchType GetSearchTypeByName(string searchTypeName) { return this.GetSearchTypes().Single(t => t.SearchTypeName == searchTypeName); } - - private IDictionary> GetSynonymTerms(int portalId, string cultureCode) - { - var cacheKey = string.Format("{0}_{1}_{2}", SynonymTermsCacheKey, portalId, cultureCode); - var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); - return CBO.GetCachedObject>>(cachArg, this.SynonymTermsCallBack); - } public IEnumerable GetSynonyms(int portalId, string cultureCode, string term) { @@ -78,6 +71,13 @@ public IEnumerable GetSynonymsGroups(int portalId, string culture var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); return CBO.GetCachedObject>(cachArg, this.GetSynonymsGroupsCallBack); } + + private IDictionary> GetSynonymTerms(int portalId, string cultureCode) + { + var cacheKey = string.Format("{0}_{1}_{2}", SynonymTermsCacheKey, portalId, cultureCode); + var cachArg = new CacheItemArgs(cacheKey, 120, CacheItemPriority.Default); + return CBO.GetCachedObject>>(cachArg, this.SynonymTermsCallBack); + } public int AddSynonymsGroup(string synonymsTags, int portalId, string cultureCode, out string duplicateWord) { diff --git a/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs b/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs index abc2f842dd3..acbb5225a7d 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs @@ -19,16 +19,16 @@ public class SearchQueryStringParser : ServiceLocator, ISearchQueryStringParser { - protected override Func GetFactory() - { - return () => new SearchQueryStringParser(); - } - private static readonly Regex TagRegex = new Regex(@"\[(.*?)\]", RegexOptions.Compiled); private static readonly Regex DateRegex = new Regex(@"after:(\w+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex TypeRegex = new Regex(@"type:([^,]+(,[^,]+)*)", RegexOptions.IgnoreCase | RegexOptions.Compiled); + + protected override Func GetFactory() + { + return () => new SearchQueryStringParser(); + } /// /// Gets the list of tags parsing the search keywords. diff --git a/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs b/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs index 8da32a1ece4..d832daa15c3 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs @@ -42,21 +42,6 @@ public override bool AcceptsDocsOutOfOrder get { return false; } } - public override void SetNextReader(IndexReader reader, int docBase) - { - this._docBase = docBase; - } - - public override void SetScorer(Scorer scorer) - { - this._scorer = scorer; - } - - public override void Collect(int doc) - { - this._hitDocs.Add(new ScoreDoc(doc + this._docBase, this._scorer.Score())); - } - public int TotalHits { get @@ -83,6 +68,21 @@ public List ScoreDocs } } + public override void SetNextReader(IndexReader reader, int docBase) + { + this._docBase = docBase; + } + + public override void SetScorer(Scorer scorer) + { + this._scorer = scorer; + } + + public override void Collect(int doc) + { + this._hitDocs.Add(new ScoreDoc(doc + this._docBase, this._scorer.Score())); + } + private string GetStringFromField(Document doc, SortField sortField) { var field = doc.GetField(sortField.Field); diff --git a/DNN Platform/Library/Services/Search/ModuleIndexer.cs b/DNN Platform/Library/Services/Search/ModuleIndexer.cs index 40336cf9b1d..0fff6a693bb 100644 --- a/DNN Platform/Library/Services/Search/ModuleIndexer.cs +++ b/DNN Platform/Library/Services/Search/ModuleIndexer.cs @@ -86,7 +86,7 @@ public override int IndexSearchDocuments( // We won't be calling into such modules if LastContentModifiedOnDate is prior to startDate. // LastContentModifiedOnDate remains MinValue for modules that don't update this property var modulesInDateRange = searchModuleCollection.Where(module => - ! (SqlDateTime.MinValue.Value < module.LastContentModifiedOnDate && module.LastContentModifiedOnDate < startDateLocal)) + !(SqlDateTime.MinValue.Value < module.LastContentModifiedOnDate && module.LastContentModifiedOnDate < startDateLocal)) .OrderBy(m => m.LastContentModifiedOnDate).ThenBy(m => m.ModuleID).ToArray(); if (modulesInDateRange.Any()) @@ -133,33 +133,6 @@ public override int IndexSearchDocuments( return totalIndexed; } - private static void AddModuleMetaData(IEnumerable searchItems, ModuleInfo module) - { - foreach (var searchItem in searchItems) - { - searchItem.ModuleDefId = module.ModuleDefID; - searchItem.ModuleId = module.ModuleID; - if (string.IsNullOrEmpty(searchItem.CultureCode)) - { - searchItem.CultureCode = module.CultureCode; - } - - if (Null.IsNull(searchItem.ModifiedTimeUtc)) - { - searchItem.ModifiedTimeUtc = module.LastContentModifiedOnDate.ToUniversalTime(); - } - } - } - - private int IndexCollectedDocs( - Action> indexer, ICollection searchDocuments, int portalId, ScheduleHistoryItem schedule) - { - indexer.Invoke(searchDocuments); - var total = searchDocuments.Count; - this.SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, schedule.StartDate); - return total; - } - /// ----------------------------------------------------------------------------- /// /// Returns a collection of SearchDocuments containing module metadata (title, header, footer...) of Searchable Modules. @@ -209,8 +182,8 @@ public List GetModuleMetaData(int portalId, DateTime startDate) } return searchDocuments; - } - + } + /// ----------------------------------------------------------------------------- /// /// Converts a SearchItemInfo into a SearchDocument. @@ -220,7 +193,7 @@ public List GetModuleMetaData(int portalId, DateTime startDate) /// /// /// ----------------------------------------------------------------------------- - #pragma warning disable 0618 +#pragma warning disable 0618 public SearchDocument ConvertSearchItemInfoToSearchDocument(SearchItemInfo searchItem) { var module = ModuleController.Instance.GetModule(searchItem.ModuleId, Null.NullInteger, true); @@ -247,6 +220,33 @@ public SearchDocument ConvertSearchItemInfoToSearchDocument(SearchItemInfo searc return searchDoc; } + + private static void AddModuleMetaData(IEnumerable searchItems, ModuleInfo module) + { + foreach (var searchItem in searchItems) + { + searchItem.ModuleDefId = module.ModuleDefID; + searchItem.ModuleId = module.ModuleID; + if (string.IsNullOrEmpty(searchItem.CultureCode)) + { + searchItem.CultureCode = module.CultureCode; + } + + if (Null.IsNull(searchItem.ModifiedTimeUtc)) + { + searchItem.ModifiedTimeUtc = module.LastContentModifiedOnDate.ToUniversalTime(); + } + } + } + + private int IndexCollectedDocs( + Action> indexer, ICollection searchDocuments, int portalId, ScheduleHistoryItem schedule) + { + indexer.Invoke(searchDocuments); + var total = searchDocuments.Count; + this.SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, schedule.StartDate); + return total; + } #pragma warning restore 0618 /// ----------------------------------------------------------------------------- @@ -264,9 +264,9 @@ protected IEnumerable GetSearchModules(int portalId) protected IEnumerable GetSearchModules(int portalId, bool allModules) { - return from mii in this.GetModulesForIndex(portalId) - where allModules || mii.SupportSearch - select mii.ModuleInfo; + return from mii in this.GetModulesForIndex(portalId) + where allModules || mii.SupportSearch + select mii.ModuleInfo; } private static void ThrowLogError(ModuleInfo module, Exception ex) diff --git a/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs index 546c8150a9c..207ebef731f 100644 --- a/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.Services.Search /// /// /// ----------------------------------------------------------------------------- - #pragma warning disable 0618 +#pragma warning disable 0618 public class SearchContentModuleInfoCollection : CollectionBase { /// diff --git a/DNN Platform/Library/Services/Search/SearchDataStore.cs b/DNN Platform/Library/Services/Search/SearchDataStore.cs index fbd3e172d32..9132a15485f 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStore.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStore.cs @@ -35,42 +35,6 @@ namespace DotNetNuke.Services.Search [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] public class SearchDataStore : SearchDataStoreProvider { - /// ----------------------------------------------------------------------------- - /// - /// GetCommonWords gets a list of the Common Words for the locale. - /// - /// - /// - /// The locale string. - /// A hashtable of common words. - /// ----------------------------------------------------------------------------- - private Hashtable GetCommonWords(string locale) - { - string strCacheKey = "CommonWords" + locale; - var objWords = (Hashtable)DataCache.GetCache(strCacheKey); - if (objWords == null) - { - objWords = new Hashtable(); - IDataReader drWords = DataProvider.Instance().GetSearchCommonWordsByLocale(locale); - try - { - while (drWords.Read()) - { - objWords.Add(drWords["CommonWord"].ToString(), drWords["CommonWord"].ToString()); - } - } - finally - { - drWords.Close(); - drWords.Dispose(); - } - - DataCache.SetCache(strCacheKey, objWords); - } - - return objWords; - } - /// ----------------------------------------------------------------------------- /// /// GetSearchItems gets a collection of Search Items for a Module/Tab/Portal. @@ -240,6 +204,42 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin // Return Search Results Collection return results; } + + /// ----------------------------------------------------------------------------- + /// + /// GetCommonWords gets a list of the Common Words for the locale. + /// + /// + /// + /// The locale string. + /// A hashtable of common words. + /// ----------------------------------------------------------------------------- + private Hashtable GetCommonWords(string locale) + { + string strCacheKey = "CommonWords" + locale; + var objWords = (Hashtable)DataCache.GetCache(strCacheKey); + if (objWords == null) + { + objWords = new Hashtable(); + IDataReader drWords = DataProvider.Instance().GetSearchCommonWordsByLocale(locale); + try + { + while (drWords.Read()) + { + objWords.Add(drWords["CommonWord"].ToString(), drWords["CommonWord"].ToString()); + } + } + finally + { + drWords.Close(); + drWords.Dispose(); + } + + DataCache.SetCache(strCacheKey, objWords); + } + + return objWords; + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Services/Search/SearchEngine.cs b/DNN Platform/Library/Services/Search/SearchEngine.cs index 04be5ef8bd9..0d1aa87637c 100644 --- a/DNN Platform/Library/Services/Search/SearchEngine.cs +++ b/DNN Platform/Library/Services/Search/SearchEngine.cs @@ -86,11 +86,6 @@ internal void IndexContent() this.SchedulerItem.AddLogNote("
Total Items Indexed: " + indexedSearchDocumentCount + ""); } - private void AddIdexingResults(string description, int count) - { - this.SchedulerItem.AddLogNote(string.Format("
  {0}: {1}", description, count)); - } - internal bool CompactSearchIndexIfNeeded(ScheduleHistoryItem scheduleItem) { var shelper = SearchHelper.Instance; @@ -123,6 +118,11 @@ internal void DeleteOldDocsBeforeReindex() } } + private void AddIdexingResults(string description, int count) + { + this.SchedulerItem.AddLogNote(string.Format("
  {0}: {1}", description, count)); + } + /// /// Deletes all deleted items from the system that are added to deletions table. /// @@ -157,6 +157,72 @@ internal void Commit() InternalSearchController.Instance.Commit(); } + /// ----------------------------------------------------------------------------- + /// + /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. + /// Used for Legacy Search (ISearchable) + /// + /// GetContent gets all the content and passes it to the Indexer. + /// + /// + /// + /// The Index Provider that will index the content of the portal. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] + protected SearchItemInfoCollection GetContent(IndexingProviderBase indexer) + { + var searchItems = new SearchItemInfoCollection(); + var portals = PortalController.Instance.GetPortals(); + for (var index = 0; index <= portals.Count - 1; index++) + { + var portal = (PortalInfo)portals[index]; + searchItems.AddRange(indexer.GetSearchIndexItems(portal.PortalID)); + } + + return searchItems; + } + + /// ----------------------------------------------------------------------------- + /// + /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. + /// Used for Legacy Search (ISearchable) + /// + /// GetContent gets the Portal's content and passes it to the Indexer. + /// + /// + /// + /// The Id of the Portal. + /// The Index Provider that will index the content of the portal. + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] + protected SearchItemInfoCollection GetContent(int portalId, IndexingProvider indexer) + { + var searchItems = new SearchItemInfoCollection(); + searchItems.AddRange(indexer.GetSearchIndexItems(portalId)); + return searchItems; + } + + /// ----------------------------------------------------------------------------- + /// + /// Ensures all SearchDocuments have a SearchTypeId. + /// + /// + /// ----------------------------------------------------------------------------- + private static void StoreSearchDocuments(IEnumerable searchDocs) + { + var defaultSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; + + var searchDocumentList = searchDocs as IList ?? searchDocs.ToList(); + foreach (var searchDocument in searchDocumentList.Where(searchDocument => searchDocument.SearchTypeId <= 0)) + { + searchDocument.SearchTypeId = defaultSearchTypeId; + } + + InternalSearchController.Instance.AddSearchDocuments(searchDocumentList); + } + /// ----------------------------------------------------------------------------- /// /// Gets all the Search Documents for the given timeframe. @@ -237,25 +303,6 @@ private int GetAndStoreModuleMetaData(ModuleIndexer indexer) return indexedCount; } - /// ----------------------------------------------------------------------------- - /// - /// Ensures all SearchDocuments have a SearchTypeId. - /// - /// - /// ----------------------------------------------------------------------------- - private static void StoreSearchDocuments(IEnumerable searchDocs) - { - var defaultSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; - - var searchDocumentList = searchDocs as IList ?? searchDocs.ToList(); - foreach (var searchDocument in searchDocumentList.Where(searchDocument => searchDocument.SearchTypeId <= 0)) - { - searchDocument.SearchTypeId = defaultSearchTypeId; - } - - InternalSearchController.Instance.AddSearchDocuments(searchDocumentList); - } - /// ----------------------------------------------------------------------------- /// /// Adjusts the re-index date/time to account for the portal reindex value. @@ -272,52 +319,5 @@ private DateTime FixedIndexingStartDate(int portalId) return startDate; } - - /// ----------------------------------------------------------------------------- - /// - /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. - /// Used for Legacy Search (ISearchable) - /// - /// GetContent gets all the content and passes it to the Indexer. - /// - /// - /// - /// The Index Provider that will index the content of the portal. - /// - /// ----------------------------------------------------------------------------- - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - protected SearchItemInfoCollection GetContent(IndexingProviderBase indexer) - { - var searchItems = new SearchItemInfoCollection(); - var portals = PortalController.Instance.GetPortals(); - for (var index = 0; index <= portals.Count - 1; index++) - { - var portal = (PortalInfo)portals[index]; - searchItems.AddRange(indexer.GetSearchIndexItems(portal.PortalID)); - } - - return searchItems; - } - - /// ----------------------------------------------------------------------------- - /// - /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. - /// Used for Legacy Search (ISearchable) - /// - /// GetContent gets the Portal's content and passes it to the Indexer. - /// - /// - /// - /// The Id of the Portal. - /// The Index Provider that will index the content of the portal. - /// - /// ----------------------------------------------------------------------------- - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - protected SearchItemInfoCollection GetContent(int portalId, IndexingProvider indexer) - { - var searchItems = new SearchItemInfoCollection(); - searchItems.AddRange(indexer.GetSearchIndexItems(portalId)); - return searchItems; - } } } diff --git a/DNN Platform/Library/Services/Search/UserIndexer.cs b/DNN Platform/Library/Services/Search/UserIndexer.cs index 13adf88aff1..395fecfc272 100644 --- a/DNN Platform/Library/Services/Search/UserIndexer.cs +++ b/DNN Platform/Library/Services/Search/UserIndexer.cs @@ -140,13 +140,6 @@ public override int IndexSearchDocuments( return totalIndexed; } - private int IndexCollectedDocs(Action> indexer, ICollection searchDocuments) - { - indexer.Invoke(searchDocuments); - var total = searchDocuments.Select(d => d.UniqueKey.Substring(0, d.UniqueKey.IndexOf("_", StringComparison.Ordinal))).Distinct().Count(); - return total; - } - private static int FindModifiedUsers(int portalId, DateTime startDateLocal, IDictionary searchDocuments, IList profileDefinitions, out IList indexedUsers, ref int startUserId) @@ -311,6 +304,13 @@ private static void AddBasicInformation(IDictionary sear } } + private int IndexCollectedDocs(Action> indexer, ICollection searchDocuments) + { + indexer.Invoke(searchDocuments); + var total = searchDocuments.Select(d => d.UniqueKey.Substring(0, d.UniqueKey.IndexOf("_", StringComparison.Ordinal))).Distinct().Count(); + return total; + } + private static UserSearch GetUserSearch(IDataRecord reader) { try @@ -361,9 +361,9 @@ private static void DeleteDocuments(int portalId, ICollection usersList) keyword.AppendFormat("{2} {0}_{1} OR {0}_{1}* ", userId, mode, keyword.Length > 1 ? "OR " : string.Empty); clauseCount += 2; - if (clauseCount >= ClauseMaxCount) + if (clauseCount >= ClauseMaxCount) - // max cluaseCount is 1024, if reach the max value, perform a delete action. + // max cluaseCount is 1024, if reach the max value, perform a delete action. { keyword.Append(")"); PerformDelete(portalId, keyword.ToString().ToLowerInvariant()); diff --git a/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs b/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs index bf223ae90e2..cc3365021c8 100644 --- a/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs +++ b/DNN Platform/Library/Services/Sitemap/CoreSitemapProvider.cs @@ -21,9 +21,9 @@ namespace DotNetNuke.Services.Sitemap public class CoreSitemapProvider : SitemapProvider { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CoreSitemapProvider)); private bool includeHiddenPages; private float minPagePriority; - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CoreSitemapProvider)); private bool useLevelBasedPagePriority; @@ -91,6 +91,78 @@ public override List GetUrls(int portalId, PortalSettings ps, string return urls; } + public virtual bool IsTabPublic(TabPermissionCollection objTabPermissions) + { + string roles = objTabPermissions.ToString("VIEW"); + bool hasPublicRole = false; + + if (roles != null) + { + // permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance + foreach (string role in roles.Split(new[] { ';' })) + { + if (!string.IsNullOrEmpty(role)) + { + // Deny permission + if (role.StartsWith("!")) + { + string denyRole = role.Replace("!", string.Empty); + if (denyRole == Globals.glbRoleUnauthUserName || denyRole == Globals.glbRoleAllUsersName) + { + hasPublicRole = false; + break; + } + + // Grant permission + } + else + { + if (role == Globals.glbRoleUnauthUserName || role == Globals.glbRoleAllUsersName) + { + hasPublicRole = true; + break; + } + } + } + } + } + + return hasPublicRole; + } + + /// + /// When page level priority is used, the priority for each page will be computed from + /// the hierarchy level of the page. + /// Top level pages will have a value of 1, second level 0.9, third level 0.8, ... + /// + /// The page being indexed. + /// The priority assigned to the page. + /// + /// + protected float GetPriority(TabInfo objTab) + { + float priority = objTab.SiteMapPriority; + + if (this.useLevelBasedPagePriority) + { + if (objTab.Level >= 9) + { + priority = 0.1F; + } + else + { + priority = Convert.ToSingle(1 - (objTab.Level * 0.1)); + } + + if (priority < this.minPagePriority) + { + priority = this.minPagePriority; + } + } + + return priority; + } + /// /// Return the sitemap url node for the page. /// @@ -165,77 +237,5 @@ private SitemapUrl GetPageUrl(TabInfo objTab, string language, PortalSettings ps return pageUrl; } - - /// - /// When page level priority is used, the priority for each page will be computed from - /// the hierarchy level of the page. - /// Top level pages will have a value of 1, second level 0.9, third level 0.8, ... - /// - /// The page being indexed. - /// The priority assigned to the page. - /// - /// - protected float GetPriority(TabInfo objTab) - { - float priority = objTab.SiteMapPriority; - - if (this.useLevelBasedPagePriority) - { - if (objTab.Level >= 9) - { - priority = 0.1F; - } - else - { - priority = Convert.ToSingle(1 - (objTab.Level * 0.1)); - } - - if (priority < this.minPagePriority) - { - priority = this.minPagePriority; - } - } - - return priority; - } - - public virtual bool IsTabPublic(TabPermissionCollection objTabPermissions) - { - string roles = objTabPermissions.ToString("VIEW"); - bool hasPublicRole = false; - - if (roles != null) - { - // permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance - foreach (string role in roles.Split(new[] { ';' })) - { - if (!string.IsNullOrEmpty(role)) - { - // Deny permission - if (role.StartsWith("!")) - { - string denyRole = role.Replace("!", string.Empty); - if (denyRole == Globals.glbRoleUnauthUserName || denyRole == Globals.glbRoleAllUsersName) - { - hasPublicRole = false; - break; - } - - // Grant permission - } - else - { - if (role == Globals.glbRoleUnauthUserName || role == Globals.glbRoleAllUsersName) - { - hasPublicRole = true; - break; - } - } - } - } - } - - return hasPublicRole; - } } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs b/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs index 8a65c34a4bc..7bdfa9ed702 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs @@ -24,10 +24,28 @@ public class SitemapBuilder private const int SITEMAP_MAXURLS = 50000; private const string SITEMAP_VERSION = "0.9"; + private static readonly object _lock = new object(); + + private static List _providers; + private readonly PortalSettings PortalSettings; private string _cacheFileName; private string _cacheIndexFileNameFormat; + /// + /// Initializes a new instance of the class. + /// Creates an instance of the sitemap builder class. + /// + /// Current PortalSettings for the portal being processed. + /// + /// + public SitemapBuilder(PortalSettings ps) + { + this.PortalSettings = ps; + + LoadProviders(); + } + public string CacheFileName { get @@ -60,20 +78,14 @@ public string CacheIndexFileNameFormat return this._cacheIndexFileNameFormat; } } - - /// - /// Initializes a new instance of the class. - /// Creates an instance of the sitemap builder class. - /// - /// Current PortalSettings for the portal being processed. - /// - /// - public SitemapBuilder(PortalSettings ps) - { - this.PortalSettings = ps; - LoadProviders(); - } + public List Providers + { + get + { + return _providers; + } + } /// /// Builds the complete portal sitemap. @@ -418,18 +430,6 @@ private bool IsChildPortal(PortalSettings ps, HttpContext context) return isChild; } - private static List _providers; - - private static readonly object _lock = new object(); - - public List Providers - { - get - { - return _providers; - } - } - private static void LoadProviders() { // Avoid claiming lock if providers are already loaded diff --git a/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs b/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs index a0cff99367c..9a661f66d32 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Data/DataService.cs @@ -378,12 +378,12 @@ public IList GetMessageAttachmentsByMessage(int messageId) } var attachment = new MessageFileView - { - Name = file.FileName, - Size = file.Size.ToString(CultureInfo.InvariantCulture), - Url = FileManager.Instance.GetUrl(file), - FileId = fileId, - }; + { + Name = file.FileName, + Size = file.Size.ToString(CultureInfo.InvariantCulture), + Url = FileManager.Instance.GetUrl(file), + FileId = fileId, + }; attachments.Add(attachment); } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs index 9ef78a9eebb..d3e72276cd4 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs @@ -380,8 +380,33 @@ public virtual int CountArchivedConversations(int userId, int portalId) /// The message identifier. /// A list of message attachments for the given message. public IEnumerable GetAttachments(int messageId) + { + return this._dataService.GetMessageAttachmentsByMessage(messageId); + } + + public void ConvertLegacyMessages(int pageIndex, int pageSize) { - return this._dataService.GetMessageAttachmentsByMessage(messageId); + this._dataService.ConvertLegacyMessages(pageIndex, pageSize); + } + + public int CountLegacyMessages() + { + var totalRecords = 0; + var dr = this._dataService.CountLegacyMessages(); + + try + { + while (dr.Read()) + { + totalRecords = Convert.ToInt32(dr["TotalRecords"]); + } + } + finally + { + CBO.CloseDataReader(dr, true); + } + + return totalRecords; } internal virtual DateTime GetDateTimeNow() @@ -420,31 +445,6 @@ internal virtual string InputFilter(string input) return ps.InputFilter(input, PortalSecurity.FilterFlag.NoProfanity); } - public void ConvertLegacyMessages(int pageIndex, int pageSize) - { - this._dataService.ConvertLegacyMessages(pageIndex, pageSize); - } - - public int CountLegacyMessages() - { - var totalRecords = 0; - var dr = this._dataService.CountLegacyMessages(); - - try - { - while (dr.Read()) - { - totalRecords = Convert.ToInt32(dr["TotalRecords"]); - } - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return totalRecords; - } - public IList GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize) { return CBO.FillCollection(this._dataService.GetNextMessagesForInstantDispatch(schedulerInstance, batchSize)); diff --git a/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs index 24bca3df61a..58c930106d3 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs @@ -34,14 +34,14 @@ public class MessagingController : ServiceLocator, IMessagingController { + internal const int ConstMaxTo = 2000; + internal const int ConstMaxSubject = 400; + internal const int ConstDefaultPageIndex = 0; + protected override Func GetFactory() { return () => new MessagingController(); } - - internal const int ConstMaxTo = 2000; - internal const int ConstMaxSubject = 400; - internal const int ConstDefaultPageIndex = 0; internal const int ConstDefaultPageSize = 10; internal const string ConstSortColumnDate = "CreatedOnDate"; internal const string ConstSortColumnFrom = "From"; diff --git a/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs b/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs index 8901e8c46d0..9c01eea179f 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs @@ -416,6 +416,43 @@ private static object GetMessageTabCallback(CacheItemArgs cacheItemArgs) return portalSettings.UserTabId; } + private static string RemoveHttpUrlsIfSiteisSSLEnabled(string stringContainingHttp, PortalSettings portalSettings) + { + if (stringContainingHttp.IndexOf("http") > -1 && portalSettings != null && (portalSettings.SSLEnabled || portalSettings.SSLEnforced)) + { + var urlToReplace = GetPortalHomeUrl(portalSettings); + var urlReplaceWith = $"https://{portalSettings.DefaultPortalAlias}"; + stringContainingHttp = stringContainingHttp.Replace(urlToReplace, urlReplaceWith); + } + + return stringContainingHttp; + } + + private static string ResolveUrl(PortalSettings portalSettings, string template) + { + const string linkRegex = "(href|src)=\"(/[^\"]*?)\""; + var matches = Regex.Matches(template, linkRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); + foreach (Match match in matches) + { + var link = match.Groups[2].Value; + var defaultAlias = portalSettings.DefaultPortalAlias; + var domain = Globals.AddHTTP(defaultAlias); + if (defaultAlias.Contains("/")) + { + var subDomain = + defaultAlias.Substring(defaultAlias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase)); + if (link.StartsWith(subDomain, StringComparison.InvariantCultureIgnoreCase)) + { + link = link.Substring(subDomain.Length); + } + } + + template = template.Replace(match.Value, $"{match.Groups[1].Value}=\"{domain}{link}\""); + } + + return template; + } + /// Handles the frequent digests. /// The scheduler instance. /// The remaining messages. @@ -570,18 +607,6 @@ private void SendDigest(IEnumerable messages, PortalSettings p MarkMessagesAsDispatched(messageRecipients); } - private static string RemoveHttpUrlsIfSiteisSSLEnabled(string stringContainingHttp, PortalSettings portalSettings) - { - if (stringContainingHttp.IndexOf("http") > -1 && portalSettings != null && (portalSettings.SSLEnabled || portalSettings.SSLEnforced)) - { - var urlToReplace = GetPortalHomeUrl(portalSettings); - var urlReplaceWith = $"https://{portalSettings.DefaultPortalAlias}"; - stringContainingHttp = stringContainingHttp.Replace(urlToReplace, urlReplaceWith); - } - - return stringContainingHttp; - } - /// Gets the schedule item date setting. /// The setting key. /// The date the schedule was ran. @@ -718,30 +743,5 @@ private IEnumerable CreateAttachments(int messageId) } } } - - private static string ResolveUrl(PortalSettings portalSettings, string template) - { - const string linkRegex = "(href|src)=\"(/[^\"]*?)\""; - var matches = Regex.Matches(template, linkRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); - foreach (Match match in matches) - { - var link = match.Groups[2].Value; - var defaultAlias = portalSettings.DefaultPortalAlias; - var domain = Globals.AddHTTP(defaultAlias); - if (defaultAlias.Contains("/")) - { - var subDomain = - defaultAlias.Substring(defaultAlias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase)); - if (link.StartsWith(subDomain, StringComparison.InvariantCultureIgnoreCase)) - { - link = link.Substring(subDomain.Length); - } - } - - template = template.Replace(match.Value, $"{match.Groups[1].Value}=\"{domain}{link}\""); - } - - return template; - } } } diff --git a/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs b/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs index 972f1182364..fb2769ab73d 100644 --- a/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs @@ -16,11 +16,6 @@ public class UserPreferencesController : ServiceLocator GetFactory() - { - return () => new UserPreferencesController(); - } - public UserPreferencesController() : this(DataService.Instance) { @@ -38,6 +33,11 @@ public void SetUserPreference(UserPreference userPreference) { this.dataService.SetUserPreference(userPreference.PortalId, userPreference.UserId, Convert.ToInt32(userPreference.MessagesEmailFrequency), Convert.ToInt32(userPreference.NotificationsEmailFrequency)); } + + protected override Func GetFactory() + { + return () => new UserPreferencesController(); + } public UserPreference GetUserPreference(UserInfo userinfo) { diff --git a/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs b/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs index 8e169852941..76a787d8b9e 100644 --- a/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs @@ -13,13 +13,8 @@ namespace DotNetNuke.Services.Social.Notifications.Data internal class DataService : ComponentBase, IDataService { - private readonly DataProvider _provider = DataProvider.Instance(); private const string Prefix = "CoreMessaging_"; - - private static string GetFullyQualifiedName(string procedureName) - { - return Prefix + procedureName; - } + private readonly DataProvider _provider = DataProvider.Instance(); public int CreateNotificationType(string name, string description, int timeToLive, int desktopModuleId, int createUpdateUserId, bool isTask) { @@ -30,6 +25,11 @@ public void DeleteNotificationType(int notificationTypeId) { this._provider.ExecuteNonQuery(GetFullyQualifiedName("DeleteNotificationType"), notificationTypeId); } + + private static string GetFullyQualifiedName(string procedureName) + { + return Prefix + procedureName; + } public IDataReader GetNotificationType(int notificationTypeId) { diff --git a/DNN Platform/Library/Services/Social/Notifications/Notification.cs b/DNN Platform/Library/Services/Social/Notifications/Notification.cs index 209943afd0f..1a8b4598059 100644 --- a/DNN Platform/Library/Services/Social/Notifications/Notification.cs +++ b/DNN Platform/Library/Services/Social/Notifications/Notification.cs @@ -27,6 +27,15 @@ public class Notification : BaseEntityInfo, IHydratable private int _notificationID = -1; private string _displayDate; + /// + /// Initializes a new instance of the class. + /// Default constructor. + /// + public Notification() + { + this.SendToast = true; + } + /// /// Gets or sets notificationID - The primary key. /// @@ -138,15 +147,6 @@ public int KeyID [XmlAttribute] public bool SendToast { get; set; } - /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - public Notification() - { - this.SendToast = true; - } - /// /// Fill the object with data from database. /// diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs index c7bb8efaa72..b0e6660182e 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs @@ -30,14 +30,14 @@ public class NotificationsController : ServiceLocator, INotificationsController { + internal const int ConstMaxSubject = 400; + internal const int ConstMaxTo = 2000; + private const string ToastsCacheKey = "GetToasts_{0}"; + protected override Func GetFactory() { return () => new NotificationsController(); } - - internal const int ConstMaxSubject = 400; - internal const int ConstMaxTo = 2000; - private const string ToastsCacheKey = "GetToasts_{0}"; private readonly IDataService _dataService; private readonly Messaging.Data.IDataService _messagingDataService; @@ -206,13 +206,13 @@ public virtual void SendNotification(Notification notification, int portalId, IL var recipients = from user in users where InternalMessagingController.Instance.GetMessageRecipient(notification.NotificationID, user.UserID) == null - select new MessageRecipient - { - MessageID = notification.NotificationID, - UserID = user.UserID, - Read = false, - RecipientID = Null.NullInteger, - }; + select new MessageRecipient + { + MessageID = notification.NotificationID, + UserID = user.UserID, + Read = false, + RecipientID = Null.NullInteger, + }; foreach (var recipient in recipients) { diff --git a/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs b/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs index fa8e4ef63b7..48337777654 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs @@ -18,11 +18,6 @@ public DataService() { this.provider = DataProvider.Instance(); } - - protected override Func GetFactory() - { - return () => new DataService(); - } public int AddSubscriptionType(string subscriptionName, string friendlyName, int desktopModuleId) { @@ -34,6 +29,11 @@ public IDataReader GetSubscriptionTypes() return this.provider.ExecuteReader("CoreMessaging_GetSubscriptionTypes"); } + protected override Func GetFactory() + { + return () => new DataService(); + } + public bool DeleteSubscriptionType(int subscriptionTypeId) { return this.provider.ExecuteScalar("CoreMessaging_DeleteSubscriptionType", subscriptionTypeId) == 0; diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs index 681bb468fc0..d78797d957b 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs @@ -28,11 +28,6 @@ public SubscriptionController() this.dataService = DataService.Instance; this.subscriptionSecurityController = SubscriptionSecurityController.Instance; } - - protected override Func GetFactory() - { - return () => new SubscriptionController(); - } public IEnumerable GetUserSubscriptions(UserInfo user, int portalId, int subscriptionTypeId = -1) { @@ -54,6 +49,11 @@ public IEnumerable GetContentSubscriptions(int portalId, int subsc return subscriptions.Where(s => this.subscriptionSecurityController.HasPermission(s)); } + protected override Func GetFactory() + { + return () => new SubscriptionController(); + } + public bool IsSubscribed(Subscription subscription) { var fetchedSubscription = CBO.FillObject(this.dataService.IsSubscribed( diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs index d349e611b14..12ccfa470ad 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs @@ -20,11 +20,6 @@ namespace DotNetNuke.Services.Social.Subscriptions /// public class SubscriptionSecurityController : ServiceLocator, ISubscriptionSecurityController { - protected override Func GetFactory() - { - return () => new SubscriptionSecurityController(); - } - public bool HasPermission(Subscription subscription) { var userInfo = GetUserFromSubscription(subscription); @@ -44,6 +39,11 @@ public bool HasPermission(Subscription subscription) return true; } + protected override Func GetFactory() + { + return () => new SubscriptionSecurityController(); + } + private static bool HasUserModuleViewPermission(UserInfo userInfo, ModuleInfo moduleInfo) { var portalSettings = new PortalSettings(moduleInfo.PortalID); diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs index ffd482b715a..f17a76f7c3e 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs @@ -25,11 +25,6 @@ public SubscriptionTypeController() { this.dataService = DataService.Instance; } - - protected override Func GetFactory() - { - return () => new SubscriptionTypeController(); - } public void AddSubscriptionType(SubscriptionType subscriptionType) { @@ -50,6 +45,11 @@ public SubscriptionType GetSubscriptionType(Func predica return this.GetSubscriptionTypes().SingleOrDefault(predicate); } + protected override Func GetFactory() + { + return () => new SubscriptionTypeController(); + } + public IEnumerable GetSubscriptionTypes() { var cacheArgs = new CacheItemArgs( diff --git a/DNN Platform/Library/Services/Syndication/RssHandler.cs b/DNN Platform/Library/Services/Syndication/RssHandler.cs index 0fcac5a1f67..620acece9dd 100644 --- a/DNN Platform/Library/Services/Syndication/RssHandler.cs +++ b/DNN Platform/Library/Services/Syndication/RssHandler.cs @@ -89,6 +89,21 @@ protected override void PopulateChannel(string channelName, string userName) } } + /// + /// The PreRender event is used to set the Caching Policy for the Feed. This mimics the behavior from the + /// OutputCache directive in the old Rss.aspx file. @OutputCache Duration="60" VaryByParam="moduleid". + /// + /// Event Args. + /// + protected override void OnPreRender(EventArgs ea) + { + base.OnPreRender(ea); + + this.Context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); + this.Context.Response.Cache.SetCacheability(HttpCacheability.Public); + this.Context.Response.Cache.VaryByParams["moduleid"] = true; + } + /// /// Creates an RSS Item. /// @@ -116,20 +131,5 @@ private GenericRssElement GetRssItem(SearchResult searchResult) return item; } - - /// - /// The PreRender event is used to set the Caching Policy for the Feed. This mimics the behavior from the - /// OutputCache directive in the old Rss.aspx file. @OutputCache Duration="60" VaryByParam="moduleid". - /// - /// Event Args. - /// - protected override void OnPreRender(EventArgs ea) - { - base.OnPreRender(ea); - - this.Context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); - this.Context.Response.Cache.SetCacheability(HttpCacheability.Public); - this.Context.Response.Cache.VaryByParams["moduleid"] = true; - } } } diff --git a/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs b/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs index c450706dfd7..ada00e37b88 100644 --- a/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs @@ -27,12 +27,6 @@ public abstract class BaseCustomTokenReplace : BaseTokenReplace /// UserInfo oject. public UserInfo AccessingUser { get; set; } - /// - /// Gets or sets /sets the current Access Level controlling access to critical user settings. - /// - /// A TokenAccessLevel as defined above. - protected Scope CurrentAccessLevel { get; set; } - /// /// Gets or sets a value indicating whether if DebugMessages are enabled, unknown Tokens are replaced with Error Messages. /// @@ -43,50 +37,11 @@ public abstract class BaseCustomTokenReplace : BaseTokenReplace /// public bool DebugMessages { get; set; } - protected override string replacedTokenValue(string objectName, string propertyName, string format) - { - string result = string.Empty; - bool propertyNotFound = false; - if (this.PropertySource.ContainsKey(objectName.ToLowerInvariant())) - { - result = this.PropertySource[objectName.ToLowerInvariant()].GetProperty(propertyName, format, this.FormatProvider, this.AccessingUser, this.CurrentAccessLevel, ref propertyNotFound); - } - else - { - if (this.DebugMessages) - { - string message = Localization.GetString("TokenReplaceUnknownObject", Localization.SharedResourceFile, this.FormatProvider.ToString()); - if (message == string.Empty) - { - message = "Error accessing [{0}:{1}], {0} is an unknown datasource"; - } - - result = string.Format(message, objectName, propertyName); - } - } - - if (this.DebugMessages && propertyNotFound) - { - string message; - if (result == PropertyAccess.ContentLocked) - { - message = Localization.GetString("TokenReplaceRestrictedProperty", Localization.GlobalResourceFile, this.FormatProvider.ToString()); - } - else - { - message = Localization.GetString("TokenReplaceUnknownProperty", Localization.GlobalResourceFile, this.FormatProvider.ToString()); - } - - if (message == string.Empty) - { - message = "Error accessing [{0}:{1}], {1} is unknown for datasource {0}"; - } - - result = string.Format(message, objectName, propertyName); - } - - return result; - } + /// + /// Gets or sets /sets the current Access Level controlling access to critical user settings. + /// + /// A TokenAccessLevel as defined above. + protected Scope CurrentAccessLevel { get; set; } /// /// returns cacheability of the passed text regarding all contained tokens. @@ -143,5 +98,50 @@ public bool ContainsTokens(string strSourceText) return false; } + + protected override string replacedTokenValue(string objectName, string propertyName, string format) + { + string result = string.Empty; + bool propertyNotFound = false; + if (this.PropertySource.ContainsKey(objectName.ToLowerInvariant())) + { + result = this.PropertySource[objectName.ToLowerInvariant()].GetProperty(propertyName, format, this.FormatProvider, this.AccessingUser, this.CurrentAccessLevel, ref propertyNotFound); + } + else + { + if (this.DebugMessages) + { + string message = Localization.GetString("TokenReplaceUnknownObject", Localization.SharedResourceFile, this.FormatProvider.ToString()); + if (message == string.Empty) + { + message = "Error accessing [{0}:{1}], {0} is an unknown datasource"; + } + + result = string.Format(message, objectName, propertyName); + } + } + + if (this.DebugMessages && propertyNotFound) + { + string message; + if (result == PropertyAccess.ContentLocked) + { + message = Localization.GetString("TokenReplaceRestrictedProperty", Localization.GlobalResourceFile, this.FormatProvider.ToString()); + } + else + { + message = Localization.GetString("TokenReplaceUnknownProperty", Localization.GlobalResourceFile, this.FormatProvider.ToString()); + } + + if (message == string.Empty) + { + message = "Error accessing [{0}:{1}], {1} is unknown for datasource {0}"; + } + + result = string.Format(message, objectName, propertyName); + } + + return result; + } } } diff --git a/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs b/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs index e19b393d2e9..b811555bcb1 100644 --- a/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs @@ -20,6 +20,8 @@ namespace DotNetNuke.Services.Tokens /// public abstract class BaseTokenReplace { + protected const string ObjectLessToken = "no_object"; + private const string ExpressionDefault = "(?:(?\\[\\])|\\[(?:(?[^{}\\]\\[:]+):(?[^\\]\\[\\|]+))(?:\\|(?:(?[^\\]\\[]+)\\|(?[^\\]\\[]+))|\\|(?:(?[^\\|\\]\\[]+)))?\\])|(?\\[[^\\]\\[]+\\])|(?[^\\]\\[]+)"; @@ -34,19 +36,6 @@ public abstract class BaseTokenReplace private CultureInfo _formatProvider; private string _language; - protected const string ObjectLessToken = "no_object"; - - protected bool UseObjectLessExpression { get; set; } - - /// - /// Gets the Format provider as Culture info from stored language or current culture. - /// - /// An CultureInfo. - protected CultureInfo FormatProvider - { - get { return this._formatProvider ?? (this._formatProvider = Thread.CurrentThread.CurrentUICulture); } - } - /// /// Gets or sets /sets the language to be used, e.g. for date format. /// @@ -65,6 +54,17 @@ public string Language } } + protected bool UseObjectLessExpression { get; set; } + + /// + /// Gets the Format provider as Culture info from stored language or current culture. + /// + /// An CultureInfo. + protected CultureInfo FormatProvider + { + get { return this._formatProvider ?? (this._formatProvider = Thread.CurrentThread.CurrentUICulture); } + } + /// /// Gets the Regular expression for the token to be replaced. /// diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs index a88233b60f8..e97ebf69ee9 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs @@ -17,6 +17,14 @@ public ArrayListPropertyAccess(ArrayList list) { this.custom = list; } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { @@ -62,13 +70,5 @@ public string GetProperty(string propertyName, string format, CultureInfo format return string.Empty; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs index 66863a37f3d..3a53aa65809 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs @@ -11,6 +11,14 @@ namespace DotNetNuke.Services.Tokens public class CulturePropertyAccess : IPropertyAccess { + 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; @@ -104,13 +112,5 @@ public string GetProperty(string propertyName, string format, CultureInfo format PropertyNotFound = true; return string.Empty; } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs index 9591ab76b0c..93dbfb2d065 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs @@ -17,6 +17,14 @@ public DataRowPropertyAccess(DataRow row) { this.dr = row; } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { @@ -56,13 +64,5 @@ public string GetProperty(string propertyName, string format, CultureInfo format return string.Empty; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs index de5c9185158..33c70ff51f3 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs @@ -10,6 +10,14 @@ namespace DotNetNuke.Services.Tokens public class DateTimePropertyAccess : IPropertyAccess { + public CacheLevel Cacheability + { + get + { + return CacheLevel.secureforCaching; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { TimeZoneInfo userTimeZone = AccessingUser.Profile.PreferredTimeZone; @@ -48,13 +56,5 @@ public string GetProperty(string propertyName, string format, CultureInfo format return string.Empty; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.secureforCaching; - } - } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs index 0c89716a72d..aefa16d06a5 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs @@ -17,6 +17,14 @@ public DictionaryPropertyAccess(IDictionary list) { this.NameValueCollection = list; } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } public virtual string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { @@ -56,13 +64,5 @@ public virtual string GetProperty(string propertyName, string format, CultureInf return string.Empty; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs index dc086925124..bf9ca9e1d52 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs @@ -13,11 +13,6 @@ namespace DotNetNuke.Services.Tokens /// public class EmptyPropertyAccess : IPropertyAccess { - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) - { - return string.Empty; - } - public CacheLevel Cacheability { get @@ -25,5 +20,10 @@ public CacheLevel Cacheability return CacheLevel.notCacheable; } } + + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) + { + return string.Empty; + } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs index c554bd3fb0b..a334d3622f3 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs @@ -32,16 +32,6 @@ public static string ContentLocked return "*******"; } } - - public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) - { - if (this.obj == null) - { - return string.Empty; - } - - return GetObjectProperty(this.obj, propertyName, format, formatProvider, ref PropertyNotFound); - } public CacheLevel Cacheability { @@ -86,6 +76,16 @@ public static string FormatString(string value, string format) return string.Empty; } } + + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) + { + if (this.obj == null) + { + return string.Empty; + } + + return GetObjectProperty(this.obj, propertyName, format, formatProvider, ref PropertyNotFound); + } /// /// Returns the localized property of any object as string using reflection. diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs index ff641d12d80..5b0ee6de526 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs @@ -13,6 +13,14 @@ namespace DotNetNuke.Services.Tokens public class TicksPropertyAccess : IPropertyAccess { + public CacheLevel Cacheability + { + get + { + return CacheLevel.secureforCaching; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { switch (propertyName.ToLowerInvariant()) @@ -28,13 +36,5 @@ public string GetProperty(string propertyName, string format, CultureInfo format PropertyNotFound = true; return string.Empty; } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.secureforCaching; - } - } } } diff --git a/DNN Platform/Library/Services/Tokens/TokenReplace.cs b/DNN Platform/Library/Services/Tokens/TokenReplace.cs index 2ac4e062317..0bfa86c1681 100644 --- a/DNN Platform/Library/Services/Tokens/TokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/TokenReplace.cs @@ -192,6 +192,30 @@ public ModuleInfo ModuleInfo /// UserInfo oject. public UserInfo User { get; set; } + /// + /// Replaces tokens in sourceText parameter with the property values. + /// + /// String with [Object:Property] tokens. + /// string containing replaced values. + public string ReplaceEnvironmentTokens(string sourceText) + { + return this.ReplaceTokens(sourceText); + } + + /// + /// Replaces tokens in sourceText parameter with the property values. + /// + /// String with [Object:Property] tokens. + /// + /// string containing replaced values. + public string ReplaceEnvironmentTokens(string sourceText, DataRow row) + { + var rowProperties = new DataRowPropertyAccess(row); + this.PropertySource["field"] = rowProperties; + this.PropertySource["row"] = rowProperties; + return this.ReplaceTokens(sourceText); + } + /// /// setup context by creating appropriate objects. /// @@ -234,30 +258,6 @@ private void InitializePropertySources() } } - /// - /// Replaces tokens in sourceText parameter with the property values. - /// - /// String with [Object:Property] tokens. - /// string containing replaced values. - public string ReplaceEnvironmentTokens(string sourceText) - { - return this.ReplaceTokens(sourceText); - } - - /// - /// Replaces tokens in sourceText parameter with the property values. - /// - /// String with [Object:Property] tokens. - /// - /// string containing replaced values. - public string ReplaceEnvironmentTokens(string sourceText, DataRow row) - { - var rowProperties = new DataRowPropertyAccess(row); - this.PropertySource["field"] = rowProperties; - this.PropertySource["row"] = rowProperties; - return this.ReplaceTokens(sourceText); - } - /// /// Replaces tokens in sourceText parameter with the property values. /// diff --git a/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs b/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs index d47ab5fc937..b2078103a3a 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs @@ -19,6 +19,8 @@ namespace DotNetNuke.Services.Upgrade.Internals /// public interface IInstallController { + string InstallerLogName { get; } + bool IsValidSqlServerVersion(string connectionString); bool IsAbleToPerformDatabaseActions(string connectionString); @@ -57,7 +59,5 @@ public interface IInstallController string TestDatabaseConnection(ConnectionConfig connectionConfig); CultureInfo GetCultureFromCookie(); - - string InstallerLogName { get; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs index be7df205f90..8fb242f7e06 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs @@ -14,6 +14,13 @@ namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration /// ----------------------------------------------------------------------------- public class InstallConfig { + public InstallConfig() + { + this.Portals = new List(); + this.Scripts = new List(); + this.Settings = new List(); + } + public IList Scripts { get; set; } public string Version { get; set; } @@ -33,12 +40,5 @@ public class InstallConfig public string FolderMappingsSettings { get; set; } public bool SupportLocalization { get; set; } - - public InstallConfig() - { - this.Portals = new List(); - this.Scripts = new List(); - this.Settings = new List(); - } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs index d77aa08805a..4d48566fa4d 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs @@ -13,6 +13,11 @@ namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration /// ----------------------------------------------------------------------------- public class PortalConfig { + public PortalConfig() + { + this.PortAliases = new List(); + } + public string PortalName { get; set; } public string AdminFirstName { get; set; } @@ -36,10 +41,5 @@ public class PortalConfig public string HomeDirectory { get; set; } public IList PortAliases { get; set; } - - public PortalConfig() - { - this.PortAliases = new List(); - } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs index 48da384aa31..cdf223bc279 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs @@ -31,6 +31,11 @@ namespace DotNetNuke.Services.Upgrade.Internals /// internal class InstallControllerImpl : IInstallController { + public string InstallerLogName + { + get { return "InstallerLog" + DateTime.Now.ToString("yyyyMMdd") + ".resources"; } + } + /// /// GetConnectionFromWebConfig - Returns Connection Configuration in web.config file. /// @@ -455,16 +460,16 @@ public bool IsValidSqlServerVersion(string connectionString) switch (versionNumber) { - case 8: - // sql 2000 + case 8: + // sql 2000 case 9: // sql 2005 isValidVersion = false; break; - case 10: - // sql 2008 - case 11: - // sql 2010 + case 10: + // sql 2008 + case 11: + // sql 2010 case 12: // sql 2012 isValidVersion = true; @@ -601,11 +606,6 @@ public CultureInfo GetCultureFromCookie() var culture = new CultureInfo(language); return culture; } - - public string InstallerLogName - { - get { return "InstallerLog" + DateTime.Now.ToString("yyyyMMdd") + ".resources"; } - } public CultureInfo GetCultureFromBrowser() { @@ -620,6 +620,18 @@ public CultureInfo GetCultureFromBrowser() return culture; } + private static XmlNode AppendNewXmlNode(ref XmlDocument document, ref XmlNode parentNode, string elementName, string elementValue) + { + XmlNode newNode = document.CreateNode(XmlNodeType.Element, elementName, null); + if (!string.IsNullOrEmpty(elementValue)) + { + newNode.InnerText = elementValue; + } + + parentNode.AppendChild(newNode); + return newNode; + } + private CultureInfo GetCultureFromQs() { if (HttpContext.Current == null || HttpContext.Current.Request["language"] == null) @@ -655,17 +667,5 @@ private void GetLanguagePack(string downloadUrl, string installFolder) myfile = "installlanguage.resources"; Util.DeployExtension(wr, myfile, installFolder); } - - private static XmlNode AppendNewXmlNode(ref XmlDocument document, ref XmlNode parentNode, string elementName, string elementValue) - { - XmlNode newNode = document.CreateNode(XmlNodeType.Element, elementName, null); - if (!string.IsNullOrEmpty(elementValue)) - { - newNode.InnerText = elementValue; - } - - parentNode.AppendChild(newNode); - return newNode; - } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs index b2ef22ce2b5..a23b5d31c12 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs @@ -22,6 +22,11 @@ protected BaseInstallationStep() this.Percentage = 0; this.Errors = new List(); } + + /// + /// This event gets fired when any activity gets recorded + /// + public event ActivityEventHandler Activity; /// /// Gets or sets any details of the task while it's executing. @@ -63,10 +68,5 @@ public string Details /// Main method to execute the step. /// public abstract void Execute(); - - /// - /// This event gets fired when any activity gets recorded - /// - public event ActivityEventHandler Activity; } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs index e4cfb7b71f0..ba644bbd198 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs @@ -17,6 +17,11 @@ namespace DotNetNuke.Services.Upgrade.Internals.Steps /// ----------------------------------------------------------------------------- public interface IInstallationStep { + /// + /// This event gets fired when any activity gets recorded + /// + event ActivityEventHandler Activity; + /// /// Gets any details of the task while it's executing. /// @@ -41,10 +46,5 @@ public interface IInstallationStep /// Main method to execute the step. /// void Execute(); - - /// - /// This event gets fired when any activity gets recorded - /// - event ActivityEventHandler Activity; } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs index 86298166d0c..d87486ba9f3 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs @@ -55,17 +55,17 @@ public override void Execute() else { // Construct UserInfo object - var superUser = new UserInfo - { - PortalID = -1, - FirstName = installConfig.SuperUser.FirstName, - LastName = installConfig.SuperUser.LastName, - Username = installConfig.SuperUser.UserName, - DisplayName = installConfig.SuperUser.FirstName + " " + installConfig.SuperUser.LastName, - Membership = { Password = installConfig.SuperUser.Password }, - Email = installConfig.SuperUser.Email, - IsSuperUser = true, - }; + var superUser = new UserInfo + { + PortalID = -1, + FirstName = installConfig.SuperUser.FirstName, + LastName = installConfig.SuperUser.LastName, + Username = installConfig.SuperUser.UserName, + DisplayName = installConfig.SuperUser.FirstName + " " + installConfig.SuperUser.LastName, + Membership = { Password = installConfig.SuperUser.Password }, + Email = installConfig.SuperUser.Email, + IsSuperUser = true, + }; superUser.Membership.Approved = true; superUser.Profile.FirstName = installConfig.SuperUser.FirstName; diff --git a/DNN Platform/Library/Services/Upgrade/Upgrade.cs b/DNN Platform/Library/Services/Upgrade/Upgrade.cs index 5d8a7dd8245..ded5cc3b4a4 100644 --- a/DNN Platform/Library/Services/Upgrade/Upgrade.cs +++ b/DNN Platform/Library/Services/Upgrade/Upgrade.cs @@ -82,11 +82,11 @@ namespace DotNetNuke.Services.Upgrade /// ----------------------------------------------------------------------------- public class Upgrade { + private const string FipsCompilanceAssembliesCheckedKey = "FipsCompilanceAssembliesChecked"; + private const string FipsCompilanceAssembliesFolder = "App_Data\\FipsCompilanceAssemblies"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Upgrade)); private static readonly object _threadLocker = new object(); private static DateTime _startTime; - private const string FipsCompilanceAssembliesCheckedKey = "FipsCompilanceAssembliesChecked"; - private const string FipsCompilanceAssembliesFolder = "App_Data\\FipsCompilanceAssemblies"; public static string DefaultProvider { @@ -113,6 +113,228 @@ private static Version ApplicationVersion } } + public static int RemoveModule(string desktopModuleName, string tabName, int parentId, bool removeTab) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModule:" + desktopModuleName); + TabInfo tab = TabController.Instance.GetTabByName(tabName, Null.NullInteger, parentId); + int moduleDefId = 0; + int count = 0; + + // Get the Modules on the Tab + if (tab != null) + { + foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(tab.TabID)) + { + var module = kvp.Value; + if (module.DesktopModule.FriendlyName == desktopModuleName) + { + // Delete the Module from the Modules list + ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); + moduleDefId = module.ModuleDefID; + } + else + { + count += 1; + } + } + + // If Tab has no modules optionally remove tab + if (count == 0 && removeTab) + { + TabController.Instance.DeleteTab(tab.TabID, tab.PortalID); + } + } + + return moduleDefId; + } + + public static void MakeModulePremium(string moduleName) + { + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, -1); + if (desktopModule != null) + { + desktopModule.IsAdmin = true; + desktopModule.IsPremium = true; + DesktopModuleController.SaveDesktopModule(desktopModule, false, true); + + // Remove Portal/Module to PortalDesktopModules + DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals. + /// + /// The Name to give this new Tab. + /// + /// The Icon for this new Tab. + /// + /// A flag indicating whether the tab is visible. + /// The Module Deinition Id for the module to be aded to this tab. + /// The Module's title. + /// The Module's icon. + /// Modules Inherit the Pages View Permisions. + /// ----------------------------------------------------------------------------- + public static void AddAdminPages(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) + { + ArrayList portals = PortalController.Instance.GetPortals(); + + // Add Page to Admin Menu of all configured Portals + for (var index = 0; index <= portals.Count - 1; index++) + { + var portal = (PortalInfo)portals[index]; + + // Create New Admin Page (or get existing one) + var newPage = AddAdminPage(portal, tabName, description, tabIconFile, tabIconFileLarge, isVisible); + + // Add Module To Page + AddModuleToPage(newPage, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// AddAdminPage adds an Admin Tab Page. + /// + /// The Portal. + /// The Name to give this new Tab. + /// + /// The Icon for this new Tab. + /// + /// A flag indicating whether the tab is visible. + /// + /// ----------------------------------------------------------------------------- + public static TabInfo AddAdminPage(PortalInfo portal, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminPage:" + tabName); + TabInfo adminPage = TabController.Instance.GetTab(portal.AdminTabId, portal.PortalID, false); + + if (adminPage != null) + { + var tabPermissionCollection = new TabPermissionCollection(); + AddPagePermission(tabPermissionCollection, "View", Convert.ToInt32(portal.AdministratorRoleId)); + AddPagePermission(tabPermissionCollection, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); + return AddPage(adminPage, tabName, description, tabIconFile, tabIconFileLarge, isVisible, tabPermissionCollection, true); + } + + return null; + } + + /// ----------------------------------------------------------------------------- + /// + /// ExecuteScript executes a SQl script file. + /// + /// + /// + /// The script to Execute. + /// Need to output feedback message. + /// + /// ----------------------------------------------------------------------------- + internal static string ExecuteScript(string scriptFile, bool writeFeedback) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ExecutingScript", Localization.GlobalResourceFile) + ":" + Path.GetFileName(scriptFile)); + } + + // read script file for installation + string script = FileSystemUtils.ReadFile(scriptFile); + + // execute SQL installation script + string exceptions = DataProvider.Instance().ExecuteScript(script); + + // add installer logging + if (string.IsNullOrEmpty(exceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); + } + else + { + DnnInstallLogger.InstallLogError(exceptions); + } + + // log the results + try + { + using (var streamWriter = File.CreateText(scriptFile.Replace("." + DefaultProvider, string.Empty) + ".log.resources")) + { + streamWriter.WriteLine(exceptions); + streamWriter.Close(); + } + } + catch (Exception exc) + { + // does not have permission to create the log file + Logger.Error(exc); + } + + if (writeFeedback) + { + string resourcesFile = Path.GetFileName(scriptFile); + if (!string.IsNullOrEmpty(resourcesFile)) + { + HtmlUtils.WriteScriptSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions), resourcesFile.Replace("." + DefaultProvider, ".log.resources")); + } + } + + return exceptions; + } + + /// ----------------------------------------------------------------------------- + /// + /// InstallMemberRoleProvider - Installs the MemberRole Provider Db objects. + /// + /// + /// + /// The Path to the Provider Directory. + /// Whether need to output feedback message. + /// + /// ----------------------------------------------------------------------------- + internal static string InstallMemberRoleProvider(string providerPath, bool writeFeedback) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); + + string exceptions = string.Empty; + + bool installMemberRole = true; + if (Config.GetSetting("InstallMemberRole") != null) + { + installMemberRole = bool.Parse(Config.GetSetting("InstallMemberRole")); + } + + if (installMemberRole) + { + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing MemberRole Provider:
"); + } + + // Install Common + exceptions += InstallMemberRoleProviderScript(providerPath, "InstallCommon", writeFeedback); + + // Install Membership + exceptions += InstallMemberRoleProviderScript(providerPath, "InstallMembership", writeFeedback); + + // Install Profile + // exceptions += InstallMemberRoleProviderScript(providerPath, "InstallProfile", writeFeedback); + // Install Roles + // exceptions += InstallMemberRoleProviderScript(providerPath, "InstallRoles", writeFeedback); + } + + if (string.IsNullOrEmpty(exceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); + } + else + { + DnnInstallLogger.InstallLogError(exceptions); + } + + return exceptions; + } + /// ----------------------------------------------------------------------------- /// /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals. @@ -735,80 +957,19 @@ private static void EnableModalPopUps() ModuleControlController.SaveModuleControl(control, false); } } - } - - break; - default: - break; - } - } - - foreach (ModuleControlInfo control in ModuleControlController.GetModuleControlsByModuleDefinitionID(Null.NullInteger).Values) - { - control.SupportsPopUps = true; - ModuleControlController.SaveModuleControl(control, false); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// ExecuteScript executes a SQl script file. - /// - /// - /// - /// The script to Execute. - /// Need to output feedback message. - /// - /// ----------------------------------------------------------------------------- - internal static string ExecuteScript(string scriptFile, bool writeFeedback) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ExecutingScript", Localization.GlobalResourceFile) + ":" + Path.GetFileName(scriptFile)); - } - - // read script file for installation - string script = FileSystemUtils.ReadFile(scriptFile); - - // execute SQL installation script - string exceptions = DataProvider.Instance().ExecuteScript(script); - - // add installer logging - if (string.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); - } - else - { - DnnInstallLogger.InstallLogError(exceptions); - } - - // log the results - try - { - using (var streamWriter = File.CreateText(scriptFile.Replace("." + DefaultProvider, string.Empty) + ".log.resources")) - { - streamWriter.WriteLine(exceptions); - streamWriter.Close(); + } + + break; + default: + break; } } - catch (Exception exc) - { - // does not have permission to create the log file - Logger.Error(exc); - } - if (writeFeedback) + foreach (ModuleControlInfo control in ModuleControlController.GetModuleControlsByModuleDefinitionID(Null.NullInteger).Values) { - string resourcesFile = Path.GetFileName(scriptFile); - if (!string.IsNullOrEmpty(resourcesFile)) - { - HtmlUtils.WriteScriptSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions), resourcesFile.Replace("." + DefaultProvider, ".log.resources")); - } + control.SupportsPopUps = true; + ModuleControlController.SaveModuleControl(control, false); } - - return exceptions; } /// ----------------------------------------------------------------------------- @@ -861,59 +1022,6 @@ private static bool HostTabExists(string tabName) return tabExists; } - /// ----------------------------------------------------------------------------- - /// - /// InstallMemberRoleProvider - Installs the MemberRole Provider Db objects. - /// - /// - /// - /// The Path to the Provider Directory. - /// Whether need to output feedback message. - /// - /// ----------------------------------------------------------------------------- - internal static string InstallMemberRoleProvider(string providerPath, bool writeFeedback) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); - - string exceptions = string.Empty; - - bool installMemberRole = true; - if (Config.GetSetting("InstallMemberRole") != null) - { - installMemberRole = bool.Parse(Config.GetSetting("InstallMemberRole")); - } - - if (installMemberRole) - { - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing MemberRole Provider:
"); - } - - // Install Common - exceptions += InstallMemberRoleProviderScript(providerPath, "InstallCommon", writeFeedback); - - // Install Membership - exceptions += InstallMemberRoleProviderScript(providerPath, "InstallMembership", writeFeedback); - - // Install Profile - // exceptions += InstallMemberRoleProviderScript(providerPath, "InstallProfile", writeFeedback); - // Install Roles - // exceptions += InstallMemberRoleProviderScript(providerPath, "InstallRoles", writeFeedback); - } - - if (string.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); - } - else - { - DnnInstallLogger.InstallLogError(exceptions); - } - - return exceptions; - } - /// ----------------------------------------------------------------------------- /// /// InstallMemberRoleProviderScript - Installs a specific MemberRole Provider script. @@ -1071,41 +1179,6 @@ private static void RemoveCoreModule(string desktopModuleName, string parentTabN } } - public static int RemoveModule(string desktopModuleName, string tabName, int parentId, bool removeTab) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModule:" + desktopModuleName); - TabInfo tab = TabController.Instance.GetTabByName(tabName, Null.NullInteger, parentId); - int moduleDefId = 0; - int count = 0; - - // Get the Modules on the Tab - if (tab != null) - { - foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(tab.TabID)) - { - var module = kvp.Value; - if (module.DesktopModule.FriendlyName == desktopModuleName) - { - // Delete the Module from the Modules list - ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); - moduleDefId = module.ModuleDefID; - } - else - { - count += 1; - } - } - - // If Tab has no modules optionally remove tab - if (count == 0 && removeTab) - { - TabController.Instance.DeleteTab(tab.TabID, tab.PortalID); - } - } - - return moduleDefId; - } - private static void RemoveModuleControl(int moduleDefId, string controlKey) { DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModuleControl:" + moduleDefId); @@ -3396,20 +3469,6 @@ private static void ReplaceMessagingModule() } } - public static void MakeModulePremium(string moduleName) - { - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, -1); - if (desktopModule != null) - { - desktopModule.IsAdmin = true; - desktopModule.IsPremium = true; - DesktopModuleController.SaveDesktopModule(desktopModule, false, true); - - // Remove Portal/Module to PortalDesktopModules - DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); - } - } - private static void MovePhotoProperty() { DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "MovePhotoProperty"); @@ -3564,65 +3623,6 @@ private static bool DoesLogTypeExists(string logTypeKey) return true; } - /// ----------------------------------------------------------------------------- - /// - /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals. - /// - /// The Name to give this new Tab. - /// - /// The Icon for this new Tab. - /// - /// A flag indicating whether the tab is visible. - /// The Module Deinition Id for the module to be aded to this tab. - /// The Module's title. - /// The Module's icon. - /// Modules Inherit the Pages View Permisions. - /// ----------------------------------------------------------------------------- - public static void AddAdminPages(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) - { - ArrayList portals = PortalController.Instance.GetPortals(); - - // Add Page to Admin Menu of all configured Portals - for (var index = 0; index <= portals.Count - 1; index++) - { - var portal = (PortalInfo)portals[index]; - - // Create New Admin Page (or get existing one) - var newPage = AddAdminPage(portal, tabName, description, tabIconFile, tabIconFileLarge, isVisible); - - // Add Module To Page - AddModuleToPage(newPage, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// AddAdminPage adds an Admin Tab Page. - /// - /// The Portal. - /// The Name to give this new Tab. - /// - /// The Icon for this new Tab. - /// - /// A flag indicating whether the tab is visible. - /// - /// ----------------------------------------------------------------------------- - public static TabInfo AddAdminPage(PortalInfo portal, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminPage:" + tabName); - TabInfo adminPage = TabController.Instance.GetTab(portal.AdminTabId, portal.PortalID, false); - - if (adminPage != null) - { - var tabPermissionCollection = new TabPermissionCollection(); - AddPagePermission(tabPermissionCollection, "View", Convert.ToInt32(portal.AdministratorRoleId)); - AddPagePermission(tabPermissionCollection, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); - return AddPage(adminPage, tabName, description, tabIconFile, tabIconFileLarge, isVisible, tabPermissionCollection, true); - } - - return null; - } - /// ----------------------------------------------------------------------------- /// /// AddHostPage adds a Host Tab Page. @@ -3906,125 +3906,50 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe } } - PortalController.Instance.AddPortalAlias(portalId, portalAlias.InnerText); - } - } - } - - // Force Administrator to Update Password on first log in - PortalInfo portal = PortalController.Instance.GetPortal(portalId); - UserInfo adminUser = UserController.GetUserById(portalId, portal.AdministratorId); - adminUser.Membership.UpdatePassword = true; - UserController.UpdateUser(portalId, adminUser); - } - - return portalId; - } - } - catch (Exception ex) - { - Logger.Error(ex); - - if (HttpContext.Current != null) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Error! " + ex.Message + ex.StackTrace + "
"); - DnnInstallLogger.InstallLogError(ex); - } - - // failure - portalId = -1; - } - - return portalId; - } - - /// ----------------------------------------------------------------------------- - /// - /// Obsolete, AddPortal manages the Installation of a new DotNetNuke Portal. - /// - /// - /// - /// - /// ----------------------------------------------------------------------------- - [Obsolete("Deprecated in DNN 9.3.0, will be removed in 11.0.0. Use the overloaded method with the 'superUser' parameter instead. Scheduled removal in v11.0.0.")] - public static int AddPortal(XmlNode node, bool status, int indent) - { - return AddPortal(node, status, indent, null); - } - - internal static UserInfo CreateUserInfo(string firstName, string lastName, string userName, string password, string email) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "CreateUserInfo:" + userName); - var adminUser = new UserInfo - { - FirstName = firstName, - LastName = lastName, - Username = userName, - DisplayName = firstName + " " + lastName, - Membership = { Password = password }, - Email = email, - IsSuperUser = false, - }; - adminUser.Membership.Approved = true; - adminUser.Profile.FirstName = firstName; - adminUser.Profile.LastName = lastName; - adminUser.Membership.UpdatePassword = true; - return adminUser; - } - - internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName, string currentCulture) - { - if (string.IsNullOrEmpty(currentCulture)) - { - currentCulture = Localization.SystemLocale; - } - - var templates = PortalController.Instance.GetAvailablePortalTemplates(); + PortalController.Instance.AddPortalAlias(portalId, portalAlias.InnerText); + } + } + } - var defaultTemplates = - templates.Where(x => Path.GetFileName(x.TemplateFilePath) == templateFileName).ToList(); + // Force Administrator to Update Password on first log in + PortalInfo portal = PortalController.Instance.GetPortal(portalId); + UserInfo adminUser = UserController.GetUserById(portalId, portal.AdministratorId); + adminUser.Membership.UpdatePassword = true; + UserController.UpdateUser(portalId, adminUser); + } - var match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant() == currentCulture); - if (match == null) - { - match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant().StartsWith(currentCulture.Substring(0, 2))); + return portalId; + } } - - if (match == null) + catch (Exception ex) { - match = defaultTemplates.FirstOrDefault(x => string.IsNullOrEmpty(x.CultureCode)); - } + Logger.Error(ex); - if (match == null) - { - throw new Exception("Unable to locate specified portal template: " + templateFileName); + if (HttpContext.Current != null) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Error! " + ex.Message + ex.StackTrace + "
"); + DnnInstallLogger.InstallLogError(ex); + } + + // failure + portalId = -1; } - return match; + return portalId; } - internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName) + /// ----------------------------------------------------------------------------- + /// + /// Obsolete, AddPortal manages the Installation of a new DotNetNuke Portal. + /// + /// + /// + /// + /// ----------------------------------------------------------------------------- + [Obsolete("Deprecated in DNN 9.3.0, will be removed in 11.0.0. Use the overloaded method with the 'superUser' parameter instead. Scheduled removal in v11.0.0.")] + public static int AddPortal(XmlNode node, bool status, int indent) { - // Load Template - var installTemplate = new XmlDocument { XmlResolver = null }; - Upgrade.GetInstallTemplate(installTemplate); - - // Parse the root node - XmlNode rootNode = installTemplate.SelectSingleNode("//dotnetnuke"); - string currentCulture = string.Empty; - if (rootNode != null) - { - currentCulture = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "installCulture"); - } - - if (string.IsNullOrEmpty(currentCulture)) - { - currentCulture = Localization.SystemLocale; - } - - currentCulture = currentCulture.ToLowerInvariant(); - - return FindBestTemplate(templateFileName, currentCulture); + return AddPortal(node, status, indent, null); } public static string BuildUserTable(IDataReader dr, string header, string message) @@ -4128,6 +4053,81 @@ public static string CheckUpgrade() return warnings; } + internal static UserInfo CreateUserInfo(string firstName, string lastName, string userName, string password, string email) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "CreateUserInfo:" + userName); + var adminUser = new UserInfo + { + FirstName = firstName, + LastName = lastName, + Username = userName, + DisplayName = firstName + " " + lastName, + Membership = { Password = password }, + Email = email, + IsSuperUser = false, + }; + adminUser.Membership.Approved = true; + adminUser.Profile.FirstName = firstName; + adminUser.Profile.LastName = lastName; + adminUser.Membership.UpdatePassword = true; + return adminUser; + } + + internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName, string currentCulture) + { + if (string.IsNullOrEmpty(currentCulture)) + { + currentCulture = Localization.SystemLocale; + } + + var templates = PortalController.Instance.GetAvailablePortalTemplates(); + + var defaultTemplates = + templates.Where(x => Path.GetFileName(x.TemplateFilePath) == templateFileName).ToList(); + + var match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant() == currentCulture); + if (match == null) + { + match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant().StartsWith(currentCulture.Substring(0, 2))); + } + + if (match == null) + { + match = defaultTemplates.FirstOrDefault(x => string.IsNullOrEmpty(x.CultureCode)); + } + + if (match == null) + { + throw new Exception("Unable to locate specified portal template: " + templateFileName); + } + + return match; + } + + internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName) + { + // Load Template + var installTemplate = new XmlDocument { XmlResolver = null }; + Upgrade.GetInstallTemplate(installTemplate); + + // Parse the root node + XmlNode rootNode = installTemplate.SelectSingleNode("//dotnetnuke"); + string currentCulture = string.Empty; + if (rootNode != null) + { + currentCulture = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "installCulture"); + } + + if (string.IsNullOrEmpty(currentCulture)) + { + currentCulture = Localization.SystemLocale; + } + + currentCulture = currentCulture.ToLowerInvariant(); + + return FindBestTemplate(templateFileName, currentCulture); + } + /// ----------------------------------------------------------------------------- /// /// DeleteInstallerFiles - clean up install config and installwizard files @@ -4228,17 +4228,6 @@ public static string DeleteFiles(string providerPath, Version version, bool writ return exceptions; } - private static string GetStringVersionWithRevision(Version version) - { - var stringVersion = GetStringVersion(version); - if (version.Revision > 0) - { - stringVersion += "." + version.Revision.ToString("D2"); - } - - return stringVersion; - } - /// ----------------------------------------------------------------------------- /// /// ExecuteScripts manages the Execution of Scripts from the Install/Scripts folder. @@ -4294,6 +4283,17 @@ public static void ExecuteScript(string file) } } + private static string GetStringVersionWithRevision(Version version) + { + var stringVersion = GetStringVersion(version); + if (version.Revision > 0) + { + stringVersion += "." + version.Revision.ToString("D2"); + } + + return stringVersion; + } + /// ----------------------------------------------------------------------------- /// /// GetInstallTemplate retrieves the Installation Template as specifeid in web.config. @@ -4569,24 +4569,6 @@ public static ArrayList GetUpgradeScripts(string providerPath, Version databaseV return scriptFiles; } - private static string[] AddAvailableIncrementalFiles(string providerPath, Version version) - { - if (version.Major < 8) - { - return null; - } - - var files = Directory.GetFiles(providerPath, GetStringVersion(version) + ".*." + DefaultProvider); - Array.Sort(files); // The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required. - - return files; - } - - private static string GetFileName(string file) - { - return Path.GetFileName(file); - } - /// ----------------------------------------------------------------------------- /// /// InitialiseHostSettings gets the Host Settings from the Install Template. @@ -4704,6 +4686,24 @@ public static string InstallDatabase(Version version, string providerPath, XmlDo return message; } + private static string[] AddAvailableIncrementalFiles(string providerPath, Version version) + { + if (version.Major < 8) + { + return null; + } + + var files = Directory.GetFiles(providerPath, GetStringVersion(version) + ".*." + DefaultProvider); + Array.Sort(files); // The order of the returned file names is not guaranteed; use the Sort method if a specific sort order is required. + + return files; + } + + private static string GetFileName(string file) + { + return Path.GetFileName(file); + } + /// ----------------------------------------------------------------------------- /// /// InstallDNN manages the Installation of a new DotNetNuke Application. @@ -4962,33 +4962,90 @@ public static IDictionary GetInstallPackages() var dependentCount = dependentPackages.Count; while (dependentCount != prevDependentCount) { - prevDependentCount = dependentCount; - var addedPackages = new List(); - foreach (var package in dependentPackages) - { - if (package.Value.Dependencies.All( - d => sortedPackages.Any(p => p.Value.Name.Equals(d.PackageName, StringComparison.OrdinalIgnoreCase) && p.Value.Version >= d.Version))) + prevDependentCount = dependentCount; + var addedPackages = new List(); + foreach (var package in dependentPackages) + { + if (package.Value.Dependencies.All( + d => sortedPackages.Any(p => p.Value.Name.Equals(d.PackageName, StringComparison.OrdinalIgnoreCase) && p.Value.Version >= d.Version))) + { + sortedPackages.Add(package.Key, package.Value); + addedPackages.Add(package.Key); + } + } + + foreach (var packageKey in addedPackages) + { + dependentPackages.Remove(packageKey); + } + + dependentCount = dependentPackages.Count; + } + + // Add any packages whose dependency cannot be resolved + foreach (var package in dependentPackages) + { + sortedPackages.Add(package.Key, package.Value); + } + + return sortedPackages; + } + + public static void InstallPackages(string packageType, bool writeFeedback) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallPackages:" + packageType); + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Optional " + packageType + "s:
"); + } + + string installPackagePath = Globals.ApplicationMapPath + "\\Install\\" + packageType; + if (Directory.Exists(installPackagePath)) + { + foreach (string file in Directory.GetFiles(installPackagePath)) + { + if (Path.GetExtension(file.ToLowerInvariant()) == ".zip" /*|| installLanguage */) + { + InstallPackage(file, packageType, writeFeedback); + } + } + } + } + + public static bool IsNETFrameworkCurrent(string version) + { + bool isCurrent = Null.NullBoolean; + switch (version) + { + case "3.5": + // Try and instantiate a 3.5 Class + if (Reflection.CreateType("System.Data.Linq.DataContext", true) != null) { - sortedPackages.Add(package.Key, package.Value); - addedPackages.Add(package.Key); + isCurrent = true; } - } - foreach (var packageKey in addedPackages) - { - dependentPackages.Remove(packageKey); - } + break; + case "4.0": + // Look for requestValidationMode attribute + XmlDocument configFile = Config.Load(); + XPathNavigator configNavigator = configFile.CreateNavigator().SelectSingleNode("//configuration/system.web/httpRuntime|//configuration/location/system.web/httpRuntime"); + if (configNavigator != null && !string.IsNullOrEmpty(configNavigator.GetAttribute("requestValidationMode", string.Empty))) + { + isCurrent = true; + } - dependentCount = dependentPackages.Count; - } + break; + case "4.5": + // Try and instantiate a 4.5 Class + if (Reflection.CreateType("System.Reflection.ReflectionContext", true) != null) + { + isCurrent = true; + } - // Add any packages whose dependency cannot be resolved - foreach (var package in dependentPackages) - { - sortedPackages.Add(package.Key, package.Value); + break; } - return sortedPackages; + return isCurrent; } private static void ParsePackagesFromApplicationPath(IEnumerable packageTypes, Dictionary packages, List invalidPackages) @@ -5076,63 +5133,6 @@ private static void ParsePackagesFromApplicationPath(IEnumerable package } } - public static void InstallPackages(string packageType, bool writeFeedback) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallPackages:" + packageType); - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Optional " + packageType + "s:
"); - } - - string installPackagePath = Globals.ApplicationMapPath + "\\Install\\" + packageType; - if (Directory.Exists(installPackagePath)) - { - foreach (string file in Directory.GetFiles(installPackagePath)) - { - if (Path.GetExtension(file.ToLowerInvariant()) == ".zip" /*|| installLanguage */) - { - InstallPackage(file, packageType, writeFeedback); - } - } - } - } - - public static bool IsNETFrameworkCurrent(string version) - { - bool isCurrent = Null.NullBoolean; - switch (version) - { - case "3.5": - // Try and instantiate a 3.5 Class - if (Reflection.CreateType("System.Data.Linq.DataContext", true) != null) - { - isCurrent = true; - } - - break; - case "4.0": - // Look for requestValidationMode attribute - XmlDocument configFile = Config.Load(); - XPathNavigator configNavigator = configFile.CreateNavigator().SelectSingleNode("//configuration/system.web/httpRuntime|//configuration/location/system.web/httpRuntime"); - if (configNavigator != null && !string.IsNullOrEmpty(configNavigator.GetAttribute("requestValidationMode", string.Empty))) - { - isCurrent = true; - } - - break; - case "4.5": - // Try and instantiate a 4.5 Class - if (Reflection.CreateType("System.Reflection.ReflectionContext", true) != null) - { - isCurrent = true; - } - - break; - } - - return isCurrent; - } - public static void RemoveAdminPages(string tabPath) { DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveAdminPages:" + tabPath); @@ -5497,6 +5497,73 @@ public static string UpgradeApplication(string providerPath, Version version, bo return exceptions; } + public static string UpdateConfig(string providerPath, Version version, bool writeFeedback) + { + var stringVersion = GetStringVersionWithRevision(version); + + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, $"Updating Config Files: {stringVersion}"); + } + + string strExceptions = UpdateConfig(providerPath, Globals.InstallMapPath + "Config\\" + stringVersion + ".config", version, "Core Upgrade"); + if (string.IsNullOrEmpty(strExceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); + } + else + { + DnnInstallLogger.InstallLogError(strExceptions); + } + + if (writeFeedback) + { + HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(strExceptions)); + } + + return strExceptions; + } + + 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; + if (File.Exists(configFile)) + { + // Create XmlMerge instance from config file source + StreamReader stream = File.OpenText(configFile); + try + { + var merge = new XmlMerge(stream, version.ToString(3), reason); + + // Process merge + merge.UpdateConfigs(); + } + catch (Exception ex) + { + exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + Exceptions.Exceptions.LogException(ex); + } + finally + { + // Close stream + stream.Close(); + } + } + + if (string.IsNullOrEmpty(exceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); + } + else + { + DnnInstallLogger.InstallLogError(exceptions); + } + + return exceptions; + } + private static void UpgradeToVersion8006() { RemoveAdminPages("//Admin//Languages"); @@ -5775,73 +5842,6 @@ private static void UpgradeToVersion960() HostController.Instance.Update("DefaultEndUserExtensionWhitelist", exts.ToStorageString()); } - public static string UpdateConfig(string providerPath, Version version, bool writeFeedback) - { - var stringVersion = GetStringVersionWithRevision(version); - - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, $"Updating Config Files: {stringVersion}"); - } - - string strExceptions = UpdateConfig(providerPath, Globals.InstallMapPath + "Config\\" + stringVersion + ".config", version, "Core Upgrade"); - if (string.IsNullOrEmpty(strExceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); - } - else - { - DnnInstallLogger.InstallLogError(strExceptions); - } - - if (writeFeedback) - { - HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(strExceptions)); - } - - return strExceptions; - } - - 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; - if (File.Exists(configFile)) - { - // Create XmlMerge instance from config file source - StreamReader stream = File.OpenText(configFile); - try - { - var merge = new XmlMerge(stream, version.ToString(3), reason); - - // Process merge - merge.UpdateConfigs(); - } - catch (Exception ex) - { - exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); - Exceptions.Exceptions.LogException(ex); - } - finally - { - // Close stream - stream.Close(); - } - } - - if (string.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); - } - else - { - DnnInstallLogger.InstallLogError(exceptions); - } - - return exceptions; - } - public static string UpdateConfig(string providerPath, string configFile, Version version, string reason) { DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); @@ -5950,11 +5950,6 @@ public static void UpgradeDNN(string providerPath, Version dataBaseVersion) DataCache.ClearHostCache(true); } - internal static string GetFileNameWithoutExtension(string scriptFile) - { - return Path.GetFileNameWithoutExtension(scriptFile); - } - public static string UpgradeIndicator(Version version, bool isLocal, bool isSecureConnection) { return UpgradeIndicator(version, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, string.Empty, isLocal, isSecureConnection); @@ -6011,6 +6006,11 @@ public static string UpgradeIndicator(Version version, string packageType, strin return url; } + internal static string GetFileNameWithoutExtension(string scriptFile) + { + return Path.GetFileNameWithoutExtension(scriptFile); + } + public static string UpgradeRedirect() { return UpgradeRedirect(ApplicationVersion, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, string.Empty); @@ -6141,12 +6141,6 @@ public static string UpgradeVersion(string scriptFile, bool writeFeedback, out b return exceptions; } - protected static bool IsLanguageEnabled(int portalid, string code) - { - Locale enabledLanguage; - return LocaleController.Instance.GetLocales(portalid).TryGetValue(code, out enabledLanguage); - } - public static bool UpdateNewtonsoftVersion() { try @@ -6205,6 +6199,12 @@ public static string ActivateLicense() return activationResult; } + protected static bool IsLanguageEnabled(int portalid, string code) + { + Locale enabledLanguage; + return LocaleController.Instance.GetLocales(portalid).TryGetValue(code, out enabledLanguage); + } + public static bool RemoveInvalidAntiForgeryCookie() { // DNN-9394: when upgrade from old version which use MVC version below than 5, it may saved antiforgery cookie diff --git a/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs b/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs index c9b1e6169d2..97ec3cb659d 100644 --- a/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs +++ b/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs @@ -15,6 +15,14 @@ namespace DotNetNuke.Services.UserProfile public class UserProfilePageHandler : IHttpHandler { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UserProfilePageHandler)); + + public bool IsReusable + { + get + { + return true; + } + } /// ----------------------------------------------------------------------------- /// @@ -92,14 +100,6 @@ public void ProcessRequest(HttpContext context) // Redirect to Userprofile Page context.Response.Redirect(Globals.UserProfileURL(UserId), true); } - - public bool IsReusable - { - get - { - return true; - } - } private static int GetUserId(string username, int PortalId) { diff --git a/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs b/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs index c7fe8667396..206c6a023b6 100644 --- a/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs +++ b/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs @@ -20,6 +20,14 @@ namespace DotNetNuke.Services.UserProfile public class UserProfilePicHandler : IHttpHandler { private static object _locker = new object(); + + public bool IsReusable + { + get + { + return false; + } + } public void ProcessRequest(HttpContext context) { @@ -234,13 +242,5 @@ private void SetupCulture() TestableLocalization.Instance.SetThreadCultures(pageLocale, settings); } } - - public bool IsReusable - { - get - { - return false; - } - } } } diff --git a/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs b/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs index aa491b5d6f2..bcd881e1381 100644 --- a/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs +++ b/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs @@ -57,6 +57,11 @@ public string GetUserRequestIPAddress(HttpRequestBase request, IPAddressFamily i return userIPAddress; } + + protected override Func GetFactory() + { + return () => new UserRequestIPAddressController(); + } private bool ValidateIP(string ipString, IPAddressFamily ipFamily) { @@ -79,10 +84,5 @@ private bool ValidateIP(string ipString, IPAddressFamily ipFamily) return false; } - - protected override Func GetFactory() - { - return () => new UserRequestIPAddressController(); - } } } diff --git a/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs b/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs index 71e00f4302b..4ba5d8afaa4 100644 --- a/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs +++ b/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs @@ -25,10 +25,10 @@ namespace DotNetNuke.Services.Zip /// internal class SharpZipLibRedirect { - internal static bool AlreadyRun { get; private set; } - private const string OldName = "SharpZipLib"; private const string NewName = "ICSharpCode.SharpZipLib"; + + internal static bool AlreadyRun { get; private set; } /// /// Registration call - should only be called once diff --git a/DNN Platform/Library/UI/Containers/ActionBase.cs b/DNN Platform/Library/UI/Containers/ActionBase.cs index 0b5b11aa816..d07c7a51fe5 100644 --- a/DNN Platform/Library/UI/Containers/ActionBase.cs +++ b/DNN Platform/Library/UI/Containers/ActionBase.cs @@ -27,9 +27,27 @@ namespace DotNetNuke.UI.Containers /// public abstract class ActionBase : UserControl, IActionControl { + protected bool m_supportsIcons = true; private ActionManager _ActionManager; private ModuleAction _ActionRoot; - protected bool m_supportsIcons = true; + + public event ActionEventHandler Action; + + public bool EditMode + { + get + { + return this.ModuleContext.PortalSettings.UserMode != PortalSettings.Mode.View; + } + } + + public bool SupportsIcons + { + get + { + return this.m_supportsIcons; + } + } /// ----------------------------------------------------------------------------- /// @@ -88,24 +106,6 @@ protected PortalSettings PortalSettings } } - public bool EditMode - { - get - { - return this.ModuleContext.PortalSettings.UserMode != PortalSettings.Mode.View; - } - } - - public bool SupportsIcons - { - get - { - return this.m_supportsIcons; - } - } - - public event ActionEventHandler Action; - /// ----------------------------------------------------------------------------- /// /// Gets the ActionManager instance for this Action control. diff --git a/DNN Platform/Library/UI/Containers/ActionButton.cs b/DNN Platform/Library/UI/Containers/ActionButton.cs index dde5ae1df22..d6da3b1f1be 100644 --- a/DNN Platform/Library/UI/Containers/ActionButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionButton.cs @@ -168,16 +168,6 @@ public string ButtonSeparator } } - /// ----------------------------------------------------------------------------- - /// - /// 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()); - } - /// ----------------------------------------------------------------------------- /// /// CreateChildControls builds the control tree. @@ -192,5 +182,15 @@ protected override void CreateChildControls() this.Controls.Add(this._ButtonList); } + + /// ----------------------------------------------------------------------------- + /// + /// 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()); + } } } diff --git a/DNN Platform/Library/UI/Containers/ActionButtonList.cs b/DNN Platform/Library/UI/Containers/ActionButtonList.cs index 26c314cc6b7..3fec63ab692 100644 --- a/DNN Platform/Library/UI/Containers/ActionButtonList.cs +++ b/DNN Platform/Library/UI/Containers/ActionButtonList.cs @@ -25,23 +25,7 @@ public class ActionButtonList : CompositeControl, IActionControl private string _commandName = string.Empty; private bool _displayLink = true; - /// ----------------------------------------------------------------------------- - /// - /// Gets the ModuleActionCollection to bind to the list. - /// - /// A ModuleActionCollection. - protected ModuleActionCollection ModuleActions - { - get - { - if (this._ModuleActions == null) - { - this._ModuleActions = this.ModuleControl.ModuleContext.Actions.GetActionsByCommandName(this.CommandName); - } - - return this._ModuleActions; - } - } + public event ActionEventHandler Action; /// ----------------------------------------------------------------------------- /// @@ -81,6 +65,24 @@ public string CommandName } } + /// ----------------------------------------------------------------------------- + /// + /// Gets the ModuleActionCollection to bind to the list. + /// + /// A ModuleActionCollection. + protected ModuleActionCollection ModuleActions + { + get + { + if (this._ModuleActions == null) + { + this._ModuleActions = this.ModuleControl.ModuleContext.Actions.GetActionsByCommandName(this.CommandName); + } + + return this._ModuleActions; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets or sets whether the icon is displayed. @@ -116,8 +118,6 @@ public bool DisplayLink /// A String. public string ImageURL { get; set; } - public event ActionEventHandler Action; - /// ----------------------------------------------------------------------------- /// /// Gets the ActionManager instance for this Action control. diff --git a/DNN Platform/Library/UI/Containers/ActionCommandButton.cs b/DNN Platform/Library/UI/Containers/ActionCommandButton.cs index 82c86150c0d..a5395382530 100644 --- a/DNN Platform/Library/UI/Containers/ActionCommandButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionCommandButton.cs @@ -27,6 +27,8 @@ public class ActionCommandButton : CommandButton, IActionControl private ActionManager _ActionManager; private ModuleAction _ModuleAction; + public event ActionEventHandler Action; + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the ModuleAction for this Action control. @@ -50,8 +52,6 @@ public ModuleAction ModuleAction this._ModuleAction = value; } } - - public event ActionEventHandler Action; /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/UI/Containers/ActionManager.cs b/DNN Platform/Library/UI/Containers/ActionManager.cs index 5c6db4fa406..c1272643670 100644 --- a/DNN Platform/Library/UI/Containers/ActionManager.cs +++ b/DNN Platform/Library/UI/Containers/ActionManager.cs @@ -71,6 +71,52 @@ protected ModuleInstanceContext ModuleContext } } + /// ----------------------------------------------------------------------------- + /// + /// DisplayControl determines whether the associated Action control should be + /// displayed. + /// + /// + /// ----------------------------------------------------------------------------- + public bool DisplayControl(DNNNodeCollection objNodes) + { + if (objNodes != null && objNodes.Count > 0 && this.PortalSettings.UserMode != PortalSettings.Mode.View) + { + DNNNode objRootNode = objNodes[0]; + if (objRootNode.HasNodes && objRootNode.DNNNodes.Count == 0) + { + // if has pending node then display control + return true; + } + else if (objRootNode.DNNNodes.Count > 0) + { + // verify that at least one child is not a break + foreach (DNNNode childNode in objRootNode.DNNNodes) + { + if (!childNode.IsBreak) + { + // Found a child so make Visible + return true; + } + } + } + } + + return false; + } + + /// ----------------------------------------------------------------------------- + /// + /// GetAction gets the action associated with the commandName. + /// + /// The command name. + /// + /// ----------------------------------------------------------------------------- + public ModuleAction GetAction(string commandName) + { + return this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByCommandName(commandName); + } + private void ClearCache(ModuleAction Command) { // synchronize cache @@ -185,52 +231,6 @@ private void MoveUpDown(ModuleAction Command) // Redirect to the same page to pick up changes this.Response.Redirect(this.Request.RawUrl, true); } - - /// ----------------------------------------------------------------------------- - /// - /// DisplayControl determines whether the associated Action control should be - /// displayed. - /// - /// - /// ----------------------------------------------------------------------------- - public bool DisplayControl(DNNNodeCollection objNodes) - { - if (objNodes != null && objNodes.Count > 0 && this.PortalSettings.UserMode != PortalSettings.Mode.View) - { - DNNNode objRootNode = objNodes[0]; - if (objRootNode.HasNodes && objRootNode.DNNNodes.Count == 0) - { - // if has pending node then display control - return true; - } - else if (objRootNode.DNNNodes.Count > 0) - { - // verify that at least one child is not a break - foreach (DNNNode childNode in objRootNode.DNNNodes) - { - if (!childNode.IsBreak) - { - // Found a child so make Visible - return true; - } - } - } - } - - return false; - } - - /// ----------------------------------------------------------------------------- - /// - /// GetAction gets the action associated with the commandName. - /// - /// The command name. - /// - /// ----------------------------------------------------------------------------- - public ModuleAction GetAction(string commandName) - { - return this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByCommandName(commandName); - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/UI/Containers/ActionsMenu.cs b/DNN Platform/Library/UI/Containers/ActionsMenu.cs index b4f9d90f36f..cbfa0303de7 100644 --- a/DNN Platform/Library/UI/Containers/ActionsMenu.cs +++ b/DNN Platform/Library/UI/Containers/ActionsMenu.cs @@ -35,70 +35,72 @@ public class ActionsMenu : Control, IActionControl private NavigationProvider _ProviderControl; private string _ProviderName = "DNNMenuNavigationProvider"; + public event ActionEventHandler Action; + /// ----------------------------------------------------------------------------- /// - /// Gets the ActionRoot. + /// Gets or sets and Sets the Expansion Depth for the Control. /// - /// A ModuleActionCollection. + /// An Integer. /// ----------------------------------------------------------------------------- - protected ModuleAction ActionRoot + public int ExpandDepth { get { - if (this._ActionRoot == null) + if (this.PopulateNodesFromClient == false || this.ProviderControl.SupportsPopulateOnDemand == false) { - this._ActionRoot = new ModuleAction(this.ModuleControl.ModuleContext.GetNextActionID(), " ", string.Empty, string.Empty, "action.gif"); + return -1; } - return this._ActionRoot; + return this._ExpandDepth; + } + + set + { + this._ExpandDepth = value; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Provider Control. + /// Gets or sets and Sets the Path to the Script Library for the provider. /// - /// A NavigationProvider. + /// A String. /// ----------------------------------------------------------------------------- - protected NavigationProvider ProviderControl - { - get - { - return this._ProviderControl; - } - } + public string PathSystemScript { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets or sets and Sets the Expansion Depth for the Control. + /// Gets the ActionRoot. /// - /// An Integer. + /// A ModuleActionCollection. /// ----------------------------------------------------------------------------- - public int ExpandDepth + protected ModuleAction ActionRoot { get { - if (this.PopulateNodesFromClient == false || this.ProviderControl.SupportsPopulateOnDemand == false) + if (this._ActionRoot == null) { - return -1; + this._ActionRoot = new ModuleAction(this.ModuleControl.ModuleContext.GetNextActionID(), " ", string.Empty, string.Empty, "action.gif"); } - return this._ExpandDepth; - } - - set - { - this._ExpandDepth = value; + return this._ActionRoot; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets and Sets the Path to the Script Library for the provider. + /// Gets the Provider Control. /// - /// A String. + /// A NavigationProvider. /// ----------------------------------------------------------------------------- - public string PathSystemScript { get; set; } + protected NavigationProvider ProviderControl + { + get + { + return this._ProviderControl; + } + } /// ----------------------------------------------------------------------------- /// @@ -126,8 +128,6 @@ public string ProviderName this._ProviderName = value; } } - - public event ActionEventHandler Action; /// ----------------------------------------------------------------------------- /// @@ -156,6 +156,29 @@ public ActionManager ActionManager /// ----------------------------------------------------------------------------- public IModuleControl ModuleControl { get; set; } + /// ----------------------------------------------------------------------------- + /// + /// BindMenu binds the Navigation Provider to the Node Collection. + /// + /// ----------------------------------------------------------------------------- + protected void BindMenu() + { + this.BindMenu(Navigation.GetActionNodes(this.ActionRoot, this, this.ExpandDepth)); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnAction raises the Action Event. + /// + /// ----------------------------------------------------------------------------- + protected virtual void OnAction(ActionEventArgs e) + { + if (this.Action != null) + { + this.Action(this, e); + } + } + /// ----------------------------------------------------------------------------- /// /// BindMenu binds the Navigation Provider to the Node Collection. @@ -235,29 +258,6 @@ private void SetMenuDefaults() Exceptions.ProcessModuleLoadException(this, exc); } } - - /// ----------------------------------------------------------------------------- - /// - /// BindMenu binds the Navigation Provider to the Node Collection. - /// - /// ----------------------------------------------------------------------------- - protected void BindMenu() - { - this.BindMenu(Navigation.GetActionNodes(this.ActionRoot, this, this.ExpandDepth)); - } - - /// ----------------------------------------------------------------------------- - /// - /// OnAction raises the Action Event. - /// - /// ----------------------------------------------------------------------------- - protected virtual void OnAction(ActionEventArgs e) - { - if (this.Action != null) - { - this.Action(this, e); - } - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/UI/Containers/Container.cs b/DNN Platform/Library/UI/Containers/Container.cs index 3e6df9ef356..7ecdd5bf0dc 100644 --- a/DNN Platform/Library/UI/Containers/Container.cs +++ b/DNN Platform/Library/UI/Containers/Container.cs @@ -45,60 +45,60 @@ public class Container : UserControl private ModuleInfo _moduleConfiguration; private ModuleHost _moduleHost; + /// ----------------------------------------------------------------------------- /// - /// Gets the Content Pane Control (Id="ContentPane"). + /// Gets the ModuleControl object that this container is displaying. /// - /// An HtmlContainerControl. - protected HtmlContainerControl ContentPane + /// A ModuleHost object. + public IModuleControl ModuleControl { get { - return this._contentPane ?? (this._contentPane = this.FindControl(Globals.glbDefaultPane) as HtmlContainerControl); + IModuleControl moduleControl = null; + if (this.ModuleHost != null) + { + moduleControl = this.ModuleHost.ModuleControl; + } + + return moduleControl; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Portal Settings for the current Portal. + /// Gets and sets the ModuleInfo object that this container is displaying. /// - /// A PortalSettings object. - protected PortalSettings PortalSettings + /// A ModuleInfo object. + public ModuleInfo ModuleConfiguration { get { - return PortalController.Instance.GetCurrentPortalSettings(); + return this._moduleConfiguration; } } - /// ----------------------------------------------------------------------------- /// - /// Gets the ModuleControl object that this container is displaying. + /// Gets the Content Pane Control (Id="ContentPane"). /// - /// A ModuleHost object. - public IModuleControl ModuleControl + /// An HtmlContainerControl. + protected HtmlContainerControl ContentPane { get { - IModuleControl moduleControl = null; - if (this.ModuleHost != null) - { - moduleControl = this.ModuleHost.ModuleControl; - } - - return moduleControl; + return this._contentPane ?? (this._contentPane = this.FindControl(Globals.glbDefaultPane) as HtmlContainerControl); } } /// ----------------------------------------------------------------------------- /// - /// Gets and sets the ModuleInfo object that this container is displaying. + /// Gets the Portal Settings for the current Portal. /// - /// A ModuleInfo object. - public ModuleInfo ModuleConfiguration + /// A PortalSettings object. + protected PortalSettings PortalSettings { get { - return this._moduleConfiguration; + return PortalController.Instance.GetCurrentPortalSettings(); } } @@ -151,6 +151,33 @@ public string ContainerPath internal bool InjectActionMenu { get; set; } + public void SetModuleConfiguration(ModuleInfo configuration) + { + this._moduleConfiguration = configuration; + this.ProcessModule(); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnInit runs when the Container is initialised. + /// + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.InvokeContainerEvents(ContainerEventType.OnContainerInit); + } + + /// + /// OnLoad runs when the Container is loaded. + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.InvokeContainerEvents(ContainerEventType.OnContainerLoad); + } + private void AddAdministratorOnlyHighlighting(string message) { this.ContentPane.Controls.Add(new LiteralControl(string.Format("
{0}
", message))); @@ -424,27 +451,6 @@ private void SetBorder() } } - /// ----------------------------------------------------------------------------- - /// - /// OnInit runs when the Container is initialised. - /// - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.InvokeContainerEvents(ContainerEventType.OnContainerInit); - } - - /// - /// OnLoad runs when the Container is loaded. - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.InvokeContainerEvents(ContainerEventType.OnContainerLoad); - } - /// ----------------------------------------------------------------------------- /// /// OnLoad runs just before the Container is rendered. @@ -480,12 +486,6 @@ private void InvokeContainerEvents(ContainerEventType containerEventType) } } - public void SetModuleConfiguration(ModuleInfo configuration) - { - this._moduleConfiguration = configuration; - this.ProcessModule(); - } - /// ----------------------------------------------------------------------------- /// /// ModuleAction_Click runs when a ModuleAction is clicked. diff --git a/DNN Platform/Library/UI/Containers/IActionControl.cs b/DNN Platform/Library/UI/Containers/IActionControl.cs index ddbdc5eb2f3..e5428c256e7 100644 --- a/DNN Platform/Library/UI/Containers/IActionControl.cs +++ b/DNN Platform/Library/UI/Containers/IActionControl.cs @@ -17,10 +17,10 @@ namespace DotNetNuke.UI.Containers /// ----------------------------------------------------------------------------- public interface IActionControl { + event ActionEventHandler Action; + ActionManager ActionManager { get; } IModuleControl ModuleControl { get; set; } - - event ActionEventHandler Action; } } diff --git a/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs b/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs index a040a46d836..bad4b26280f 100644 --- a/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs +++ b/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs @@ -34,45 +34,10 @@ public class ControlPanelBase : UserControl { private string _localResourceFile; - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets whether the ControlPanel is Visible. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - protected bool IsVisible - { - get - { - return this.PortalSettings.ControlPanelVisible; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the current Portal Settings. - /// - /// ----------------------------------------------------------------------------- - protected PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the User mode of the Control Panel. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - protected PortalSettings.Mode UserMode + protected enum ViewPermissionType { - get - { - return this.PortalSettings.UserMode; - } + View = 0, + Edit = 1, } /// ----------------------------------------------------------------------------- @@ -109,20 +74,51 @@ public virtual bool IncludeInControlHierarchy get { return true; } } - public virtual bool IsDockable + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether the ControlPanel is Visible. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + protected bool IsVisible { - get { return false; } - set { } + get + { + return this.PortalSettings.ControlPanelVisible; + } } - protected bool IsModuleAdmin() + /// ----------------------------------------------------------------------------- + /// + /// Gets the current Portal Settings. + /// + /// ----------------------------------------------------------------------------- + protected PortalSettings PortalSettings { - return IsModuleAdminInternal(); + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } } - protected bool IsPageAdmin() + /// ----------------------------------------------------------------------------- + /// + /// Gets the User mode of the Control Panel. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + protected PortalSettings.Mode UserMode { - return IsPageAdminInternal(); + get + { + return this.PortalSettings.UserMode; + } + } + + public virtual bool IsDockable + { + get { return false; } + set { } } internal static bool IsModuleAdminInternal() @@ -156,33 +152,14 @@ internal static bool IsPageAdminInternal() return _IsPageAdmin; } - /// ----------------------------------------------------------------------------- - /// - /// Adds a Module Permission. - /// - /// Module Info. - /// The permission to add. - /// The Id of the role to add the permission for. - /// Operator. - /// Whether allow to access the module. - /// ----------------------------------------------------------------------------- - private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess) + protected bool IsModuleAdmin() { - var objModulePermission = new ModulePermissionInfo(); - objModulePermission.ModuleID = objModule.ModuleID; - objModulePermission.PermissionID = permission.PermissionID; - objModulePermission.RoleID = roleId; - objModulePermission.UserID = userId; - objModulePermission.PermissionKey = permission.PermissionKey; - objModulePermission.AllowAccess = allowAccess; - - // add the permission to the collection - if (!objModule.ModulePermissions.Contains(objModulePermission)) - { - objModule.ModulePermissions.Add(objModulePermission); - } + return IsModuleAdminInternal(); + } - return objModulePermission; + protected bool IsPageAdmin() + { + return IsPageAdminInternal(); } /// ----------------------------------------------------------------------------- @@ -379,6 +356,35 @@ protected void AddNewModule(string title, int desktopModuleId, string paneName, } } + /// ----------------------------------------------------------------------------- + /// + /// Adds a Module Permission. + /// + /// Module Info. + /// The permission to add. + /// The Id of the role to add the permission for. + /// Operator. + /// Whether allow to access the module. + /// ----------------------------------------------------------------------------- + private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess) + { + var objModulePermission = new ModulePermissionInfo(); + objModulePermission.ModuleID = objModule.ModuleID; + objModulePermission.PermissionID = permission.PermissionID; + objModulePermission.RoleID = roleId; + objModulePermission.UserID = userId; + objModulePermission.PermissionKey = permission.PermissionKey; + objModulePermission.AllowAccess = allowAccess; + + // add the permission to the collection + if (!objModule.ModulePermissions.Contains(objModulePermission)) + { + objModule.ModulePermissions.Add(objModulePermission); + } + + return objModulePermission; + } + /// ----------------------------------------------------------------------------- /// /// Builds a URL. @@ -452,11 +458,5 @@ protected override void OnInit(EventArgs e) base.OnInit(e); } } - - protected enum ViewPermissionType - { - View = 0, - Edit = 1, - } } } diff --git a/DNN Platform/Library/UI/ControlUtilities.cs b/DNN Platform/Library/UI/ControlUtilities.cs index 4eb5b90f993..3099949d7cd 100644 --- a/DNN Platform/Library/UI/ControlUtilities.cs +++ b/DNN Platform/Library/UI/ControlUtilities.cs @@ -53,28 +53,28 @@ public static T FindControl(Control control, string id, bool recursive) public static T FindFirstDescendent(Control control) where T : Control - { - return FindFirstDescendent(control, idx => idx is T); + { + return FindFirstDescendent(control, idx => idx is T); } public static T FindFirstDescendent(Control control, Predicate predicate) where T : Control - { - if (predicate(control)) + { + if (predicate(control)) { return control as T; } - foreach (Control childControl in control.Controls) - { - T descendent = FindFirstDescendent(childControl, predicate); - if (descendent != null) + foreach (Control childControl in control.Controls) + { + T descendent = FindFirstDescendent(childControl, predicate); + if (descendent != null) { return descendent; } - } - - return null; + } + + return null; } /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/UI/FavIcon.cs b/DNN Platform/Library/UI/FavIcon.cs index 145c4817bf7..96b6723baa8 100644 --- a/DNN Platform/Library/UI/FavIcon.cs +++ b/DNN Platform/Library/UI/FavIcon.cs @@ -31,27 +31,6 @@ public FavIcon(int portalId) this._portalId = portalId; } - /// - /// Get the path of the favicon file relative to the portal root. - /// - /// This relative path is only relevant to use with Host/Portal Settings the path is not guaranteed any - /// physical relevance in the local file system. - /// Path to the favicon file relative to portal root, or empty string when there is no favicon set. - public string GetSettingPath() - { - return PortalController.GetPortalSetting(SettingName, this._portalId, string.Empty); - } - - /// - /// Update the file to use for a favIcon. - /// - /// 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); - DataCache.ClearCache(GetCacheKey(this._portalId)); - } - /// /// Get the HTML for a favicon link. /// @@ -87,21 +66,25 @@ public static string GetHeaderLink(int portalId) return headerLink; } - private string GetRelativeUrl() + /// + /// Get the path of the favicon file relative to the portal root. + /// + /// This relative path is only relevant to use with Host/Portal Settings the path is not guaranteed any + /// physical relevance in the local file system. + /// Path to the favicon file relative to portal root, or empty string when there is no favicon set. + public string GetSettingPath() { - var fileInfo = this.GetFileInfo(); - return fileInfo == null ? string.Empty : FileManager.Instance.GetUrl(fileInfo); + return PortalController.GetPortalSetting(SettingName, this._portalId, string.Empty); } - private IFileInfo GetFileInfo() + /// + /// Update the file to use for a favIcon. + /// + /// The file id or Null.NullInteger for none. + public void Update(int fileId) { - var path = this.GetSettingPath(); - if (!string.IsNullOrEmpty(path)) - { - return FileManager.Instance.GetFile(this._portalId, path); - } - - return null; + PortalController.UpdatePortalSetting(this._portalId, SettingName, fileId != Null.NullInteger ? string.Format("FileID={0}", fileId) : string.Empty, /*clearCache*/ true); + DataCache.ClearCache(GetCacheKey(this._portalId)); } private static void UpdateCachedHeaderLink(int portalId, string headerLink) @@ -116,5 +99,22 @@ private static string GetCacheKey(int portalId) { return "FAVICON" + portalId; } + + private string GetRelativeUrl() + { + var fileInfo = this.GetFileInfo(); + return fileInfo == null ? string.Empty : FileManager.Instance.GetUrl(fileInfo); + } + + private IFileInfo GetFileInfo() + { + var path = this.GetSettingPath(); + if (!string.IsNullOrEmpty(path)) + { + return FileManager.Instance.GetFile(this._portalId, path); + } + + return null; + } } } diff --git a/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs b/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs index 16e0615c5c2..ad72fade265 100644 --- a/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs +++ b/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs @@ -33,7 +33,7 @@ protected override void OnInit(EventArgs e) { base.OnInit(e); - if (! string.IsNullOrEmpty(this._html5File)) + if (!string.IsNullOrEmpty(this._html5File)) { // Check if css file exists var cssFile = Path.ChangeExtension(this._html5File, ".css"); @@ -60,6 +60,24 @@ protected override void OnInit(EventArgs e) ServicesFramework.Instance.RequestAjaxScriptSupport(); } + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (!string.IsNullOrEmpty(this._html5File)) + { + this.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(this._fileContent))); + } + } + + private static string GetFileContentInternal(string filepath) + { + using (var reader = new StreamReader(filepath)) + { + return reader.ReadToEnd(); + } + } + private string GetFileContent(string filepath) { var cacheKey = string.Format(DataCache.SpaModulesContentHtmlFileCacheKey, filepath); @@ -82,23 +100,5 @@ private bool FileExists(string filepath) DataCache.SpaModulesHtmlFileCachePriority), c => File.Exists(this.Page.Server.MapPath(filepath))); } - - private static string GetFileContentInternal(string filepath) - { - using (var reader = new StreamReader(filepath)) - { - return reader.ReadToEnd(); - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (! string.IsNullOrEmpty(this._html5File)) - { - this.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(this._fileContent))); - } - } } } diff --git a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs index 39d2eb46b90..f78fee1d849 100644 --- a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs @@ -19,47 +19,6 @@ public class ModuleControlFactory { private static readonly ILog TracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - private static IModuleControlFactory GetModuleControlFactory(string controlSrc) - { - string extension = Path.GetExtension(controlSrc.ToLowerInvariant()); - - IModuleControlFactory controlFactory = null; - Type factoryType; - switch (extension) - { - case ".ascx": - controlFactory = new WebFormsModuleControlFactory(); - break; - case ".html": - case ".htm": - controlFactory = new Html5ModuleControlFactory(); - break; - case ".cshtml": - case ".vbhtml": - factoryType = Reflection.CreateType("DotNetNuke.Web.Razor.RazorModuleControlFactory"); - if (factoryType != null) - { - controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; - } - - break; - case ".mvc": - factoryType = Reflection.CreateType("DotNetNuke.Web.Mvc.MvcModuleControlFactory"); - if (factoryType != null) - { - controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; - } - - break; - default: - controlFactory = new ReflectedModuleControlFactory(); - break; - } - - return controlFactory; - } - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] public static Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlKey, string controlSrc) { @@ -136,6 +95,47 @@ public static Control LoadModuleControl(TemplateControl containerControl, Module return control; } + [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] + private static IModuleControlFactory GetModuleControlFactory(string controlSrc) + { + string extension = Path.GetExtension(controlSrc.ToLowerInvariant()); + + IModuleControlFactory controlFactory = null; + Type factoryType; + switch (extension) + { + case ".ascx": + controlFactory = new WebFormsModuleControlFactory(); + break; + case ".html": + case ".htm": + controlFactory = new Html5ModuleControlFactory(); + break; + case ".cshtml": + case ".vbhtml": + factoryType = Reflection.CreateType("DotNetNuke.Web.Razor.RazorModuleControlFactory"); + if (factoryType != null) + { + controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; + } + + break; + case ".mvc": + factoryType = Reflection.CreateType("DotNetNuke.Web.Mvc.MvcModuleControlFactory"); + if (factoryType != null) + { + controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; + } + + break; + default: + controlFactory = new ReflectedModuleControlFactory(); + break; + } + + return controlFactory; + } + [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] public static Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) { diff --git a/DNN Platform/Library/UI/Modules/ModuleHost.cs b/DNN Platform/Library/UI/Modules/ModuleHost.cs index bd0410d5e2c..8612a41aaba 100644 --- a/DNN Platform/Library/UI/Modules/ModuleHost.cs +++ b/DNN Platform/Library/UI/Modules/ModuleHost.cs @@ -45,14 +45,14 @@ namespace DotNetNuke.UI.Modules /// public sealed class ModuleHost : Panel { + private const string DefaultCssProvider = "DnnPageHeaderProvider"; + private const string DefaultJsProvider = "DnnBodyProvider"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleHost)); private static readonly Regex CdfMatchRegex = new Regex( @"<\!--CDF\((?JAVASCRIPT|CSS|JS-LIBRARY)\|(?.+?)(\|(?.+?)\|(?\d+?))?\)-->", RegexOptions.IgnoreCase | RegexOptions.Compiled); - - private const string DefaultCssProvider = "DnnPageHeaderProvider"; - private const string DefaultJsProvider = "DnnBodyProvider"; private readonly ModuleInfo _moduleConfiguration; private Control _control; private bool _isCached; @@ -104,6 +104,84 @@ public PortalSettings PortalSettings public Skins.Skin Skin { get; private set; } + /// ----------------------------------------------------------------------------- + /// + /// Gets a flag that indicates whether the Module is in View Mode. + /// + /// A Boolean. + internal static bool IsViewMode(ModuleInfo moduleInfo, PortalSettings settings) + { + bool viewMode; + + if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.ViewPermissions, Null.NullString, + moduleInfo)) + { + viewMode = false; + } + else + { + viewMode = !ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, Null.NullString, + moduleInfo); + } + + return viewMode || settings.UserMode == PortalSettings.Mode.View; + } + + /// ----------------------------------------------------------------------------- + /// + /// CreateChildControls builds the control tree. + /// + protected override void CreateChildControls() + { + this.Controls.Clear(); + + // Load Module Control (or cached control) + this.LoadModuleControl(); + + // Optionally Inject AJAX Update Panel + if (this.ModuleControl != null) + { + // if module is dynamically loaded and AJAX is installed and the control supports partial rendering (defined in ModuleControls table ) + if (!this._isCached && this._moduleConfiguration.ModuleControl.SupportsPartialRendering && AJAX.IsInstalled()) + { + this.LoadUpdatePanel(); + } + else + { + // inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage + InjectMessageControl(this); + + this.InjectVersionToTheModuleIfSupported(); + + // inject the module into the panel + this.InjectModuleContent(this._control); + } + } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (Host.EnableCustomModuleCssClass) + { + string moduleName = this.ModuleControl.ModuleContext.Configuration.DesktopModule.ModuleName; + if (moduleName != null) + { + moduleName = Globals.CleanName(moduleName); + } + + this.Attributes.Add("class", string.Format("DNNModuleContent Mod{0}C", moduleName)); + } + } + + private static void InjectMessageControl(Control container) + { + // inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage + var messagePlaceholder = new PlaceHolder { ID = "MessagePlaceHolder", Visible = false }; + container.Controls.Add(messagePlaceholder); + } + private bool IsVersionRequest() { int version; @@ -131,10 +209,10 @@ private void InjectModuleContent(Control content) // Assign the class - hslice to the Drag-N-Drop Panel this.CssClass = "hslice"; var titleLabel = new Label - { - CssClass = "entry-title Hidden", - Text = !string.IsNullOrEmpty(this._moduleConfiguration.WebSliceTitle) ? this._moduleConfiguration.WebSliceTitle : this._moduleConfiguration.ModuleTitle, - }; + { + CssClass = "entry-title Hidden", + Text = !string.IsNullOrEmpty(this._moduleConfiguration.WebSliceTitle) ? this._moduleConfiguration.WebSliceTitle : this._moduleConfiguration.ModuleTitle, + }; this.Controls.Add(titleLabel); var websliceContainer = new Panel { CssClass = "entry-content" }; @@ -206,36 +284,6 @@ private bool DisplayContent() return content; } - private static void InjectMessageControl(Control container) - { - // inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage - var messagePlaceholder = new PlaceHolder { ID = "MessagePlaceHolder", Visible = false }; - container.Controls.Add(messagePlaceholder); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets a flag that indicates whether the Module is in View Mode. - /// - /// A Boolean. - internal static bool IsViewMode(ModuleInfo moduleInfo, PortalSettings settings) - { - bool viewMode; - - if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.ViewPermissions, Null.NullString, - moduleInfo)) - { - viewMode = false; - } - else - { - viewMode = ! ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, Null.NullString, - moduleInfo); - } - - return viewMode || settings.UserMode == PortalSettings.Mode.View; - } - /// ----------------------------------------------------------------------------- /// /// LoadModuleControl loads the ModuleControl (PortalModuelBase). @@ -319,10 +367,10 @@ private void LoadUpdatePanel() // create update panel var updatePanel = new UpdatePanel - { - UpdateMode = UpdatePanelUpdateMode.Conditional, - ID = this._control.ID + "_UP", - }; + { + UpdateMode = UpdatePanelUpdateMode.Conditional, + ID = this._control.ID + "_UP", + }; // get update panel content template var templateContainer = updatePanel.ContentTemplateContainer; @@ -341,12 +389,12 @@ private void LoadUpdatePanel() // inject updateprogress into the panel var updateProgress = new UpdateProgress - { - AssociatedUpdatePanelID = updatePanel.ID, - ID = updatePanel.ID + "_Prog", + { + AssociatedUpdatePanelID = updatePanel.ID, + ID = updatePanel.ID + "_Prog", - ProgressTemplate = new LiteralTemplate(progressTemplate), - }; + ProgressTemplate = new LiteralTemplate(progressTemplate), + }; this.Controls.Add(updateProgress); } @@ -480,54 +528,6 @@ private void RestoreCachedClientResourceRegistrations(string cachedContent) } } - /// ----------------------------------------------------------------------------- - /// - /// CreateChildControls builds the control tree. - /// - protected override void CreateChildControls() - { - this.Controls.Clear(); - - // Load Module Control (or cached control) - this.LoadModuleControl(); - - // Optionally Inject AJAX Update Panel - if (this.ModuleControl != null) - { - // if module is dynamically loaded and AJAX is installed and the control supports partial rendering (defined in ModuleControls table ) - if (!this._isCached && this._moduleConfiguration.ModuleControl.SupportsPartialRendering && AJAX.IsInstalled()) - { - this.LoadUpdatePanel(); - } - else - { - // inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage - InjectMessageControl(this); - - this.InjectVersionToTheModuleIfSupported(); - - // inject the module into the panel - this.InjectModuleContent(this._control); - } - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (Host.EnableCustomModuleCssClass) - { - string moduleName = this.ModuleControl.ModuleContext.Configuration.DesktopModule.ModuleName; - if (moduleName != null) - { - moduleName = Globals.CleanName(moduleName); - } - - this.Attributes.Add("class", string.Format("DNNModuleContent Mod{0}C", moduleName)); - } - } - /// ----------------------------------------------------------------------------- /// /// RenderContents renders the contents of the control to the output stream. diff --git a/DNN Platform/Library/UI/Modules/ModuleInjectionManager.cs b/DNN Platform/Library/UI/Modules/ModuleInjectionManager.cs index 841e9c39a00..899ca5628f6 100644 --- a/DNN Platform/Library/UI/Modules/ModuleInjectionManager.cs +++ b/DNN Platform/Library/UI/Modules/ModuleInjectionManager.cs @@ -29,6 +29,16 @@ public static void RegisterInjectionFilters() } } + public static bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings) + { + return _filters.All(filter => filter.CanInjectModule(module, portalSettings)); + } + + internal static bool IsValidModuleInjectionFilter(Type t) + { + return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IModuleInjectionFilter).IsAssignableFrom(t); + } + private static IEnumerable GetFilters() { var typeLocator = new TypeLocator(); @@ -54,15 +64,5 @@ private static IEnumerable GetFilters() } } } - - internal static bool IsValidModuleInjectionFilter(Type t) - { - return t != null && t.IsClass && !t.IsAbstract && t.IsVisible && typeof(IModuleInjectionFilter).IsAssignableFrom(t); - } - - public static bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings) - { - return _filters.All(filter => filter.CanInjectModule(module, portalSettings)); - } } } diff --git a/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs b/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs index 0ee7ade75f3..be2a6f48656 100644 --- a/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs +++ b/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs @@ -275,6 +275,44 @@ public int TabModuleId } } + public string EditUrl() + { + return this.EditUrl(string.Empty, string.Empty, "Edit"); + } + + public string EditUrl(string controlKey) + { + return this.EditUrl(string.Empty, string.Empty, controlKey); + } + + private static string FilterUrl(HttpRequest request) + { + return request.RawUrl.Replace("\"", string.Empty); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetActionsCount gets the current number of actions. + /// + /// The actions collection to count. + /// The current count. + /// ----------------------------------------------------------------------------- + private static int GetActionsCount(int count, ModuleActionCollection actions) + { + foreach (ModuleAction action in actions) + { + if (action.HasChildren()) + { + count += action.Actions.Count; + + // Recursively call to see if this collection has any child actions that would affect the count + count = GetActionsCount(count, action.Actions); + } + } + + return count; + } + /// ----------------------------------------------------------------------------- /// /// AddHelpActions Adds the Help actions to the Action Menu. @@ -305,29 +343,29 @@ private void AddHelpActions() } var helpAction = new ModuleAction(this.GetNextActionID()) - { - Title = Localization.GetString(ModuleActionType.ModuleHelp, Localization.GlobalResourceFile), - CommandName = ModuleActionType.ModuleHelp, - CommandArgument = string.Empty, - Icon = "action_help.gif", - Url = url, - Secure = SecurityAccessLevel.Edit, - Visible = true, - NewWindow = showInNewWindow, - UseActionEvent = true, - }; + { + Title = Localization.GetString(ModuleActionType.ModuleHelp, Localization.GlobalResourceFile), + CommandName = ModuleActionType.ModuleHelp, + CommandArgument = string.Empty, + Icon = "action_help.gif", + Url = url, + Secure = SecurityAccessLevel.Edit, + Visible = true, + NewWindow = showInNewWindow, + UseActionEvent = true, + }; this._moduleGenericActions.Actions.Add(helpAction); } private void AddPrintAction() { var action = new ModuleAction(this.GetNextActionID()) - { - Title = Localization.GetString(ModuleActionType.PrintModule, Localization.GlobalResourceFile), - CommandName = ModuleActionType.PrintModule, - CommandArgument = string.Empty, - Icon = "action_print.gif", - Url = this.NavigateUrl( + { + Title = Localization.GetString(ModuleActionType.PrintModule, Localization.GlobalResourceFile), + CommandName = ModuleActionType.PrintModule, + CommandArgument = string.Empty, + Icon = "action_print.gif", + Url = this.NavigateUrl( this.TabId, string.Empty, false, @@ -335,28 +373,28 @@ private void AddPrintAction() "SkinSrc=" + Globals.QueryStringEncode("[G]" + SkinController.RootSkin + "/" + Globals.glbHostSkinFolder + "/" + "No Skin"), "ContainerSrc=" + Globals.QueryStringEncode("[G]" + SkinController.RootContainer + "/" + Globals.glbHostSkinFolder + "/" + "No Container"), "dnnprintmode=true"), - Secure = SecurityAccessLevel.Anonymous, - UseActionEvent = true, - Visible = true, - NewWindow = true, - }; + Secure = SecurityAccessLevel.Anonymous, + UseActionEvent = true, + Visible = true, + NewWindow = true, + }; this._moduleGenericActions.Actions.Add(action); } private void AddSyndicateAction() { var action = new ModuleAction(this.GetNextActionID()) - { - Title = Localization.GetString(ModuleActionType.SyndicateModule, Localization.GlobalResourceFile), - CommandName = ModuleActionType.SyndicateModule, - CommandArgument = string.Empty, - Icon = "action_rss.gif", - Url = this.NavigateUrl(this.PortalSettings.ActiveTab.TabID, string.Empty, "RSS.aspx", false, "moduleid=" + this.ModuleId), - Secure = SecurityAccessLevel.Anonymous, - UseActionEvent = true, - Visible = true, - NewWindow = true, - }; + { + Title = Localization.GetString(ModuleActionType.SyndicateModule, Localization.GlobalResourceFile), + CommandName = ModuleActionType.SyndicateModule, + CommandArgument = string.Empty, + Icon = "action_rss.gif", + Url = this.NavigateUrl(this.PortalSettings.ActiveTab.TabID, string.Empty, "RSS.aspx", false, "moduleid=" + this.ModuleId), + Secure = SecurityAccessLevel.Anonymous, + UseActionEvent = true, + Visible = true, + NewWindow = true, + }; this._moduleGenericActions.Actions.Add(action); } @@ -449,34 +487,6 @@ private void AddMenuMoveActions() } } - private static string FilterUrl(HttpRequest request) - { - return request.RawUrl.Replace("\"", string.Empty); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetActionsCount gets the current number of actions. - /// - /// The actions collection to count. - /// The current count. - /// ----------------------------------------------------------------------------- - private static int GetActionsCount(int count, ModuleActionCollection actions) - { - foreach (ModuleAction action in actions) - { - if (action.HasChildren()) - { - count += action.Actions.Count; - - // Recursively call to see if this collection has any child actions that would affect the count - count = GetActionsCount(count, action.Actions); - } - } - - return count; - } - /// ----------------------------------------------------------------------------- /// /// LoadActions loads the Actions collections. @@ -739,16 +749,6 @@ private bool SupportShowInPopup(string url) || (!isSecureConnection && url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)); } - public string EditUrl() - { - return this.EditUrl(string.Empty, string.Empty, "Edit"); - } - - public string EditUrl(string controlKey) - { - return this.EditUrl(string.Empty, string.Empty, controlKey); - } - public string EditUrl(string keyName, string keyValue) { return this.EditUrl(keyName, keyValue, "Edit"); diff --git a/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs b/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs index 58e7df02f67..6bb4821d45d 100644 --- a/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs @@ -23,16 +23,6 @@ public class ModuleUserControlBase : UserControl, IModuleControl { private string _localResourceFile; private ModuleInstanceContext _moduleContext; - - protected string LocalizeString(string key) - { - return Localization.GetString(key, this.LocalResourceFile); - } - - protected string LocalizeSafeJsString(string key) - { - return Localization.GetSafeJSString(key, this.LocalResourceFile); - } /// ----------------------------------------------------------------------------- /// @@ -76,6 +66,16 @@ public string ControlName } } + protected string LocalizeString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } + + protected string LocalizeSafeJsString(string key) + { + return Localization.GetSafeJSString(key, this.LocalResourceFile); + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the local resource file for this control. diff --git a/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs b/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs index 8999f64c012..572f4ae279f 100644 --- a/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs @@ -17,8 +17,6 @@ namespace DotNetNuke.UI.Modules public abstract class ProfileModuleUserControlBase : ModuleUserControlBase, IProfileModule { - protected INavigationManager NavigationManager { get; } - public ProfileModuleUserControlBase() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); @@ -39,6 +37,8 @@ public int ProfileUserId } } + protected INavigationManager NavigationManager { get; } + protected bool IsUser { get { return this.ProfileUserId == this.ModuleContext.PortalSettings.UserId; } @@ -49,25 +49,6 @@ protected UserInfo ProfileUser get { return UserController.GetUserById(this.ModuleContext.PortalId, this.ProfileUserId); } } - private string GetRedirectUrl() - { - // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. - var homeTabId = this.ModuleContext.PortalSettings.HomeTabId; - string redirectUrl; - - if (homeTabId > Null.NullInteger) - { - redirectUrl = TestableGlobals.Instance.NavigateURL(homeTabId); - } - else - { - redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, this.Request, true) + - "/" + Globals.glbDefaultPage; - } - - return redirectUrl; - } - protected override void OnInit(EventArgs e) { if (string.IsNullOrEmpty(this.Request.Params["UserId"]) && @@ -90,5 +71,24 @@ protected override void OnInit(EventArgs e) base.OnInit(e); } + + private string GetRedirectUrl() + { + // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. + var homeTabId = this.ModuleContext.PortalSettings.HomeTabId; + string redirectUrl; + + if (homeTabId > Null.NullInteger) + { + redirectUrl = TestableGlobals.Instance.NavigateURL(homeTabId); + } + else + { + redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, this.Request, true) + + "/" + Globals.glbDefaultPage; + } + + return redirectUrl; + } } } diff --git a/DNN Platform/Library/UI/Navigation.cs b/DNN Platform/Library/UI/Navigation.cs index 911d1a47bbd..f6f4ee449c8 100644 --- a/DNN Platform/Library/UI/Navigation.cs +++ b/DNN Platform/Library/UI/Navigation.cs @@ -38,6 +38,21 @@ public enum ToolTipSource None, } + public static bool CanShowTab(TabInfo objTab, bool isAdminMode, bool showDisabled) + { + return CanShowTab(objTab, isAdminMode, showDisabled, false); + } + + public static bool CanShowTab(TabInfo tab, bool isAdminMode, bool showDisabled, bool showHidden) + { + // if tab is visible, not deleted, not expired (or admin), and user has permission to see it... + return (tab.IsVisible || showHidden) && tab.HasAVisibleVersion && !tab.IsDeleted && + (!tab.DisableLink || showDisabled) && + (((tab.StartDate < DateTime.Now || tab.StartDate == Null.NullDate) && + (tab.EndDate > DateTime.Now || tab.EndDate == Null.NullDate)) || isAdminMode) && + TabPermissionController.CanNavigateToPage(tab); + } + /// ----------------------------------------------------------------------------- /// /// Recursive function to add module's actions to the DNNNodeCollection based off of passed in ModuleActions. @@ -365,21 +380,6 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob } } } - - public static bool CanShowTab(TabInfo objTab, bool isAdminMode, bool showDisabled) - { - return CanShowTab(objTab, isAdminMode, showDisabled, false); - } - - public static bool CanShowTab(TabInfo tab, bool isAdminMode, bool showDisabled, bool showHidden) - { - // if tab is visible, not deleted, not expired (or admin), and user has permission to see it... - return (tab.IsVisible || showHidden) && tab.HasAVisibleVersion && !tab.IsDeleted && - (!tab.DisableLink || showDisabled) && - (((tab.StartDate < DateTime.Now || tab.StartDate == Null.NullDate) && - (tab.EndDate > DateTime.Now || tab.EndDate == Null.NullDate)) || isAdminMode) && - TabPermissionController.CanNavigateToPage(tab); - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs b/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs index 2a5fc217135..d2087f7a31d 100644 --- a/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs +++ b/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs @@ -36,10 +36,10 @@ public LanguageTokenReplace() public class LanguagePropertyAccess : IPropertyAccess { + public LanguageTokenReplace objParent; private const string FlagIconPhysicalLocation = @"~\images\Flags"; private const string NonExistingFlagIconFileName = "none.gif"; private readonly PortalSettings objPortal; - public LanguageTokenReplace objParent; public LanguagePropertyAccess(LanguageTokenReplace parent, PortalSettings settings) { @@ -47,6 +47,14 @@ public LanguagePropertyAccess(LanguageTokenReplace parent, PortalSettings settin this.objParent = parent; } + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope CurrentScope, ref bool PropertyNotFound) { switch (propertyName.ToLowerInvariant()) @@ -74,14 +82,6 @@ public string GetProperty(string propertyName, string format, CultureInfo format } } - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - /// /// getQSParams builds up a new querystring. This is necessary /// in order to prep for navigateUrl. diff --git a/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs b/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs index f2a25e6ffcd..763d6372de9 100644 --- a/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs +++ b/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs @@ -15,6 +15,10 @@ namespace DotNetNuke.UI.Skins.Controls /// public class ModuleMessage : SkinObjectBase { + protected Panel dnnSkinMessage; + protected Label lblHeading; + protected Label lblMessage; + public enum ModuleMessageType { GreenSuccess, @@ -22,10 +26,6 @@ public enum ModuleMessageType RedError, BlueInfo, } - - protected Panel dnnSkinMessage; - protected Label lblHeading; - protected Label lblMessage; protected Control scrollScript; public string Text { get; set; } diff --git a/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs b/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs index b03db3ad2b2..7d654302961 100644 --- a/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs +++ b/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs @@ -178,6 +178,35 @@ public void RaisePostBackEvent(string eventArgument) } } + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + bool dataChanged = false; + string postedValue; + var newDictionaryValue = new Dictionary(); + foreach (KeyValuePair kvp in this.DictionaryValue) + { + postedValue = postCollection[this.UniqueID + "_skin" + kvp.Key]; + if (kvp.Value.Equals(postedValue)) + { + newDictionaryValue[kvp.Key] = kvp.Value; + } + else + { + newDictionaryValue[kvp.Key] = postedValue; + dataChanged = true; + } + } + + postedValue = postCollection[this.UniqueID + "_skinnew"]; + if (!string.IsNullOrEmpty(postedValue)) + { + this.AddedItem = postedValue; + } + + this.DictionaryValue = newDictionaryValue; + return dataChanged; + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged @@ -319,34 +348,5 @@ protected override void RenderViewMode(HtmlTextWriter writer) } } } - - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - bool dataChanged = false; - string postedValue; - var newDictionaryValue = new Dictionary(); - foreach (KeyValuePair kvp in this.DictionaryValue) - { - postedValue = postCollection[this.UniqueID + "_skin" + kvp.Key]; - if (kvp.Value.Equals(postedValue)) - { - newDictionaryValue[kvp.Key] = kvp.Value; - } - else - { - newDictionaryValue[kvp.Key] = postedValue; - dataChanged = true; - } - } - - postedValue = postCollection[this.UniqueID + "_skinnew"]; - if (!string.IsNullOrEmpty(postedValue)) - { - this.AddedItem = postedValue; - } - - this.DictionaryValue = newDictionaryValue; - return dataChanged; - } } } diff --git a/DNN Platform/Library/UI/Skins/NavObjectBase.cs b/DNN Platform/Library/UI/Skins/NavObjectBase.cs index b18cba06f13..1572bd43272 100644 --- a/DNN Platform/Library/UI/Skins/NavObjectBase.cs +++ b/DNN Platform/Library/UI/Skins/NavObjectBase.cs @@ -124,14 +124,6 @@ public string ProviderName } } - protected NavigationProvider Control - { - get - { - return this.m_objControl; - } - } - public string Level { get @@ -158,6 +150,14 @@ public string ToolTip } } + protected NavigationProvider Control + { + get + { + return this.m_objControl; + } + } + public bool PopulateNodesFromClient { get @@ -2407,6 +2407,11 @@ protected void InitializeNavControl(Control objParent, string strDefaultProvider this.AssignControlProperties(); objParent.Controls.Add(this.Control.NavigationControl); } + + protected void Bind(DNNNodeCollection objNodes) + { + this.Control.Bind(objNodes); + } private void AssignControlProperties() { @@ -2808,11 +2813,6 @@ private void AssignControlProperties() this.Control.CustomAttributes = this.CustomAttributes; } - protected void Bind(DNNNodeCollection objNodes) - { - this.Control.Bind(objNodes); - } - private string GetPath(string strPath) { if (strPath.IndexOf("[SKINPATH]") > -1) diff --git a/DNN Platform/Library/UI/Skins/Pane.cs b/DNN Platform/Library/UI/Skins/Pane.cs index 37ee932d7f4..3cf8eac8836 100644 --- a/DNN Platform/Library/UI/Skins/Pane.cs +++ b/DNN Platform/Library/UI/Skins/Pane.cs @@ -111,6 +111,203 @@ protected PortalSettings PortalSettings return PortalController.Instance.GetCurrentPortalSettings(); } } + + /// ----------------------------------------------------------------------------- + /// + /// InjectModule injects a Module (and its container) into the Pane. + /// + /// The Module. + /// ----------------------------------------------------------------------------- + public void InjectModule(ModuleInfo module) + { + this._containerWrapperControl = new HtmlGenericControl("div"); + this.PaneControl.Controls.Add(this._containerWrapperControl); + + // inject module classes + string classFormatString = "DnnModule DnnModule-{0} DnnModule-{1}"; + string sanitizedModuleName = Null.NullString; + + if (!string.IsNullOrEmpty(module.DesktopModule.ModuleName)) + { + sanitizedModuleName = Globals.CreateValidClass(module.DesktopModule.ModuleName, false); + } + + if (this.IsVesionableModule(module)) + { + classFormatString += " DnnVersionableControl"; + } + + this._containerWrapperControl.Attributes["class"] = string.Format(classFormatString, sanitizedModuleName, module.ModuleID); + + try + { + if (!Globals.IsAdminControl() && (this.PortalSettings.InjectModuleHyperLink || this.PortalSettings.UserMode != PortalSettings.Mode.View)) + { + this._containerWrapperControl.Controls.Add(new LiteralControl("")); + } + + // Load container control + Containers.Container container = this.LoadModuleContainer(module); + + // Add Container to Dictionary + this.Containers.Add(container.ID, container); + + // hide anything of type ActionsMenu - as we're injecting our own menu now. + container.InjectActionMenu = container.Controls.OfType().Count() == 0; + if (!container.InjectActionMenu) + { + foreach (var actionControl in container.Controls.OfType()) + { + if (actionControl is ActionsMenu) + { + Control control = actionControl as Control; + if (control != null) + { + control.Visible = false; + container.InjectActionMenu = true; + } + } + } + } + + if (Globals.IsLayoutMode() && Globals.IsAdminControl() == false) + { + // provide Drag-N-Drop capabilities + var dragDropContainer = new Panel(); + Control title = container.FindControl("dnnTitle"); + + // Assume that the title control is named dnnTitle. If this becomes an issue we could loop through the controls looking for the title type of skin object + dragDropContainer.ID = container.ID + "_DD"; + this._containerWrapperControl.Controls.Add(dragDropContainer); + + // inject the container into the page pane - this triggers the Pre_Init() event for the user control + dragDropContainer.Controls.Add(container); + + if (title != null) + { + if (title.Controls.Count > 0) + { + title = title.Controls[0]; + } + } + + // enable drag and drop + if (title != null) + { + // The title ID is actually the first child so we need to make sure at least one child exists + DNNClientAPI.EnableContainerDragAndDrop(title, dragDropContainer, module.ModuleID); + ClientAPI.RegisterPostBackEventHandler(this.PaneControl, "MoveToPane", this.ModuleMoveToPanePostBack, false); + } + } + else + { + this._containerWrapperControl.Controls.Add(container); + if (Globals.IsAdminControl()) + { + this._containerWrapperControl.Attributes["class"] += " DnnModule-Admin"; + } + } + + // Attach Module to Container + container.SetModuleConfiguration(module); + + // display collapsible page panes + if (this.PaneControl.Visible == false) + { + 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. + } + catch (Exception exc) + { + var lex = new ModuleLoadException(string.Format(Skin.MODULEADD_ERROR, this.PaneControl.ID), exc); + if (TabPermissionController.CanAdminPage()) + { + // only display the error to administrators + this._containerWrapperControl.Controls.Add(new ErrorContainer(this.PortalSettings, Skin.MODULELOAD_ERROR, lex).Container); + } + + Exceptions.LogException(exc); + throw lex; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// ProcessPane processes the Attributes for the PaneControl. + /// + /// ----------------------------------------------------------------------------- + public void ProcessPane() + { + if (this.PaneControl != null) + { + // remove excess skin non-validating attributes + this.PaneControl.Attributes.Remove("ContainerType"); + this.PaneControl.Attributes.Remove("ContainerName"); + this.PaneControl.Attributes.Remove("ContainerSrc"); + + if (Globals.IsLayoutMode()) + { + this.PaneControl.Visible = true; + + // display pane border + string cssclass = this.PaneControl.Attributes["class"]; + if (string.IsNullOrEmpty(cssclass)) + { + this.PaneControl.Attributes["class"] = CPaneOutline; + } + else + { + this.PaneControl.Attributes["class"] = cssclass.Replace(CPaneOutline, string.Empty).Trim().Replace(" ", " ") + " " + CPaneOutline; + } + + // display pane name + var ctlLabel = new Label { Text = "
" + this.Name + "

", CssClass = "SubHead" }; + this.PaneControl.Controls.AddAt(0, ctlLabel); + } + else + { + if (this.PaneControl.Visible == false && TabPermissionController.CanAddContentToPage()) + { + this.PaneControl.Visible = true; + } + + if (this.CanCollapsePane()) + { + // This pane has no controls so set the width to 0 + if (this.PaneControl.Attributes["style"] != null) + { + this.PaneControl.Attributes.Remove("style"); + } + + if (this.PaneControl.Attributes["class"] != null) + { + this.PaneControl.Attributes["class"] = this.PaneControl.Attributes["class"] + " DNNEmptyPane"; + } + else + { + this.PaneControl.Attributes["class"] = "DNNEmptyPane"; + } + } + + // Add support for drag and drop + if (Globals.IsEditMode()) // this call also checks for permission + { + if (this.PaneControl.Attributes["class"] != null) + { + this.PaneControl.Attributes["class"] = this.PaneControl.Attributes["class"] + " dnnSortable"; + } + else + { + this.PaneControl.Attributes["class"] = "dnnSortable"; + } + } + } + } + } private bool CanCollapsePane() { @@ -406,211 +603,14 @@ private void ModuleMoveToPanePostBack(ClientAPIPostBackEventArgs args) } private bool IsVesionableModule(ModuleInfo moduleInfo) - { - if (string.IsNullOrEmpty(moduleInfo.DesktopModule.BusinessControllerClass)) + { + if (string.IsNullOrEmpty(moduleInfo.DesktopModule.BusinessControllerClass)) { return false; - } - - object controller = Framework.Reflection.CreateObject(moduleInfo.DesktopModule.BusinessControllerClass, string.Empty); - return controller is IVersionable; - } - - /// ----------------------------------------------------------------------------- - /// - /// InjectModule injects a Module (and its container) into the Pane. - /// - /// The Module. - /// ----------------------------------------------------------------------------- - public void InjectModule(ModuleInfo module) - { - this._containerWrapperControl = new HtmlGenericControl("div"); - this.PaneControl.Controls.Add(this._containerWrapperControl); - - // inject module classes - string classFormatString = "DnnModule DnnModule-{0} DnnModule-{1}"; - string sanitizedModuleName = Null.NullString; - - if (!string.IsNullOrEmpty(module.DesktopModule.ModuleName)) - { - sanitizedModuleName = Globals.CreateValidClass(module.DesktopModule.ModuleName, false); - } - - if (this.IsVesionableModule(module)) - { - classFormatString += " DnnVersionableControl"; - } - - this._containerWrapperControl.Attributes["class"] = string.Format(classFormatString, sanitizedModuleName, module.ModuleID); - - try - { - if (!Globals.IsAdminControl() && (this.PortalSettings.InjectModuleHyperLink || this.PortalSettings.UserMode != PortalSettings.Mode.View)) - { - this._containerWrapperControl.Controls.Add(new LiteralControl("")); - } - - // Load container control - Containers.Container container = this.LoadModuleContainer(module); - - // Add Container to Dictionary - this.Containers.Add(container.ID, container); - - // hide anything of type ActionsMenu - as we're injecting our own menu now. - container.InjectActionMenu = container.Controls.OfType().Count() == 0; - if (!container.InjectActionMenu) - { - foreach (var actionControl in container.Controls.OfType()) - { - if (actionControl is ActionsMenu) - { - Control control = actionControl as Control; - if (control != null) - { - control.Visible = false; - container.InjectActionMenu = true; - } - } - } - } - - if (Globals.IsLayoutMode() && Globals.IsAdminControl() == false) - { - // provide Drag-N-Drop capabilities - var dragDropContainer = new Panel(); - Control title = container.FindControl("dnnTitle"); - - // Assume that the title control is named dnnTitle. If this becomes an issue we could loop through the controls looking for the title type of skin object - dragDropContainer.ID = container.ID + "_DD"; - this._containerWrapperControl.Controls.Add(dragDropContainer); - - // inject the container into the page pane - this triggers the Pre_Init() event for the user control - dragDropContainer.Controls.Add(container); - - if (title != null) - { - if (title.Controls.Count > 0) - { - title = title.Controls[0]; - } - } - - // enable drag and drop - if (title != null) - { - // The title ID is actually the first child so we need to make sure at least one child exists - DNNClientAPI.EnableContainerDragAndDrop(title, dragDropContainer, module.ModuleID); - ClientAPI.RegisterPostBackEventHandler(this.PaneControl, "MoveToPane", this.ModuleMoveToPanePostBack, false); - } - } - else - { - this._containerWrapperControl.Controls.Add(container); - if (Globals.IsAdminControl()) - { - this._containerWrapperControl.Attributes["class"] += " DnnModule-Admin"; - } - } - - // Attach Module to Container - container.SetModuleConfiguration(module); - - // display collapsible page panes - if (this.PaneControl.Visible == false) - { - 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. - } - catch (Exception exc) - { - var lex = new ModuleLoadException(string.Format(Skin.MODULEADD_ERROR, this.PaneControl.ID), exc); - if (TabPermissionController.CanAdminPage()) - { - // only display the error to administrators - this._containerWrapperControl.Controls.Add(new ErrorContainer(this.PortalSettings, Skin.MODULELOAD_ERROR, lex).Container); - } + } - Exceptions.LogException(exc); - throw lex; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// ProcessPane processes the Attributes for the PaneControl. - /// - /// ----------------------------------------------------------------------------- - public void ProcessPane() - { - if (this.PaneControl != null) - { - // remove excess skin non-validating attributes - this.PaneControl.Attributes.Remove("ContainerType"); - this.PaneControl.Attributes.Remove("ContainerName"); - this.PaneControl.Attributes.Remove("ContainerSrc"); - - if (Globals.IsLayoutMode()) - { - this.PaneControl.Visible = true; - - // display pane border - string cssclass = this.PaneControl.Attributes["class"]; - if (string.IsNullOrEmpty(cssclass)) - { - this.PaneControl.Attributes["class"] = CPaneOutline; - } - else - { - this.PaneControl.Attributes["class"] = cssclass.Replace(CPaneOutline, string.Empty).Trim().Replace(" ", " ") + " " + CPaneOutline; - } - - // display pane name - var ctlLabel = new Label { Text = "
" + this.Name + "

", CssClass = "SubHead" }; - this.PaneControl.Controls.AddAt(0, ctlLabel); - } - else - { - if (this.PaneControl.Visible == false && TabPermissionController.CanAddContentToPage()) - { - this.PaneControl.Visible = true; - } - - if (this.CanCollapsePane()) - { - // This pane has no controls so set the width to 0 - if (this.PaneControl.Attributes["style"] != null) - { - this.PaneControl.Attributes.Remove("style"); - } - - if (this.PaneControl.Attributes["class"] != null) - { - this.PaneControl.Attributes["class"] = this.PaneControl.Attributes["class"] + " DNNEmptyPane"; - } - else - { - this.PaneControl.Attributes["class"] = "DNNEmptyPane"; - } - } - - // Add support for drag and drop - if (Globals.IsEditMode()) // this call also checks for permission - { - if (this.PaneControl.Attributes["class"] != null) - { - this.PaneControl.Attributes["class"] = this.PaneControl.Attributes["class"] + " dnnSortable"; - } - else - { - this.PaneControl.Attributes["class"] = "dnnSortable"; - } - } - } - } + object controller = Framework.Reflection.CreateObject(moduleInfo.DesktopModule.BusinessControllerClass, string.Empty); + return controller is IVersionable; } } } diff --git a/DNN Platform/Library/UI/Skins/Skin.cs b/DNN Platform/Library/UI/Skins/Skin.cs index bd5d6fcd4ce..c6c70050034 100644 --- a/DNN Platform/Library/UI/Skins/Skin.cs +++ b/DNN Platform/Library/UI/Skins/Skin.cs @@ -59,14 +59,14 @@ namespace DotNetNuke.UI.Skins /// ----------------------------------------------------------------------------- public class Skin : UserControlBase { + public const string OnInitMessage = "Skin_InitMessage"; + public const string OnInitMessageType = "Skin_InitMessageType"; + // ReSharper disable InconsistentNaming public static string MODULELOAD_ERROR = Localization.GetString("ModuleLoad.Error"); public static string CONTAINERLOAD_ERROR = Localization.GetString("ContainerLoad.Error"); public static string MODULEADD_ERROR = Localization.GetString("ModuleAdd.Error"); - public const string OnInitMessage = "Skin_InitMessage"; - public const string OnInitMessageType = "Skin_InitMessageType"; - private readonly ModuleCommunicate _communicator = new ModuleCommunicate(); // ReSharper restore InconsistentNaming @@ -82,68 +82,68 @@ public Skin() /// ----------------------------------------------------------------------------- /// - /// Gets the ControlPanel container. + /// Gets a Dictionary of Panes. /// /// /// /// ----------------------------------------------------------------------------- - internal Control ControlPanel + public Dictionary Panes { get { - return this._controlPanel ?? (this._controlPanel = this.FindControl("ControlPanel")); + return this._panes ?? (this._panes = new Dictionary()); } } - protected IModuleControlPipeline ModuleControlPipeline { get; } - - protected INavigationManager NavigationManager { get; } - /// ----------------------------------------------------------------------------- /// - /// Gets the ModuleCommunicate instance for the skin. + /// Gets or sets an ArrayList of ActionEventListeners. /// - /// The ModuleCommunicate instance for the Skin. - internal ModuleCommunicate Communicator + /// ----------------------------------------------------------------------------- + public ArrayList ActionEventListeners { get { - return this._communicator; + return this._actionEventListeners ?? (this._actionEventListeners = new ArrayList()); } - } + + set + { + this._actionEventListeners = value; + } + } /// ----------------------------------------------------------------------------- /// - /// Gets a Dictionary of Panes. + /// Gets the ControlPanel container. /// /// /// /// ----------------------------------------------------------------------------- - public Dictionary Panes + internal Control ControlPanel { get { - return this._panes ?? (this._panes = new Dictionary()); + return this._controlPanel ?? (this._controlPanel = this.FindControl("ControlPanel")); } } - + /// ----------------------------------------------------------------------------- /// - /// Gets or sets an ArrayList of ActionEventListeners. + /// Gets the ModuleCommunicate instance for the skin. /// - /// ----------------------------------------------------------------------------- - public ArrayList ActionEventListeners + /// The ModuleCommunicate instance for the Skin. + internal ModuleCommunicate Communicator { get { - return this._actionEventListeners ?? (this._actionEventListeners = new ArrayList()); + return this._communicator; } + } + + protected IModuleControlPipeline ModuleControlPipeline { get; } - set - { - this._actionEventListeners = value; - } - } + protected INavigationManager NavigationManager { get; } /// ----------------------------------------------------------------------------- /// @@ -167,6 +167,88 @@ public string SkinPath /// ----------------------------------------------------------------------------- public string SkinSrc { get; set; } + public static void AddModuleMessage(PortalModuleBase control, string message, ModuleMessage.ModuleMessageType moduleMessageType) + { + AddModuleMessage(control, string.Empty, message, moduleMessageType, Null.NullString); + } + + public static void AddModuleMessage(PortalModuleBase control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) + { + AddModuleMessage(control, heading, message, moduleMessageType, Null.NullString); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnInit runs when the Skin is initialised. + /// + /// ----------------------------------------------------------------------------- + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + // Load the Panes + this.LoadPanes(); + + // Load the Module Control(s) + bool success = Globals.IsAdminControl() ? this.ProcessSlaveModule() : this.ProcessMasterModules(); + + // Load the Control Panel + this.InjectControlPanel(); + + // Register any error messages on the Skin + if (this.Request.QueryString["error"] != null && Host.ShowCriticalErrors) + { + AddPageMessage(this, Localization.GetString("CriticalError.Error"), " ", ModuleMessage.ModuleMessageType.RedError); + + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) + { + ServicesFramework.Instance.RequestAjaxScriptSupport(); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + + JavaScript.RequestRegistration(CommonJs.jQueryUI); + JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn_dom); + ClientResourceManager.RegisterScript(this.Page, "~/resources/shared/scripts/dnn.logViewer.js"); + } + } + + 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); + } + + this.InvokeSkinEvents(SkinEventType.OnSkinInit); + + if (HttpContext.Current != null && HttpContext.Current.Items.Contains(OnInitMessage)) + { + var messageType = ModuleMessage.ModuleMessageType.YellowWarning; + if (HttpContext.Current.Items.Contains(OnInitMessageType)) + { + messageType = (ModuleMessage.ModuleMessageType)Enum.Parse(typeof(ModuleMessage.ModuleMessageType), HttpContext.Current.Items[OnInitMessageType].ToString(), true); + } + + AddPageMessage(this, string.Empty, HttpContext.Current.Items[OnInitMessage].ToString(), messageType); + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + } + + // Process the Panes attributes + this.ProcessPanes(); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnLoad runs when the Skin is loaded. + /// + /// ----------------------------------------------------------------------------- + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.InvokeSkinEvents(SkinEventType.OnSkinLoad); + } + private static void AddModuleMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconSrc) { if (control != null) @@ -216,6 +298,41 @@ private static Control FindControlRecursive(Control rootControl, string controlI return null; } + + private static Skin LoadSkin(PageBase page, string skinPath) + { + Skin ctlSkin = null; + try + { + string skinSrc = skinPath; + if (skinPath.IndexOf(Globals.ApplicationPath, StringComparison.OrdinalIgnoreCase) != -1) + { + skinPath = skinPath.Remove(0, Globals.ApplicationPath.Length); + } + + ctlSkin = ControlUtilities.LoadControl(page, skinPath); + ctlSkin.SkinSrc = skinSrc; + + // call databind so that any server logic in the skin is executed + ctlSkin.DataBind(); + } + catch (Exception exc) + { + // could not load user control + var lex = new PageLoadException("Unhandled error loading page.", exc); + if (TabPermissionController.CanAdminPage()) + { + // 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.Visible = true; + } + + Exceptions.LogException(lex); + } + + return ctlSkin; + } private bool CheckExpired() { @@ -338,41 +455,6 @@ private void LoadPanes() } } - private static Skin LoadSkin(PageBase page, string skinPath) - { - Skin ctlSkin = null; - try - { - string skinSrc = skinPath; - if (skinPath.IndexOf(Globals.ApplicationPath, StringComparison.OrdinalIgnoreCase) != -1) - { - skinPath = skinPath.Remove(0, Globals.ApplicationPath.Length); - } - - ctlSkin = ControlUtilities.LoadControl(page, skinPath); - ctlSkin.SkinSrc = skinSrc; - - // call databind so that any server logic in the skin is executed - ctlSkin.DataBind(); - } - catch (Exception exc) - { - // could not load user control - var lex = new PageLoadException("Unhandled error loading page.", exc); - if (TabPermissionController.CanAdminPage()) - { - // 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.Visible = true; - } - - Exceptions.LogException(lex); - } - - return ctlSkin; - } - private bool ProcessModule(ModuleInfo module) { var success = true; @@ -571,78 +653,6 @@ private bool ProcessSlaveModule() return success; } - - /// ----------------------------------------------------------------------------- - /// - /// OnInit runs when the Skin is initialised. - /// - /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - // Load the Panes - this.LoadPanes(); - - // Load the Module Control(s) - bool success = Globals.IsAdminControl() ? this.ProcessSlaveModule() : this.ProcessMasterModules(); - - // Load the Control Panel - this.InjectControlPanel(); - - // Register any error messages on the Skin - if (this.Request.QueryString["error"] != null && Host.ShowCriticalErrors) - { - AddPageMessage(this, Localization.GetString("CriticalError.Error"), " ", ModuleMessage.ModuleMessageType.RedError); - - if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) - { - ServicesFramework.Instance.RequestAjaxScriptSupport(); - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - - JavaScript.RequestRegistration(CommonJs.jQueryUI); - JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn_dom); - ClientResourceManager.RegisterScript(this.Page, "~/resources/shared/scripts/dnn.logViewer.js"); - } - } - - 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); - } - - this.InvokeSkinEvents(SkinEventType.OnSkinInit); - - if (HttpContext.Current != null && HttpContext.Current.Items.Contains(OnInitMessage)) - { - var messageType = ModuleMessage.ModuleMessageType.YellowWarning; - if (HttpContext.Current.Items.Contains(OnInitMessageType)) - { - messageType = (ModuleMessage.ModuleMessageType)Enum.Parse(typeof(ModuleMessage.ModuleMessageType), HttpContext.Current.Items[OnInitMessageType].ToString(), true); - } - - AddPageMessage(this, string.Empty, HttpContext.Current.Items[OnInitMessage].ToString(), messageType); - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - } - - // Process the Panes attributes - this.ProcessPanes(); - } - - /// ----------------------------------------------------------------------------- - /// - /// OnLoad runs when the Skin is loaded. - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.InvokeSkinEvents(SkinEventType.OnSkinLoad); - } /// ----------------------------------------------------------------------------- /// @@ -700,16 +710,6 @@ protected override void OnUnload(EventArgs e) this.InvokeSkinEvents(SkinEventType.OnSkinUnLoad); } - - public static void AddModuleMessage(PortalModuleBase control, string message, ModuleMessage.ModuleMessageType moduleMessageType) - { - AddModuleMessage(control, string.Empty, message, moduleMessageType, Null.NullString); - } - - public static void AddModuleMessage(PortalModuleBase control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) - { - AddModuleMessage(control, heading, message, moduleMessageType, Null.NullString); - } /// ----------------------------------------------------------------------------- /// @@ -971,6 +971,23 @@ public static Skin GetSkin(PageBase page) return skin; } + public static List GetInstalledSkins() + { + var list = new List(); + foreach (string folder in Directory.GetDirectories(Path.Combine(Globals.HostMapPath, "Skins"))) + { + if (!folder.EndsWith(Globals.glbHostSkinFolder)) + { + var skin = new InstalledSkinInfo(); + skin.SkinName = folder.Substring(folder.LastIndexOf("\\") + 1); + skin.InUse = isFallbackSkin(folder) || !SkinController.CanDeleteSkin(folder, string.Empty); + list.Add(skin); + } + } + + return list; + } + /// ----------------------------------------------------------------------------- /// /// InjectModule injects the module into the Pane. @@ -1035,22 +1052,5 @@ private static bool isFallbackSkin(string skinPath) return skinPath.IndexOf(defaultSkinPath, StringComparison.CurrentCultureIgnoreCase) != -1; } - - public static List GetInstalledSkins() - { - var list = new List(); - foreach (string folder in Directory.GetDirectories(Path.Combine(Globals.HostMapPath, "Skins"))) - { - if (!folder.EndsWith(Globals.glbHostSkinFolder)) - { - var skin = new InstalledSkinInfo(); - skin.SkinName = folder.Substring(folder.LastIndexOf("\\") + 1); - skin.InUse = isFallbackSkin(folder) || !SkinController.CanDeleteSkin(folder, string.Empty); - list.Add(skin); - } - } - - return list; - } } } diff --git a/DNN Platform/Library/UI/Skins/SkinControl.cs b/DNN Platform/Library/UI/Skins/SkinControl.cs index da445bcb31a..e007bf65ee9 100644 --- a/DNN Platform/Library/UI/Skins/SkinControl.cs +++ b/DNN Platform/Library/UI/Skins/SkinControl.cs @@ -18,14 +18,14 @@ namespace DotNetNuke.UI.Skins public class SkinControl : UserControlBase { + protected DropDownList cboSkin; + protected CommandButton cmdPreview; private string _DefaultKey = "System"; private string _SkinRoot; private string _SkinSrc; private string _Width = string.Empty; private string _localResourceFile; private PortalInfo _objPortal; - protected DropDownList cboSkin; - protected CommandButton cmdPreview; protected RadioButton optHost; protected RadioButton optSite; @@ -111,41 +111,6 @@ public string LocalResourceFile } } - private void LoadSkins() - { - this.cboSkin.Items.Clear(); - - if (this.optHost.Checked) - { - // load host skins - foreach (KeyValuePair Skin in SkinController.GetSkins(this._objPortal, this.SkinRoot, SkinScope.Host)) - { - this.cboSkin.Items.Add(new ListItem(Skin.Key, Skin.Value)); - } - } - - if (this.optSite.Checked) - { - // load portal skins - foreach (KeyValuePair Skin in SkinController.GetSkins(this._objPortal, this.SkinRoot, SkinScope.Site)) - { - this.cboSkin.Items.Add(new ListItem(Skin.Key, Skin.Value)); - } - } - - this.cboSkin.Items.Insert(0, new ListItem("<" + Localization.GetString(this.DefaultKey, this.LocalResourceFile) + ">", string.Empty)); - - // 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.InvariantCultureIgnoreCase)) - { - this.cboSkin.Items[intIndex].Selected = true; - break; - } - } - } - /// /// The Page_Load server event handler on this page is used /// to populate the role information for the page. @@ -219,6 +184,41 @@ protected void optHost_CheckedChanged(object sender, EventArgs e) { this.LoadSkins(); } + + private void LoadSkins() + { + this.cboSkin.Items.Clear(); + + if (this.optHost.Checked) + { + // load host skins + foreach (KeyValuePair Skin in SkinController.GetSkins(this._objPortal, this.SkinRoot, SkinScope.Host)) + { + this.cboSkin.Items.Add(new ListItem(Skin.Key, Skin.Value)); + } + } + + if (this.optSite.Checked) + { + // load portal skins + foreach (KeyValuePair Skin in SkinController.GetSkins(this._objPortal, this.SkinRoot, SkinScope.Site)) + { + this.cboSkin.Items.Add(new ListItem(Skin.Key, Skin.Value)); + } + } + + this.cboSkin.Items.Insert(0, new ListItem("<" + Localization.GetString(this.DefaultKey, this.LocalResourceFile) + ">", string.Empty)); + + // 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.InvariantCultureIgnoreCase)) + { + this.cboSkin.Items[intIndex].Selected = true; + break; + } + } + } protected void optSite_CheckedChanged(object sender, EventArgs e) { diff --git a/DNN Platform/Library/UI/Skins/SkinController.cs b/DNN Platform/Library/UI/Skins/SkinController.cs index f4bd0db8140..70fb637fcd1 100644 --- a/DNN Platform/Library/UI/Skins/SkinController.cs +++ b/DNN Platform/Library/UI/Skins/SkinController.cs @@ -35,9 +35,9 @@ namespace DotNetNuke.UI.Skins /// ----------------------------------------------------------------------------- public class SkinController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinController)); private const string GlobalSkinPrefix = "[G]"; private const string PortalSystemSkinPrefix = "[S]"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinController)); private const string PortalSkinPrefix = "[L]"; private static readonly Regex GdirRegex = new Regex("\\[g]", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex SdirRegex = new Regex("\\[s]", RegexOptions.IgnoreCase | RegexOptions.Compiled); @@ -59,6 +59,17 @@ public static string RootContainer } } + public static int AddSkin(int skinPackageID, string skinSrc) + { + return DataProvider.Instance().AddSkin(skinPackageID, skinSrc); + } + + public static int AddSkinPackage(SkinPackageInfo skinPackage) + { + EventLogController.Instance.AddLog(skinPackage, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINPACKAGE_CREATED); + return DataProvider.Instance().AddSkinPackage(skinPackage.PackageID, skinPackage.PortalID, skinPackage.SkinName, skinPackage.SkinType, UserController.Instance.GetCurrentUserInfo().UserID); + } + private static void AddSkinFiles(List> skins, string skinRoot, string skinFolder, string skinPrefix) { foreach (string skinFile in Directory.GetFiles(skinFolder, "*.ascx")) @@ -114,17 +125,6 @@ private static void ProcessSkinsFolder(List> skins, } } } - - public static int AddSkin(int skinPackageID, string skinSrc) - { - return DataProvider.Instance().AddSkin(skinPackageID, skinSrc); - } - - public static int AddSkinPackage(SkinPackageInfo skinPackage) - { - EventLogController.Instance.AddLog(skinPackage, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINPACKAGE_CREATED); - return DataProvider.Instance().AddSkinPackage(skinPackage.PackageID, skinPackage.PortalID, skinPackage.SkinName, skinPackage.SkinType, UserController.Instance.GetCurrentUserInfo().UserID); - } public static bool CanDeleteSkin(string folderPath, string portalHomeDirMapPath) { @@ -301,34 +301,6 @@ public static List> GetSkins(PortalInfo portalInfo, return skins; } - /// ----------------------------------------------------------------------------- - /// - /// format skin name. - /// - /// - /// - /// The Folder Name. - /// The File Name without extension. - private static string FormatSkinName(string skinFolder, string skinFile) - { - if (skinFolder.Equals("_default", StringComparison.InvariantCultureIgnoreCase)) - { - // host folder - return skinFile; - } - - // portal folder - switch (skinFile.ToLowerInvariant()) - { - case "skin": - case "container": - case "default": - return skinFolder; - default: - return skinFolder + " - " + skinFile; - } - } - /// /// Determines if a given skin is defined as a global skin. /// @@ -401,6 +373,34 @@ public static void SetSkin(string skinRoot, int portalId, SkinType skinType, str } } + /// ----------------------------------------------------------------------------- + /// + /// format skin name. + /// + /// + /// + /// The Folder Name. + /// The File Name without extension. + private static string FormatSkinName(string skinFolder, string skinFile) + { + if (skinFolder.Equals("_default", StringComparison.InvariantCultureIgnoreCase)) + { + // host folder + return skinFile; + } + + // portal folder + switch (skinFile.ToLowerInvariant()) + { + case "skin": + case "container": + case "default": + return skinFolder; + default: + return skinFolder + " - " + skinFile; + } + } + public static void UpdateSkin(int skinID, string skinSrc) { DataProvider.Instance().UpdateSkin(skinID, skinSrc); diff --git a/DNN Platform/Library/UI/Skins/SkinDefaults.cs b/DNN Platform/Library/UI/Skins/SkinDefaults.cs index fb61217b6b9..1661610fe44 100644 --- a/DNN Platform/Library/UI/Skins/SkinDefaults.cs +++ b/DNN Platform/Library/UI/Skins/SkinDefaults.cs @@ -72,12 +72,6 @@ public string Folder } } - private static object GetSkinDefaultsCallback(CacheItemArgs cacheItemArgs) - { - var defaultType = (SkinDefaultType)cacheItemArgs.ParamList[0]; - return new SkinDefaults(defaultType); - } - public static SkinDefaults GetSkinDefaults(SkinDefaultType DefaultType) { return @@ -85,5 +79,11 @@ public static SkinDefaults GetSkinDefaults(SkinDefaultType DefaultType) new CacheItemArgs(string.Format(DataCache.SkinDefaultsCacheKey, DefaultType), DataCache.SkinDefaultsCacheTimeOut, DataCache.SkinDefaultsCachePriority, DefaultType), GetSkinDefaultsCallback); } + + private static object GetSkinDefaultsCallback(CacheItemArgs cacheItemArgs) + { + var defaultType = (SkinDefaultType)cacheItemArgs.ParamList[0]; + return new SkinDefaults(defaultType); + } } } diff --git a/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs b/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs index f7ace620474..3b69d0630b8 100644 --- a/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs +++ b/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs @@ -150,6 +150,22 @@ public SkinFileProcessor(string SkinPath, string SkinRoot, string SkinName) this.m_ObjectFactory = new ObjectParser(this.m_ControlList); } + public string SkinRoot + { + get + { + return this.m_SkinRoot; + } + } + + public string SkinPath + { + get + { + return this.m_SkinPath; + } + } + private PathParser PathFactory { get @@ -194,22 +210,6 @@ private string Message this.m_Message = value; } } - - public string SkinRoot - { - get - { - return this.m_SkinRoot; - } - } - - public string SkinPath - { - get - { - return this.m_SkinPath; - } - } public string SkinName { @@ -300,13 +300,13 @@ public string ProcessSkin(string SkinSource, XmlDocument SkinAttributes, SkinPar /// ----------------------------------------------------------------------------- private class ControlParser { + private static readonly Regex FindTokenInstance = + new Regex("\\[\\s*(?\\w*)\\s*:?\\s*(?\\w*)\\s*]", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private readonly Hashtable m_ControlList; private XmlDocument m_Attributes = new XmlDocument { XmlResolver = null }; private string m_ParseMessages = string.Empty; private ArrayList m_RegisterList = new ArrayList(); - - private static readonly Regex FindTokenInstance = - new Regex("\\[\\s*(?\\w*)\\s*:?\\s*(?\\w*)\\s*]", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// ----------------------------------------------------------------------------- /// @@ -576,16 +576,16 @@ private string TokenMatchHandler(Match m) /// ----------------------------------------------------------------------------- private class ObjectParser { - private readonly Hashtable m_ControlList; - private string m_ParseMessages = string.Empty; - private ArrayList m_RegisterList = new ArrayList(); - // define the regular expression to match objects private static readonly Regex FindObjectInstance = new Regex("\\.*?)
", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex MultiSpaceRegex = new Regex("\\s+", RegexOptions.Compiled); + private readonly Hashtable m_ControlList; + private string m_ParseMessages = string.Empty; + private ArrayList m_RegisterList = new ArrayList(); + /// ----------------------------------------------------------------------------- /// /// Initializes a new instance of the class. @@ -853,13 +853,6 @@ private string ObjectMatchHandler(Match m) /// ----------------------------------------------------------------------------- private class PathParser { - private readonly string SUBST = Util.GetLocalizedString("Substituting"); - private readonly string SUBST_DETAIL = Util.GetLocalizedString("Substituting.Detail"); - private readonly ArrayList m_CSSPatterns = new ArrayList(); - private readonly ArrayList m_HTMLPatterns = new ArrayList(); - private string m_Messages = string.Empty; - private string m_SkinPath = string.Empty; - private const RegexOptions PatternOptions = RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled; // retrieve the patterns @@ -877,6 +870,13 @@ private class PathParser new Regex("(?<(?:param\\s+name\\s*=\\s*\"(?:movie|src|base)\")[^>]*?\\svalue\\s*=\\s*\")(?!https://|http://|\\\\|[~/])(?[^\"]*)(?\"[^>]*>)", PatternOptions), new Regex("(?]*?\\s(?:src)\\s*=\\s*\")(?!https://|http://|\\\\|[~/])(?[^\"]*)(?\"[^>]*>)", PatternOptions), }; + + private readonly string SUBST = Util.GetLocalizedString("Substituting"); + private readonly string SUBST_DETAIL = Util.GetLocalizedString("Substituting.Detail"); + private readonly ArrayList m_CSSPatterns = new ArrayList(); + private readonly ArrayList m_HTMLPatterns = new ArrayList(); + private string m_Messages = string.Empty; + private string m_SkinPath = string.Empty; // retrieve the patterns private static readonly Regex[] CssArrayPattern = @@ -1064,6 +1064,11 @@ private string MatchHandler(Match m) /// ----------------------------------------------------------------------------- private class SkinFile { + 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 readonly string CONTROL_DIR = Util.GetLocalizedString("ControlDirective"); private readonly string CONTROL_REG = Util.GetLocalizedString("ControlRegister"); private readonly string FILE_FORMAT_ERROR = Util.GetLocalizedString("FileFormat.Error"); @@ -1078,11 +1083,6 @@ private class SkinFile private readonly string m_WriteFileName; private string FILE_FORMAT_DETAIL = Util.GetLocalizedString("FileFormat.Detail"); private string m_Messages = string.Empty; - - 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 const string StrPattern = "<\\s*body[^>]*>(?.*)<\\s*/\\s*body\\s*>"; private static readonly Regex BodyExtractionRegex = new Regex(StrPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); /// ----------------------------------------------------------------------------- @@ -1230,16 +1230,6 @@ public string SkinRootPath public string Contents { get; set; } - private string Read(string FileName) - { - using (var objStreamReader = new StreamReader(FileName)) - { - string strFileContents = objStreamReader.ReadToEnd(); - objStreamReader.Close(); - return strFileContents; - } - } - public void Write() { // delete the file before attempting to write @@ -1302,6 +1292,16 @@ public string PrependASCXDirectives(ArrayList Registrations) this.Contents = Prefix + this.Contents; return Messages; } + + private string Read(string FileName) + { + using (var objStreamReader = new StreamReader(FileName)) + { + string strFileContents = objStreamReader.ReadToEnd(); + objStreamReader.Close(); + return strFileContents; + } + } } } } diff --git a/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs b/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs index 6bf8134f65a..9d096cf05c8 100644 --- a/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs +++ b/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs @@ -111,6 +111,19 @@ public string SkinType this._SkinType = value; } } + + public int KeyID + { + get + { + return this.SkinPackageID; + } + + set + { + this.SkinPackageID = value; + } + } public void Fill(IDataReader dr) { @@ -134,18 +147,5 @@ public void Fill(IDataReader dr) } } } - - public int KeyID - { - get - { - return this.SkinPackageID; - } - - set - { - this.SkinPackageID = value; - } - } } } diff --git a/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs b/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs index 74681ebf242..21fb4c7b69d 100644 --- a/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs +++ b/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs @@ -25,9 +25,9 @@ namespace DotNetNuke.UI.Skins /// ----------------------------------------------------------------------------- public abstract class SkinThumbNailControl : UserControlBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinThumbNailControl)); protected HtmlGenericControl ControlContainer; protected RadioButtonList OptSkin; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinThumbNailControl)); public string Border { @@ -137,42 +137,37 @@ public string Width /// ----------------------------------------------------------------------------- /// - /// AddDefaultSkin adds the not-specified skin to the radio button list. + /// Clear clears the radio button list. /// /// /// /// ----------------------------------------------------------------------------- - private void AddDefaultSkin() + public void Clear() { - var strDefault = Localization.GetString("Not_Specified") + "
"; - strDefault += ""; - this.OptSkin.Items.Insert(0, new ListItem(strDefault, string.Empty)); + this.OptSkin.Items.Clear(); } /// ----------------------------------------------------------------------------- /// - /// AddSkin adds the skin to the radio button list. + /// LoadAllSkins loads all the available skins (Host and Site) to the radio button list. /// /// /// - /// Root Path. - /// The Skin Folder. - /// The Skin File. + /// Optionally include the "Not Specified" option. /// ----------------------------------------------------------------------------- - private void AddSkin(string root, string strFolder, string strFile) + public void LoadAllSkins(bool includeNotSpecified) { - var strImage = string.Empty; - if (File.Exists(strFile.Replace(".ascx", ".jpg"))) - { - strImage += ""; - } - else + // default value + if (includeNotSpecified) { - strImage += ""; + this.AddDefaultSkin(); } - - this.OptSkin.Items.Add(new ListItem(FormatSkinName(strFolder, Path.GetFileNameWithoutExtension(strFile)) + "
" + strImage, root + "/" + strFolder + "/" + Path.GetFileName(strFile))); + + // load host skins (includeNotSpecified = false as we have already added it) + this.LoadHostSkins(false); + + // load portal skins (includeNotSpecified = false as we have already added it) + this.LoadPortalSkins(false); } /// ----------------------------------------------------------------------------- @@ -286,37 +281,42 @@ private static string CreateThumbnail(string strImage) /// ----------------------------------------------------------------------------- /// - /// Clear clears the radio button list. + /// AddDefaultSkin adds the not-specified skin to the radio button list. /// /// /// /// ----------------------------------------------------------------------------- - public void Clear() + private void AddDefaultSkin() { - this.OptSkin.Items.Clear(); + var strDefault = Localization.GetString("Not_Specified") + "
"; + strDefault += ""; + this.OptSkin.Items.Insert(0, new ListItem(strDefault, string.Empty)); } /// ----------------------------------------------------------------------------- /// - /// LoadAllSkins loads all the available skins (Host and Site) to the radio button list. + /// AddSkin adds the skin to the radio button list. /// /// /// - /// Optionally include the "Not Specified" option. + /// Root Path. + /// The Skin Folder. + /// The Skin File. /// ----------------------------------------------------------------------------- - public void LoadAllSkins(bool includeNotSpecified) + private void AddSkin(string root, string strFolder, string strFile) { - // default value - if (includeNotSpecified) + var strImage = string.Empty; + if (File.Exists(strFile.Replace(".ascx", ".jpg"))) { - this.AddDefaultSkin(); + strImage += ""; } - - // load host skins (includeNotSpecified = false as we have already added it) - this.LoadHostSkins(false); - - // load portal skins (includeNotSpecified = false as we have already added it) - this.LoadPortalSkins(false); + else + { + 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 06cbe8ee438..26e38c7ce95 100644 --- a/DNN Platform/Library/UI/UIUtilities.cs +++ b/DNN Platform/Library/UI/UIUtilities.cs @@ -20,6 +20,52 @@ namespace DotNetNuke.UI public class UIUtilities { + public static ModuleInfo GetSlaveModule(int tabId) + { + var key = GetControlKey(); + var moduleId = GetModuleId(key); + + ModuleInfo slaveModule = GetSlaveModule(moduleId, key, tabId); + if (slaveModule != null) + { + var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID) ?? + ModuleControlController.GetModuleControlByControlKey(key, Null.NullInteger); + if (moduleControl != null) + { + slaveModule.ModuleControlId = moduleControl.ModuleControlID; + } + } + + return slaveModule; + } + + public static bool IsLegacyUI(int moduleId, string key, int portalId) + { + var request = HttpContext.Current.Request; + var isLegacyUi = true; + var settings = PortalController.Instance.GetCurrentPortalSettings(); + if (settings != null) + { + isLegacyUi = !(settings.EnablePopUps && !request.Browser.Crawler && request.Browser.EcmaScriptVersion >= new Version(1, 0)); + + if (!isLegacyUi && !string.IsNullOrEmpty(key)) + { + var slaveModule = GetSlaveModule(moduleId, key, settings.ActiveTab.TabID); + if (slaveModule != null) + { + var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID) ?? + ModuleControlController.GetModuleControlByControlKey(key, Null.NullInteger); + if (moduleControl != null) + { + isLegacyUi = !moduleControl.SupportsPopUps; + } + } + } + } + + return isLegacyUi; + } + internal static string GetControlKey() { HttpRequest request = HttpContext.Current.Request; @@ -107,52 +153,6 @@ internal static ModuleInfo GetSlaveModule(int moduleId, string key, int tabId) return slaveModule; } - public static ModuleInfo GetSlaveModule(int tabId) - { - var key = GetControlKey(); - var moduleId = GetModuleId(key); - - ModuleInfo slaveModule = GetSlaveModule(moduleId, key, tabId); - if (slaveModule != null) - { - var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID) ?? - ModuleControlController.GetModuleControlByControlKey(key, Null.NullInteger); - if (moduleControl != null) - { - slaveModule.ModuleControlId = moduleControl.ModuleControlID; - } - } - - return slaveModule; - } - - public static bool IsLegacyUI(int moduleId, string key, int portalId) - { - var request = HttpContext.Current.Request; - var isLegacyUi = true; - var settings = PortalController.Instance.GetCurrentPortalSettings(); - if (settings != null) - { - isLegacyUi = !(settings.EnablePopUps && !request.Browser.Crawler && request.Browser.EcmaScriptVersion >= new Version(1, 0)); - - if (!isLegacyUi && !string.IsNullOrEmpty(key)) - { - var slaveModule = GetSlaveModule(moduleId, key, settings.ActiveTab.TabID); - if (slaveModule != null) - { - var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID) ?? - ModuleControlController.GetModuleControlByControlKey(key, Null.NullInteger); - if (moduleControl != null) - { - isLegacyUi = !moduleControl.SupportsPopUps; - } - } - } - } - - return isLegacyUi; - } - public static bool IsLegacyUI(int portalId) { var key = GetControlKey(); diff --git a/DNN Platform/Library/UI/UserControls/Address.cs b/DNN Platform/Library/UI/UserControls/Address.cs index c33a0ff8c77..a154c898837 100644 --- a/DNN Platform/Library/UI/UserControls/Address.cs +++ b/DNN Platform/Library/UI/UserControls/Address.cs @@ -23,6 +23,8 @@ namespace DotNetNuke.UI.UserControls /// public abstract class Address : UserControlBase { + protected CountryListBox cboCountry; + protected DropDownList cboRegion; private const string MyFileName = "Address.ascx"; private string _cell; private string _city; @@ -47,8 +49,6 @@ public abstract class Address : UserControlBase private string _street; private string _telephone; private string _unit; - protected CountryListBox cboCountry; - protected DropDownList cboRegion; protected CheckBox chkCell; protected CheckBox chkCity; protected CheckBox chkCountry; @@ -391,6 +391,175 @@ public string LocalResourceFile } } + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cboCountry.SelectedIndexChanged += this.OnCountryIndexChanged; + this.chkCell.CheckedChanged += this.OnCellCheckChanged; + this.chkCity.CheckedChanged += this.OnCityCheckChanged; + this.chkCountry.CheckedChanged += this.OnCountryCheckChanged; + this.chkFax.CheckedChanged += this.OnFaxCheckChanged; + this.chkPostal.CheckedChanged += this.OnPostalCheckChanged; + this.chkRegion.CheckedChanged += this.OnRegionCheckChanged; + this.chkStreet.CheckedChanged += this.OnStreetCheckChanged; + this.chkTelephone.CheckedChanged += this.OnTelephoneCheckChanged; + + try + { + this.valStreet.ErrorMessage = Localization.GetString("StreetRequired", Localization.GetResourceFile(this, MyFileName)); + this.valCity.ErrorMessage = Localization.GetString("CityRequired", Localization.GetResourceFile(this, MyFileName)); + this.valCountry.ErrorMessage = Localization.GetString("CountryRequired", Localization.GetResourceFile(this, MyFileName)); + this.valPostal.ErrorMessage = Localization.GetString("PostalRequired", Localization.GetResourceFile(this, MyFileName)); + this.valTelephone.ErrorMessage = Localization.GetString("TelephoneRequired", Localization.GetResourceFile(this, MyFileName)); + this.valCell.ErrorMessage = Localization.GetString("CellRequired", Localization.GetResourceFile(this, MyFileName)); + this.valFax.ErrorMessage = Localization.GetString("FaxRequired", Localization.GetResourceFile(this, MyFileName)); + + if (!this.Page.IsPostBack) + { + this.txtStreet.TabIndex = Convert.ToInt16(this.StartTabIndex); + this.txtUnit.TabIndex = Convert.ToInt16(this.StartTabIndex + 1); + this.txtCity.TabIndex = Convert.ToInt16(this.StartTabIndex + 2); + this.cboCountry.TabIndex = Convert.ToInt16(this.StartTabIndex + 3); + this.cboRegion.TabIndex = Convert.ToInt16(this.StartTabIndex + 4); + this.txtRegion.TabIndex = Convert.ToInt16(this.StartTabIndex + 5); + this.txtPostal.TabIndex = Convert.ToInt16(this.StartTabIndex + 6); + this.txtTelephone.TabIndex = Convert.ToInt16(this.StartTabIndex + 7); + this.txtCell.TabIndex = Convert.ToInt16(this.StartTabIndex + 8); + this.txtFax.TabIndex = Convert.ToInt16(this.StartTabIndex + 9); + + // ", string.Empty)); + + switch (this._countryData.ToLowerInvariant()) + { + case "text": + if (string.IsNullOrEmpty(this._country)) + { + this.cboCountry.SelectedIndex = 0; + } + else + { + if (this.cboCountry.Items.FindByText(this._country) != null) + { + this.cboCountry.ClearSelection(); + this.cboCountry.Items.FindByText(this._country).Selected = true; + } + } + + break; + case "value": + if (this.cboCountry.Items.FindByValue(this._country) != null) + { + this.cboCountry.ClearSelection(); + this.cboCountry.Items.FindByValue(this._country).Selected = true; + } + + break; + } + + this.Localize(); + + if (this.cboRegion.Visible) + { + switch (this._regionData.ToLowerInvariant()) + { + case "text": + if (string.IsNullOrEmpty(this._region)) + { + this.cboRegion.SelectedIndex = 0; + } + else + { + if (this.cboRegion.Items.FindByText(this._region) != null) + { + this.cboRegion.Items.FindByText(this._region).Selected = true; + } + } + + break; + case "value": + if (this.cboRegion.Items.FindByValue(this._region) != null) + { + this.cboRegion.Items.FindByValue(this._region).Selected = true; + } + + break; + } + } + else + { + this.txtRegion.Text = this._region; + } + + this.txtStreet.Text = this._street; + this.txtUnit.Text = this._unit; + this.txtCity.Text = this._city; + this.txtPostal.Text = this._postal; + this.txtTelephone.Text = this._telephone; + this.txtCell.Text = this._cell; + this.txtFax.Text = this._fax; + + this.divStreet.Visible = this._showStreet; + this.divUnit.Visible = this._showUnit; + this.divCity.Visible = this._showCity; + this.divCountry.Visible = this._showCountry; + this.divRegion.Visible = this._showRegion; + this.divPostal.Visible = this._showPostal; + this.divTelephone.Visible = this._showTelephone; + this.divCell.Visible = this._showCell; + this.divFax.Visible = this._showFax; + + if (TabPermissionController.CanAdminPage()) + { + this.chkStreet.Visible = true; + this.chkCity.Visible = true; + this.chkCountry.Visible = true; + this.chkRegion.Visible = true; + this.chkPostal.Visible = true; + this.chkTelephone.Visible = true; + this.chkCell.Visible = true; + this.chkFax.Visible = true; + } + + this.ViewState["ModuleId"] = Convert.ToString(this._moduleId); + this.ViewState["LabelColumnWidth"] = this._labelColumnWidth; + this.ViewState["ControlColumnWidth"] = this._controlColumnWidth; + + this.ShowRequiredFields(); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnCountryIndexChanged(object sender, EventArgs e) + { + try + { + this.Localize(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + /// /// Localize correctly sets up the control for US/Canada/Other Countries. /// @@ -612,175 +781,6 @@ private void UpdateRequiredFields() this.ShowRequiredFields(); } - - /// - /// Page_Load runs when the control is loaded. - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cboCountry.SelectedIndexChanged += this.OnCountryIndexChanged; - this.chkCell.CheckedChanged += this.OnCellCheckChanged; - this.chkCity.CheckedChanged += this.OnCityCheckChanged; - this.chkCountry.CheckedChanged += this.OnCountryCheckChanged; - this.chkFax.CheckedChanged += this.OnFaxCheckChanged; - this.chkPostal.CheckedChanged += this.OnPostalCheckChanged; - this.chkRegion.CheckedChanged += this.OnRegionCheckChanged; - this.chkStreet.CheckedChanged += this.OnStreetCheckChanged; - this.chkTelephone.CheckedChanged += this.OnTelephoneCheckChanged; - - try - { - this.valStreet.ErrorMessage = Localization.GetString("StreetRequired", Localization.GetResourceFile(this, MyFileName)); - this.valCity.ErrorMessage = Localization.GetString("CityRequired", Localization.GetResourceFile(this, MyFileName)); - this.valCountry.ErrorMessage = Localization.GetString("CountryRequired", Localization.GetResourceFile(this, MyFileName)); - this.valPostal.ErrorMessage = Localization.GetString("PostalRequired", Localization.GetResourceFile(this, MyFileName)); - this.valTelephone.ErrorMessage = Localization.GetString("TelephoneRequired", Localization.GetResourceFile(this, MyFileName)); - this.valCell.ErrorMessage = Localization.GetString("CellRequired", Localization.GetResourceFile(this, MyFileName)); - this.valFax.ErrorMessage = Localization.GetString("FaxRequired", Localization.GetResourceFile(this, MyFileName)); - - if (!this.Page.IsPostBack) - { - this.txtStreet.TabIndex = Convert.ToInt16(this.StartTabIndex); - this.txtUnit.TabIndex = Convert.ToInt16(this.StartTabIndex + 1); - this.txtCity.TabIndex = Convert.ToInt16(this.StartTabIndex + 2); - this.cboCountry.TabIndex = Convert.ToInt16(this.StartTabIndex + 3); - this.cboRegion.TabIndex = Convert.ToInt16(this.StartTabIndex + 4); - this.txtRegion.TabIndex = Convert.ToInt16(this.StartTabIndex + 5); - this.txtPostal.TabIndex = Convert.ToInt16(this.StartTabIndex + 6); - this.txtTelephone.TabIndex = Convert.ToInt16(this.StartTabIndex + 7); - this.txtCell.TabIndex = Convert.ToInt16(this.StartTabIndex + 8); - this.txtFax.TabIndex = Convert.ToInt16(this.StartTabIndex + 9); - - // ", string.Empty)); - - switch (this._countryData.ToLowerInvariant()) - { - case "text": - if (string.IsNullOrEmpty(this._country)) - { - this.cboCountry.SelectedIndex = 0; - } - else - { - if (this.cboCountry.Items.FindByText(this._country) != null) - { - this.cboCountry.ClearSelection(); - this.cboCountry.Items.FindByText(this._country).Selected = true; - } - } - - break; - case "value": - if (this.cboCountry.Items.FindByValue(this._country) != null) - { - this.cboCountry.ClearSelection(); - this.cboCountry.Items.FindByValue(this._country).Selected = true; - } - - break; - } - - this.Localize(); - - if (this.cboRegion.Visible) - { - switch (this._regionData.ToLowerInvariant()) - { - case "text": - if (string.IsNullOrEmpty(this._region)) - { - this.cboRegion.SelectedIndex = 0; - } - else - { - if (this.cboRegion.Items.FindByText(this._region) != null) - { - this.cboRegion.Items.FindByText(this._region).Selected = true; - } - } - - break; - case "value": - if (this.cboRegion.Items.FindByValue(this._region) != null) - { - this.cboRegion.Items.FindByValue(this._region).Selected = true; - } - - break; - } - } - else - { - this.txtRegion.Text = this._region; - } - - this.txtStreet.Text = this._street; - this.txtUnit.Text = this._unit; - this.txtCity.Text = this._city; - this.txtPostal.Text = this._postal; - this.txtTelephone.Text = this._telephone; - this.txtCell.Text = this._cell; - this.txtFax.Text = this._fax; - - this.divStreet.Visible = this._showStreet; - this.divUnit.Visible = this._showUnit; - this.divCity.Visible = this._showCity; - this.divCountry.Visible = this._showCountry; - this.divRegion.Visible = this._showRegion; - this.divPostal.Visible = this._showPostal; - this.divTelephone.Visible = this._showTelephone; - this.divCell.Visible = this._showCell; - this.divFax.Visible = this._showFax; - - if (TabPermissionController.CanAdminPage()) - { - this.chkStreet.Visible = true; - this.chkCity.Visible = true; - this.chkCountry.Visible = true; - this.chkRegion.Visible = true; - this.chkPostal.Visible = true; - this.chkTelephone.Visible = true; - this.chkCell.Visible = true; - this.chkFax.Visible = true; - } - - this.ViewState["ModuleId"] = Convert.ToString(this._moduleId); - this.ViewState["LabelColumnWidth"] = this._labelColumnWidth; - this.ViewState["ControlColumnWidth"] = this._controlColumnWidth; - - this.ShowRequiredFields(); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnCountryIndexChanged(object sender, EventArgs e) - { - try - { - this.Localize(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } protected void OnCityCheckChanged(object sender, EventArgs e) { diff --git a/DNN Platform/Library/UI/UserControls/DualListControl.cs b/DNN Platform/Library/UI/UserControls/DualListControl.cs index e081695fa2d..c6d436d0fdc 100644 --- a/DNN Platform/Library/UI/UserControls/DualListControl.cs +++ b/DNN Platform/Library/UI/UserControls/DualListControl.cs @@ -15,6 +15,8 @@ public abstract class DualListControl : UserControlBase { protected Label Label1; protected Label Label2; + protected LinkButton cmdAdd; + protected LinkButton cmdAddAll; private string MyFileName = "DualListControl.ascx"; private ArrayList _Assigned; private ArrayList _Available; @@ -23,8 +25,6 @@ public abstract class DualListControl : UserControlBase private bool _Enabled = true; private string _ListBoxHeight = string.Empty; private string _ListBoxWidth = string.Empty; - protected LinkButton cmdAdd; - protected LinkButton cmdAddAll; protected LinkButton cmdRemove; protected LinkButton cmdRemoveAll; protected ListBox lstAssigned; diff --git a/DNN Platform/Library/UI/UserControls/Help.cs b/DNN Platform/Library/UI/UserControls/Help.cs index 971f4045978..b064e5f783a 100644 --- a/DNN Platform/Library/UI/UserControls/Help.cs +++ b/DNN Platform/Library/UI/UserControls/Help.cs @@ -20,10 +20,10 @@ namespace DotNetNuke.UI.UserControls public abstract class Help : PortalModuleBase { - private string MyFileName = "Help.ascx"; - private string _key; protected LinkButton cmdCancel; protected HyperLink cmdHelp; + private string MyFileName = "Help.ascx"; + private string _key; protected Literal helpFrame; protected Label lblHelp; protected Label lblInfo; diff --git a/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs b/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs index d8424550d1e..742b14685c0 100644 --- a/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs +++ b/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs @@ -24,10 +24,10 @@ namespace DotNetNuke.UI.UserControls /// ----------------------------------------------------------------------------- public abstract class HelpButtonControl : UserControl { - private string _HelpKey; - private string _ResourceKey; protected LinkButton cmdHelp; protected Image imgHelp; + private string _HelpKey; + private string _ResourceKey; protected Label lblHelp; protected Panel pnlHelp; diff --git a/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs b/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs index 7bcbefb5227..674370275f5 100644 --- a/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs +++ b/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs @@ -23,6 +23,14 @@ public abstract class LocaleSelectorControl : UserControlBase protected RadioButtonList rbViewType; private string MyFileName = "LocaleSelectorControl.ascx"; private string _ViewType = string.Empty; + + public string CultureCode + { + get + { + return this.ddlPortalDefaultLanguage.SelectedValue; + } + } private CultureDropDownTypes DisplayType { @@ -66,14 +74,6 @@ public void BindDefaultLanguageSelector() } } - public string CultureCode - { - get - { - return this.ddlPortalDefaultLanguage.SelectedValue; - } - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); diff --git a/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs b/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs index b4f77ecd9f7..43d5e4f2808 100644 --- a/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs +++ b/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs @@ -18,13 +18,25 @@ namespace DotNetNuke.UI.UserControls public abstract class ModuleAuditControl : UserControl { - private const string MyFileName = "ModuleAuditControl.ascx"; - private string _systemUser; protected Label lblCreatedBy; protected Label lblUpdatedBy; + private const string MyFileName = "ModuleAuditControl.ascx"; + private string _systemUser; private static readonly Regex CheckDateColumnRegex = new Regex(@"^-?\d+$", RegexOptions.Compiled); + public ModuleAuditControl() + { + this.LastModifiedDate = string.Empty; + this.LastModifiedByUser = string.Empty; + this.CreatedByUser = string.Empty; + this.CreatedDate = string.Empty; + } + + public string CreatedDate { private get; set; } + + public string CreatedByUser { private get; set; } + private string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); [Serializable] @@ -39,18 +51,6 @@ private class EntityInfo public DateTime LastModifiedOnDate { get; set; } } - public ModuleAuditControl() - { - this.LastModifiedDate = string.Empty; - this.LastModifiedByUser = string.Empty; - this.CreatedByUser = string.Empty; - this.CreatedDate = string.Empty; - } - - public string CreatedDate { private get; set; } - - public string CreatedByUser { private get; set; } - public string LastModifiedByUser { private get; set; } public string LastModifiedDate { private get; set; } diff --git a/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs b/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs index 09dd5ffbb1b..6f9c27f9c85 100644 --- a/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs +++ b/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs @@ -23,13 +23,13 @@ namespace DotNetNuke.UI.UserControls /// ----------------------------------------------------------------------------- public class SectionHeadControl : UserControl { + protected ImageButton imgIcon; + protected Label lblTitle; private bool _includeRule; private bool _isExpanded = true; private string _javaScript = "__dnn_SectionMaxMin"; private string _maxImageUrl = "images/plus.gif"; private string _minImageUrl = "images/minus.gif"; - protected ImageButton imgIcon; - protected Label lblTitle; protected Panel pnlRule; /// ----------------------------------------------------------------------------- @@ -161,28 +161,28 @@ public string MinImageUrl { this._minImageUrl = value; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the ResourceKey is the key used to identify the Localization Resource for the - /// title text. - /// - /// A string representing the ResourceKey. - /// - /// - /// ----------------------------------------------------------------------------- - public string ResourceKey { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Section is the Id of the DHTML object that contains the xection content - /// title text. - /// - /// A string representing the Section. - /// - /// - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the ResourceKey is the key used to identify the Localization Resource for the + /// title text. + /// + /// A string representing the ResourceKey. + /// + /// + /// ----------------------------------------------------------------------------- + public string ResourceKey { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Section is the Id of the DHTML object that contains the xection content + /// title text. + /// + /// A string representing the Section. + /// + /// + /// ----------------------------------------------------------------------------- public string Section { get; set; } /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/UI/UserControls/TextEditor.cs b/DNN Platform/Library/UI/UserControls/TextEditor.cs index 8bf37814498..2feafb07e49 100644 --- a/DNN Platform/Library/UI/UserControls/TextEditor.cs +++ b/DNN Platform/Library/UI/UserControls/TextEditor.cs @@ -31,10 +31,10 @@ namespace DotNetNuke.UI.UserControls [ValidationPropertyAttribute("Text")] public class TextEditor : UserControl { - private const string MyFileName = "TextEditor.ascx"; - private HtmlEditorProvider _richTextEditor; protected Panel PanelTextEditor; protected RadioButtonList OptRender; + private const string MyFileName = "TextEditor.ascx"; + private HtmlEditorProvider _richTextEditor; protected RadioButtonList OptView; protected PlaceHolder PlcEditor; protected HtmlGenericControl DivBasicTextBox; @@ -159,13 +159,13 @@ public string Text switch (this.OptRender.SelectedItem.Value) { case "T": - return this.Encode(HtmlUtils.ConvertToHtml(RemoveBaseTags(this.TxtDesktopHTML.Text))); + return this.Encode(HtmlUtils.ConvertToHtml(RemoveBaseTags(this.TxtDesktopHTML.Text))); - // break; + // break; case "R": - return RemoveBaseTags(this.TxtDesktopHTML.Text); + return RemoveBaseTags(this.TxtDesktopHTML.Text); - // break; + // break; default: return this.Encode(RemoveBaseTags(this.TxtDesktopHTML.Text)); @@ -252,6 +252,23 @@ public string LocalResourceFile } } + public void ChangeMode(string mode) + { + this.OptView.SelectedItem.Value = mode; + this.OptViewSelectedIndexChanged(this.OptView, EventArgs.Empty); + } + + public void ChangeTextRenderMode(string textRenderMode) + { + this.OptRender.SelectedItem.Value = textRenderMode; + this.OptRenderSelectedIndexChanged(this.OptRender, EventArgs.Empty); + } + + private static string RemoveBaseTags(string strInput) + { + return Globals.BaseTagRegex.Replace(strInput, " "); + } + /// ----------------------------------------------------------------------------- /// /// Decodes the html. @@ -357,23 +374,6 @@ private void SetPanels() this.PanelView.CssClass = "dnnTextPanelView"; } } - - private static string RemoveBaseTags(string strInput) - { - return Globals.BaseTagRegex.Replace(strInput, " "); - } - - public void ChangeMode(string mode) - { - this.OptView.SelectedItem.Value = mode; - this.OptViewSelectedIndexChanged(this.OptView, EventArgs.Empty); - } - - public void ChangeTextRenderMode(string textRenderMode) - { - this.OptRender.SelectedItem.Value = textRenderMode; - this.OptRenderSelectedIndexChanged(this.OptRender, EventArgs.Empty); - } protected override void OnInit(EventArgs e) { diff --git a/DNN Platform/Library/UI/UserControls/URLControl.cs b/DNN Platform/Library/UI/UserControls/URLControl.cs index cbf24df6bd1..d7b7194f64d 100644 --- a/DNN Platform/Library/UI/UserControls/URLControl.cs +++ b/DNN Platform/Library/UI/UserControls/URLControl.cs @@ -36,6 +36,8 @@ public abstract class UrlControl : UserControlBase protected Panel TypeRow; protected Panel URLRow; protected Panel UserRow; + protected DropDownList cboFiles; + protected DropDownList cboFolders; private bool _doChangeURL; private bool _doReloadFiles; private bool _doReloadFolders; @@ -43,8 +45,6 @@ public abstract class UrlControl : UserControlBase private bool _doRenderTypes; private string _localResourceFile; private PortalInfo _objPortal; - protected DropDownList cboFiles; - protected DropDownList cboFolders; protected DropDownList cboImages; protected DropDownList cboTabs; protected DropDownList cboUrls; @@ -586,6 +586,65 @@ public string Width } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + AJAX.RegisterPostBackControl(this.FindControl("cmdSave")); + + // prevent unauthorized access + if (this.Request.IsAuthenticated == false) + { + this.Visible = false; + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cboFolders.SelectedIndexChanged += this.cboFolders_SelectedIndexChanged; + this.optType.SelectedIndexChanged += this.optType_SelectedIndexChanged; + this.cmdAdd.Click += this.cmdAdd_Click; + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdDelete.Click += this.cmdDelete_Click; + this.cmdSave.Click += this.cmdSave_Click; + this.cmdSelect.Click += this.cmdSelect_Click; + this.cmdUpload.Click += this.cmdUpload_Click; + + this.ErrorRow.Visible = false; + + try + { + 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"])); + } + else + { + this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); + } + + if (this.ViewState["IsUrlControlLoaded"] == null) + { + // If Not Page.IsPostBack Then + // let's make at least an initialization + // The type radio button must be initialized + // The url must be initialized no matter its value + this._doRenderTypes = true; + this._doChangeURL = true; + ClientAPI.AddButtonConfirm(this.cmdDelete, Localization.GetString("DeleteItem")); + + // The following line was mover to the pre-render event to ensure render for the first time + // ViewState("IsUrlControlLoaded") = "Loaded" + } + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private ArrayList GetFileList(bool NoneSpecified) { int PortalId = Null.NullInteger; @@ -1164,65 +1223,6 @@ private void DoRenderTypeControls() } } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - AJAX.RegisterPostBackControl(this.FindControl("cmdSave")); - - // prevent unauthorized access - if (this.Request.IsAuthenticated == false) - { - this.Visible = false; - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cboFolders.SelectedIndexChanged += this.cboFolders_SelectedIndexChanged; - this.optType.SelectedIndexChanged += this.optType_SelectedIndexChanged; - this.cmdAdd.Click += this.cmdAdd_Click; - this.cmdCancel.Click += this.cmdCancel_Click; - this.cmdDelete.Click += this.cmdDelete_Click; - this.cmdSave.Click += this.cmdSave_Click; - this.cmdSelect.Click += this.cmdSelect_Click; - this.cmdUpload.Click += this.cmdUpload_Click; - - this.ErrorRow.Visible = false; - - try - { - 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"])); - } - else - { - this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); - } - - if (this.ViewState["IsUrlControlLoaded"] == null) - { - // If Not Page.IsPostBack Then - // let's make at least an initialization - // The type radio button must be initialized - // The url must be initialized no matter its value - this._doRenderTypes = true; - this._doChangeURL = true; - ClientAPI.AddButtonConfirm(this.cmdDelete, Localization.GetString("DeleteItem")); - - // The following line was mover to the pre-render event to ensure render for the first time - // ViewState("IsUrlControlLoaded") = "Loaded" - } - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); diff --git a/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs b/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs index 0c420471334..eef23c59cfe 100644 --- a/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs +++ b/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs @@ -26,13 +26,13 @@ public abstract class URLTrackingControl : UserControlBase protected Label Label5; protected Label Label6; protected Label Label7; + protected LinkButton cmdDisplay; + protected HyperLink cmdEndCalendar; private string _FormattedURL = string.Empty; private int _ModuleID = -2; private string _TrackingURL = string.Empty; private string _URL = string.Empty; private string _localResourceFile; - protected LinkButton cmdDisplay; - protected HyperLink cmdEndCalendar; protected HyperLink cmdStartCalendar; protected DataGrid grdLog; protected Label lblClicks; diff --git a/DNN Platform/Library/UI/UserControls/User.cs b/DNN Platform/Library/UI/UserControls/User.cs index 6ee6eb44299..66889046f13 100644 --- a/DNN Platform/Library/UI/UserControls/User.cs +++ b/DNN Platform/Library/UI/UserControls/User.cs @@ -21,8 +21,10 @@ namespace DotNetNuke.UI.UserControls public abstract class User : UserControlBase { protected HtmlTableRow ConfirmPasswordRow; - private string MyFileName = "User.ascx"; protected HtmlTableRow PasswordRow; + protected Label lblUsername; + protected Label lblUsernameAsterisk; + private string MyFileName = "User.ascx"; private string _Confirm; private string _ControlColumnWidth = string.Empty; private string _Email; @@ -36,8 +38,6 @@ public abstract class User : UserControlBase private int _StartTabIndex = 1; private string _UserName; private string _Website; - protected Label lblUsername; - protected Label lblUsernameAsterisk; protected LabelControl plConfirm; protected LabelControl plEmail; protected LabelControl plFirstName; diff --git a/DNN Platform/Library/UI/Utilities/ClientAPI.cs b/DNN Platform/Library/UI/Utilities/ClientAPI.cs index 208afd8f000..6b6a9022de3 100644 --- a/DNN Platform/Library/UI/Utilities/ClientAPI.cs +++ b/DNN Platform/Library/UI/Utilities/ClientAPI.cs @@ -28,6 +28,8 @@ namespace DotNetNuke.UI.Utilities /// public class DNNClientAPI { + private static readonly Hashtable m_objEnabledClientPersonalizationKeys = new Hashtable(); + public enum MinMaxPersistanceType { None, @@ -42,8 +44,6 @@ public enum PageCallBackType SetPersonalization = 1, } - private static readonly Hashtable m_objEnabledClientPersonalizationKeys = new Hashtable(); - /// ----------------------------------------------------------------------------- /// /// Adds client side body.onload event handler. @@ -84,12 +84,6 @@ public static void InitFileManager(Page objPage) AddBodyOnLoad(objPage, "initFileManager", "initFileManager();"); } - private static void AddBodyOnLoad(Page objPage, string scriptKey, string strJSFunction) - { - JavaScript.RegisterClientReference(objPage, ClientAPI.ClientNamespaceReferences.dnn); - objPage.ClientScript.RegisterStartupScript(objPage.GetType(), scriptKey, strJSFunction, true); - } - /// ----------------------------------------------------------------------------- /// /// Allows any module to have drag and drop functionality enabled. @@ -145,6 +139,12 @@ public static void EnableMinMax(Control objButton, Control objContent, bool blnD EnableMinMax(objButton, objContent, -1, blnDefaultMin, string.Empty, string.Empty, ePersistanceType); } + private static void AddBodyOnLoad(Page objPage, string scriptKey, string strJSFunction) + { + JavaScript.RegisterClientReference(objPage, ClientAPI.ClientNamespaceReferences.dnn); + objPage.ClientScript.RegisterStartupScript(objPage.GetType(), scriptKey, strJSFunction, true); + } + public static void EnableMinMax(Control objButton, Control objContent, int intModuleId, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) { EnableMinMax(objButton, objContent, intModuleId, blnDefaultMin, string.Empty, string.Empty, ePersistanceType); @@ -290,6 +290,16 @@ public static void EnableMinMax(Control objButton, Control objContent, int intMo } } + public static bool MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) + { + return MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType); + } + + public static void MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType, bool value) + { + MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType, value); + } + private static void SetMinMaxProperties(Control objButton, string strImage, string strToolTip, string strAltText) { if (objButton is LinkButton) @@ -335,16 +345,6 @@ private static void SetImageProperties(Control objControl, string strImage, stri } } - public static bool MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) - { - return MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType); - } - - public static void MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType, bool value) - { - MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType, value); - } - public static bool MinMaxContentVisibile(Control objButton, int intModuleId, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) { if (HttpContext.Current != null) @@ -423,6 +423,39 @@ public static void MinMaxContentVisibile(Control objButton, int intModuleId, boo } } + // enables callbacks for request, and registers personalization key to be accessible from client + // returns true when browser is capable of callbacks + public static bool EnableClientPersonalization(string strNamingContainer, string strKey, Page objPage) + { + if (ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.XMLHTTP)) + { + // Instead of sending the callback js function down to the client, we are hardcoding + // it on the client. DNN owns the interface, so there is no worry about an outside + // entity changing it on us. We are simply calling this here to register all the appropriate + // js libraries + ClientAPI.GetCallbackEventReference(objPage, string.Empty, string.Empty, string.Empty, string.Empty); + + // in order to limit the keys that can be accessed and written we are storing the enabled keys + // in this shared hash table + lock (m_objEnabledClientPersonalizationKeys.SyncRoot) + { + if (IsPersonalizationKeyRegistered(strNamingContainer + ClientAPI.CUSTOM_COLUMN_DELIMITER + strKey) == false) + { + m_objEnabledClientPersonalizationKeys.Add(strNamingContainer + ClientAPI.CUSTOM_COLUMN_DELIMITER + strKey, string.Empty); + } + } + + return true; + } + + return false; + } + + public static bool IsPersonalizationKeyRegistered(string strKey) + { + return m_objEnabledClientPersonalizationKeys.ContainsKey(strKey); + } + private static void AddAttribute(Control objControl, string strName, string strValue) { if (objControl is HtmlControl) @@ -460,38 +493,5 @@ private static void AddStyleAttribute(Control objControl, string strName, string } } } - - // enables callbacks for request, and registers personalization key to be accessible from client - // returns true when browser is capable of callbacks - public static bool EnableClientPersonalization(string strNamingContainer, string strKey, Page objPage) - { - if (ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.XMLHTTP)) - { - // Instead of sending the callback js function down to the client, we are hardcoding - // it on the client. DNN owns the interface, so there is no worry about an outside - // entity changing it on us. We are simply calling this here to register all the appropriate - // js libraries - ClientAPI.GetCallbackEventReference(objPage, string.Empty, string.Empty, string.Empty, string.Empty); - - // in order to limit the keys that can be accessed and written we are storing the enabled keys - // in this shared hash table - lock (m_objEnabledClientPersonalizationKeys.SyncRoot) - { - if (IsPersonalizationKeyRegistered(strNamingContainer + ClientAPI.CUSTOM_COLUMN_DELIMITER + strKey) == false) - { - m_objEnabledClientPersonalizationKeys.Add(strNamingContainer + ClientAPI.CUSTOM_COLUMN_DELIMITER + strKey, string.Empty); - } - } - - return true; - } - - return false; - } - - public static bool IsPersonalizationKeyRegistered(string strKey) - { - return m_objEnabledClientPersonalizationKeys.ContainsKey(strKey); - } } } diff --git a/DNN Platform/Library/UI/WebControls/ActionLink.cs b/DNN Platform/Library/UI/WebControls/ActionLink.cs index 1929ac740ab..b1827743eda 100644 --- a/DNN Platform/Library/UI/WebControls/ActionLink.cs +++ b/DNN Platform/Library/UI/WebControls/ActionLink.cs @@ -48,20 +48,6 @@ public ActionLink() public IModuleControl ModuleControl { get; set; } - private bool IsVisible(SecurityAccessLevel security) - { - bool isVisible = false; - if (ModulePermissionController.HasModuleAccess(security, Null.NullString, this.ModuleControl.ModuleContext.Configuration)) - { - if ((this.RequireEditMode != true || this.ModuleControl.ModuleContext.PortalSettings.UserMode == PortalSettings.Mode.Edit) || (security == SecurityAccessLevel.Anonymous || security == SecurityAccessLevel.View)) - { - isVisible = true; - } - } - - return isVisible; - } - /// ----------------------------------------------------------------------------- /// /// CreateChildControls builds the control tree. @@ -102,5 +88,19 @@ protected override void OnPreRender(EventArgs e) this.Visible = false; } } + + private bool IsVisible(SecurityAccessLevel security) + { + bool isVisible = false; + if (ModulePermissionController.HasModuleAccess(security, Null.NullString, this.ModuleControl.ModuleContext.Configuration)) + { + if ((this.RequireEditMode != true || this.ModuleControl.ModuleContext.PortalSettings.UserMode == PortalSettings.Mode.Edit) || (security == SecurityAccessLevel.Anonymous || security == SecurityAccessLevel.View)) + { + isVisible = true; + } + } + + return isVisible; + } } } diff --git a/DNN Platform/Library/UI/WebControls/CaptchaControl.cs b/DNN Platform/Library/UI/WebControls/CaptchaControl.cs index 3912fef66b9..e3cc6b5bca2 100644 --- a/DNN Platform/Library/UI/WebControls/CaptchaControl.cs +++ b/DNN Platform/Library/UI/WebControls/CaptchaControl.cs @@ -35,12 +35,12 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:CaptchaControl Runat=\"server\" CaptchaHeight=\"100px\" CaptchaWidth=\"300px\" />")] public class CaptchaControl : WebControl, INamingContainer, IPostBackDataHandler { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CaptchaControl)); + internal const string KEY = "captcha"; private const int EXPIRATION_DEFAULT = 120; private const int LENGTH_DEFAULT = 6; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CaptchaControl)); private const string RENDERURL_DEFAULT = "ImageChallenge.captcha.aspx"; private const string CHARS_DEFAULT = "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; - internal const string KEY = "captcha"; private static readonly string[] _FontFamilies = { "Arial", "Comic Sans MS", "Courier New", "Georgia", "Lucida Console", "MS Sans Serif", "Tahoma", "Times New Roman", "Trebuchet MS", "Verdana" }; private static readonly Random _Rand = new Random(); @@ -67,13 +67,7 @@ public CaptchaControl() this._Expiration = HostController.Instance.GetInteger("EXPIRATION_DEFAULT", EXPIRATION_DEFAULT); } - private bool IsDesignMode - { - get - { - return HttpContext.Current == null; - } - } + public event ServerValidateEventHandler UserValidated; /// /// Gets or sets and sets the BackGroundColor. @@ -110,6 +104,14 @@ public string BackGroundImage this._BackGroundImage = value; } } + + private bool IsDesignMode + { + get + { + return HttpContext.Current == null; + } + } /// /// Gets or sets and sets the list of characters. @@ -330,36 +332,128 @@ public void RaisePostDataChangedEvent() { } - public event ServerValidateEventHandler UserValidated; + /// + /// Validates the posted back data. + /// + /// The user entered data. + /// + public bool Validate(string userData) + { + var cacheKey = string.Format(DataCache.CaptchaCacheKey, userData); + var cacheObj = DataCache.GetCache(cacheKey); + + if (cacheObj == null) + { + this._IsValid = false; + } + else + { + this._IsValid = true; + DataCache.RemoveCache(cacheKey); + } + + this.OnUserValidated(new ServerValidateEventArgs(this._CaptchaText, this._IsValid)); + return this._IsValid; + } + + /// ----------------------------------------------------------------------------- + /// + /// GenerateImage generates the Captch Image. + /// + /// The Encrypted Text to display. + /// + /// ----------------------------------------------------------------------------- + internal static Bitmap GenerateImage(string encryptedText) + { + string encodedText = Decrypt(encryptedText); + Bitmap bmp = null; + string[] Settings = Regex.Split(encodedText, _Separator); + try + { + int width; + int height; + if (int.TryParse(Settings[0], out width) && int.TryParse(Settings[1], out height)) + { + string text = Settings[2]; + string backgroundImage = Settings[3]; + + Graphics g; + Brush b = new SolidBrush(Color.LightGray); + Brush b1 = new SolidBrush(Color.Black); + if (string.IsNullOrEmpty(backgroundImage)) + { + bmp = CreateImage(width, height); + } + else + { + bmp = (Bitmap)System.Drawing.Image.FromFile(HttpContext.Current.Request.MapPath(backgroundImage)); + } + + g = Graphics.FromImage(bmp); + + // Create Text + GraphicsPath textPath = CreateText(text, width, height, g); + if (string.IsNullOrEmpty(backgroundImage)) + { + g.FillPath(b, textPath); + } + else + { + g.FillPath(b1, textPath); + } + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + + return bmp; + } /// - /// Builds the url for the Handler. + /// Creates the child controls. /// - private string GetUrl() + protected override void CreateChildControls() { - var url = this.ResolveUrl(this.RenderUrl); - url += "?" + KEY + "=" + Encrypt(this.EncodeTicket(), DateTime.Now.AddSeconds(this.Expiration)); + base.CreateChildControls(); - // Append the Alias to the url so that it doesn't lose track of the alias it's currently on - var _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - url += "&alias=" + _portalSettings.PortalAlias.HTTPAlias; - return url; + if (this.CaptchaWidth.IsEmpty || this.CaptchaWidth.Type != UnitType.Pixel || this.CaptchaHeight.IsEmpty || this.CaptchaHeight.Type != UnitType.Pixel) + { + throw new InvalidOperationException("Must specify size of control in pixels."); + } + + this._image = new Image { BorderColor = this.BorderColor, BorderStyle = this.BorderStyle, BorderWidth = this.BorderWidth, ToolTip = this.ToolTip, EnableViewState = false }; + this.Controls.Add(this._image); } /// - /// Encodes the querystring to pass to the Handler. - /// - private string EncodeTicket() + /// Gets the next Captcha. + /// + /// + protected virtual string GetNextCaptcha() { var sb = new StringBuilder(); + var rand = new Random(); + int n; + var intMaxLength = this.CaptchaChars.Length; - sb.Append(this.CaptchaWidth.Value.ToString()); - sb.Append(_Separator + this.CaptchaHeight.Value); - sb.Append(_Separator + this._CaptchaText); - sb.Append(_Separator + this.BackGroundImage); + for (n = 0; n <= this.CaptchaLength - 1; n++) + { + sb.Append(this.CaptchaChars.Substring(rand.Next(intMaxLength), 1)); + } + + var challenge = sb.ToString(); - return sb.ToString(); - } + // NOTE: this could be a problem in a web farm using in-memory caching where + // 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); + DataCache.SetCache(cacheKey, challenge, (DNNCacheDependency)null, DateTime.Now.AddSeconds(this._Expiration + 1), + Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null); + return challenge; + } /// /// Creates the Image. @@ -446,6 +540,35 @@ private static GraphicsPath CreateText(string text, int width, int height, Graph return textPath; } + + /// + /// Builds the url for the Handler. + /// + private string GetUrl() + { + var url = this.ResolveUrl(this.RenderUrl); + url += "?" + KEY + "=" + Encrypt(this.EncodeTicket(), DateTime.Now.AddSeconds(this.Expiration)); + + // Append the Alias to the url so that it doesn't lose track of the alias it's currently on + var _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + url += "&alias=" + _portalSettings.PortalAlias.HTTPAlias; + return url; + } + + /// + /// Encodes the querystring to pass to the Handler. + /// + private string EncodeTicket() + { + var sb = new StringBuilder(); + + sb.Append(this.CaptchaWidth.Value.ToString()); + sb.Append(_Separator + this.CaptchaHeight.Value); + sb.Append(_Separator + this._CaptchaText); + sb.Append(_Separator + this.BackGroundImage); + + return sb.ToString(); + } /// ----------------------------------------------------------------------------- /// @@ -519,61 +642,6 @@ private static string Encrypt(string content, DateTime expiration) return FormsAuthentication.Encrypt(ticket); } - /// ----------------------------------------------------------------------------- - /// - /// GenerateImage generates the Captch Image. - /// - /// The Encrypted Text to display. - /// - /// ----------------------------------------------------------------------------- - internal static Bitmap GenerateImage(string encryptedText) - { - string encodedText = Decrypt(encryptedText); - Bitmap bmp = null; - string[] Settings = Regex.Split(encodedText, _Separator); - try - { - int width; - int height; - if (int.TryParse(Settings[0], out width) && int.TryParse(Settings[1], out height)) - { - string text = Settings[2]; - string backgroundImage = Settings[3]; - - Graphics g; - Brush b = new SolidBrush(Color.LightGray); - Brush b1 = new SolidBrush(Color.Black); - if (string.IsNullOrEmpty(backgroundImage)) - { - bmp = CreateImage(width, height); - } - else - { - bmp = (Bitmap)System.Drawing.Image.FromFile(HttpContext.Current.Request.MapPath(backgroundImage)); - } - - g = Graphics.FromImage(bmp); - - // Create Text - GraphicsPath textPath = CreateText(text, width, height, g); - if (string.IsNullOrEmpty(backgroundImage)) - { - g.FillPath(b, textPath); - } - else - { - g.FillPath(b1, textPath); - } - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - - return bmp; - } - /// ----------------------------------------------------------------------------- /// /// GetFont gets a random font to use for the Captcha Text. @@ -640,50 +708,6 @@ private static void WarpText(ref GraphicsPath textPath, Rectangle rect) m.Translate(0, 0); textPath.Warp(points, rectF, m, WarpMode.Perspective, 0); } - - /// - /// Creates the child controls. - /// - protected override void CreateChildControls() - { - base.CreateChildControls(); - - if (this.CaptchaWidth.IsEmpty || this.CaptchaWidth.Type != UnitType.Pixel || this.CaptchaHeight.IsEmpty || this.CaptchaHeight.Type != UnitType.Pixel) - { - throw new InvalidOperationException("Must specify size of control in pixels."); - } - - this._image = new Image { BorderColor = this.BorderColor, BorderStyle = this.BorderStyle, BorderWidth = this.BorderWidth, ToolTip = this.ToolTip, EnableViewState = false }; - this.Controls.Add(this._image); - } - - /// - /// Gets the next Captcha. - /// - /// - protected virtual string GetNextCaptcha() - { - var sb = new StringBuilder(); - var rand = new Random(); - int n; - var intMaxLength = this.CaptchaChars.Length; - - for (n = 0; n <= this.CaptchaLength - 1; n++) - { - sb.Append(this.CaptchaChars.Substring(rand.Next(intMaxLength), 1)); - } - - var challenge = sb.ToString(); - - // NOTE: this could be a problem in a web farm using in-memory caching where - // 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); - DataCache.SetCache(cacheKey, challenge, (DNNCacheDependency)null, DateTime.Now.AddSeconds(this._Expiration + 1), - Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null); - return challenge; - } /// /// Loads the previously saved Viewstate. @@ -836,29 +860,5 @@ protected override object SaveViewState() return allStates; } - - /// - /// Validates the posted back data. - /// - /// The user entered data. - /// - public bool Validate(string userData) - { - var cacheKey = string.Format(DataCache.CaptchaCacheKey, userData); - var cacheObj = DataCache.GetCache(cacheKey); - - if (cacheObj == null) - { - this._IsValid = false; - } - else - { - this._IsValid = true; - DataCache.RemoveCache(cacheKey); - } - - this.OnUserValidated(new ServerValidateEventArgs(this._CaptchaText, this._IsValid)); - return this._IsValid; - } } } diff --git a/DNN Platform/Library/UI/WebControls/CommandButton.cs b/DNN Platform/Library/UI/WebControls/CommandButton.cs index 75d4d6b09ec..72f7f951b65 100644 --- a/DNN Platform/Library/UI/WebControls/CommandButton.cs +++ b/DNN Platform/Library/UI/WebControls/CommandButton.cs @@ -28,6 +28,10 @@ public class CommandButton : WebControl, INamingContainer private LinkButton link; private LiteralControl separator; + public event EventHandler Click; + + public event CommandEventHandler Command; + /// ----------------------------------------------------------------------------- /// /// Gets or sets the Separator between Buttons. @@ -346,9 +350,11 @@ public string ValidationGroup public string LocalResourceFile { get; set; } - public event EventHandler Click; - - public event CommandEventHandler Command; + public void RegisterForPostback() + { + AJAX.RegisterPostBackControl(this.link); + AJAX.RegisterPostBackControl(this.icon); + } /// ----------------------------------------------------------------------------- /// @@ -449,10 +455,18 @@ protected override void OnPreRender(EventArgs e) } } - public void RegisterForPostback() + /// ----------------------------------------------------------------------------- + /// + /// RaiseImageClick runs when the Image button is clicked. + /// + /// It raises a Command Event. + /// + /// The object that triggers the event. + /// An ImageClickEventArgs object. + /// ----------------------------------------------------------------------------- + protected void RaiseImageClick(object sender, ImageClickEventArgs e) { - AJAX.RegisterPostBackControl(this.link); - AJAX.RegisterPostBackControl(this.icon); + this.OnButtonClick(new EventArgs()); } /// ----------------------------------------------------------------------------- @@ -482,19 +496,5 @@ private void RaiseCommand(object sender, CommandEventArgs e) { this.OnCommand(e); } - - /// ----------------------------------------------------------------------------- - /// - /// RaiseImageClick runs when the Image button is clicked. - /// - /// It raises a Command Event. - /// - /// The object that triggers the event. - /// An ImageClickEventArgs object. - /// ----------------------------------------------------------------------------- - protected void RaiseImageClick(object sender, ImageClickEventArgs e) - { - this.OnButtonClick(new EventArgs()); - } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs index b1fbf75481b..c3f03deafca 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs @@ -49,6 +49,8 @@ public CheckBoxColumn(bool autoPostBack) this.AutoPostBack = autoPostBack; } + public event DNNDataGridCheckedColumnEventHandler CheckedChanged; + /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets and sets whether the column fires a postback when any check box is @@ -158,7 +160,26 @@ public bool HeaderCheckBox } } - public event DNNDataGridCheckedColumnEventHandler CheckedChanged; + /// ----------------------------------------------------------------------------- + /// + /// Initialises the Column. + /// + /// ----------------------------------------------------------------------------- + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(ListItemType.Item); + this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); + if (HttpContext.Current == null) + { + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + } + + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + } /// ----------------------------------------------------------------------------- /// @@ -210,26 +231,5 @@ private void OnCheckedChanged(object sender, DNNDataGridCheckChangedEventArgs e) this.CheckedChanged(sender, e); } } - - /// ----------------------------------------------------------------------------- - /// - /// Initialises the Column. - /// - /// ----------------------------------------------------------------------------- - public override void Initialize() - { - this.ItemTemplate = this.CreateTemplate(ListItemType.Item); - this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); - this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); - if (HttpContext.Current == null) - { - this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; - this.HeaderStyle.Font.Size = new FontUnit("10pt"); - this.HeaderStyle.Font.Bold = true; - } - - this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; - this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs index 2c96bc98965..5cf30065a67 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs @@ -35,23 +35,25 @@ public CheckBoxColumnTemplate() public CheckBoxColumnTemplate(ListItemType itemType) { this.ItemType = itemType; - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether gets and sets whether the column fires a postback when any check box is - /// changed. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - public bool AutoPostBack { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether gets and sets whether the checkbox is checked (unless DataBound). - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- + } + + public event DNNDataGridCheckedColumnEventHandler CheckedChanged; + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the column fires a postback when any check box is + /// changed. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public bool AutoPostBack { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the checkbox is checked (unless DataBound). + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool Checked { get; set; } /// ----------------------------------------------------------------------------- @@ -71,14 +73,14 @@ public string DataField { this.mDataField = value; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- public bool DesignMode { get; set; } /// ----------------------------------------------------------------------------- @@ -202,8 +204,6 @@ public void InstantiateIn(Control container) container.Controls.Add(box); } } - - public event DNNDataGridCheckedColumnEventHandler CheckedChanged; /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs index f2326f445d4..d319fc5fb81 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs @@ -22,19 +22,6 @@ public class DNNDataGrid : DataGrid { public event DNNDataGridCheckedColumnEventHandler ItemCheckedChanged; - /// ----------------------------------------------------------------------------- - /// - /// Centralised Event that is raised whenever a check box is changed. - /// - /// ----------------------------------------------------------------------------- - private void OnItemCheckedChanged(object sender, DNNDataGridCheckChangedEventArgs e) - { - if (this.ItemCheckedChanged != null) - { - this.ItemCheckedChanged(sender, e); - } - } - /// ----------------------------------------------------------------------------- /// /// Called when the grid is Data Bound. @@ -57,6 +44,19 @@ protected override void CreateControlHierarchy(bool useDataSource) { base.CreateControlHierarchy(useDataSource); } + + /// ----------------------------------------------------------------------------- + /// + /// Centralised Event that is raised whenever a check box is changed. + /// + /// ----------------------------------------------------------------------------- + private void OnItemCheckedChanged(object sender, DNNDataGridCheckChangedEventArgs e) + { + if (this.ItemCheckedChanged != null) + { + this.ItemCheckedChanged(sender, e); + } + } protected override void PrepareControlHierarchy() { diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs index 21748c4ce20..9af0684d9a4 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs @@ -193,6 +193,27 @@ public DNNMultiStateCollection States } } + /// ----------------------------------------------------------------------------- + /// + /// Initialises the Column. + /// + /// ----------------------------------------------------------------------------- + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(ListItemType.Item); + this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); + if (HttpContext.Current == null) + { + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + } + + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + } + /// ----------------------------------------------------------------------------- /// /// Creates a DNNMultiStateBoxColumnTemplate. @@ -232,26 +253,5 @@ private DNNMultiStateBoxColumnTemplate CreateTemplate(ListItemType type) template.DesignMode = isDesignMode; return template; } - - /// ----------------------------------------------------------------------------- - /// - /// Initialises the Column. - /// - /// ----------------------------------------------------------------------------- - public override void Initialize() - { - this.ItemTemplate = this.CreateTemplate(ListItemType.Item); - this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); - this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); - if (HttpContext.Current == null) - { - this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; - this.HeaderStyle.Font.Size = new FontUnit("10pt"); - this.HeaderStyle.Font.Bold = true; - } - - this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; - this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs index cc7d0987ae2..b0d3b232138 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs @@ -95,9 +95,9 @@ public string ImageURL /// /// A String. // ReSharper disable InconsistentNaming - public string OnClickJS { get; set; } + public string OnClickJS { get; set; } -// ReSharper restore InconsistentNaming + // ReSharper restore InconsistentNaming /// /// Gets or sets a value indicating whether gets or sets whether an Image is displayed. @@ -122,6 +122,26 @@ public bool ShowImage /// A Boolean. public string VisibleField { get; set; } + /// + /// Initialises the Column. + /// + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(ListItemType.Item); + this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); + + if (HttpContext.Current == null) + { + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + } + + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; + } + /// /// Creates a ImageCommandColumnTemplate. /// @@ -155,25 +175,5 @@ private ImageCommandColumnTemplate CreateTemplate(ListItemType type) return template; } - - /// - /// Initialises the Column. - /// - public override void Initialize() - { - this.ItemTemplate = this.CreateTemplate(ListItemType.Item); - this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); - this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); - - if (HttpContext.Current == null) - { - this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; - this.HeaderStyle.Font.Size = new FontUnit("10pt"); - this.HeaderStyle.Font.Bold = true; - } - - this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; - this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs index a8bd2dfc0f6..90535849472 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs @@ -37,12 +37,13 @@ public PermissionTriState() LookupScriptValues(this, out this._grantImagePath, out this._denyImagePath, out this._nullImagePath, out this._lockImagePath, out this._grantAltText, out this._denyAltText, out this._nullAltText); } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); + public bool IsFullControl { get; set; } - RegisterScripts(this.Page, this); - } + public bool IsView { get; set; } + + // Locked is currently not used on a post-back and therefore the + // value on postback is undefined at this time + public bool Locked { get; set; } public static void RegisterScripts(Page page, Control ctl) { @@ -84,16 +85,11 @@ public static string GetInitScript(Control ctl) return script; } - private static void LookupScriptValues(Control ctl, out string grantImagePath, out string denyImagePath, out string nullImagePath, out string lockImagePath, out string grantAltText, out string denyAltText, out string nullAltText) + protected override void OnInit(EventArgs e) { - grantImagePath = IconController.IconURL("Grant"); - denyImagePath = IconController.IconURL("Deny"); - nullImagePath = IconController.IconURL("Unchecked"); - lockImagePath = IconController.IconURL("Lock"); + base.OnInit(e); - grantAltText = Localization.GetString("PermissionTypeGrant"); - denyAltText = Localization.GetString("PermissionTypeDeny"); - nullAltText = Localization.GetString("PermissionTypeNull"); + RegisterScripts(this.Page, this); } protected override void Render(HtmlTextWriter writer) @@ -153,13 +149,17 @@ protected override void Render(HtmlTextWriter writer) base.Render(writer); } - public bool IsFullControl { get; set; } - - public bool IsView { get; set; } + private static void LookupScriptValues(Control ctl, out string grantImagePath, out string denyImagePath, out string nullImagePath, out string lockImagePath, out string grantAltText, out string denyAltText, out string nullAltText) + { + grantImagePath = IconController.IconURL("Grant"); + denyImagePath = IconController.IconURL("Deny"); + nullImagePath = IconController.IconURL("Unchecked"); + lockImagePath = IconController.IconURL("Lock"); - // Locked is currently not used on a post-back and therefore the - // value on postback is undefined at this time - public bool Locked { get; set; } + grantAltText = Localization.GetString("PermissionTypeGrant"); + denyAltText = Localization.GetString("PermissionTypeDeny"); + nullAltText = Localization.GetString("PermissionTypeNull"); + } public string PermissionKey { get; set; } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs index 8b3c037664a..30823300871 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs @@ -19,6 +19,12 @@ public PermissionTriStateTemplate(PermissionInfo permission) { this._permission = permission; } + + public bool IsFullControl { get; set; } + + public bool IsView { get; set; } + + public bool SupportDenyMode { get; set; } public void InstantiateIn(Control container) { @@ -39,11 +45,5 @@ public void BindToTriState(object sender, EventArgs e) triState.IsView = this.IsView; triState.PermissionKey = this._permission.PermissionKey; } - - public bool IsFullControl { get; set; } - - public bool IsView { get; set; } - - public bool SupportDenyMode { get; set; } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs b/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs index d673e103458..d84016d99bd 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs @@ -142,11 +142,11 @@ public ArrayList SelectedRoleNames { this.CurrentRoleSelection = value.Cast().ToList(); } - } - - /// - /// Gets or sets and Sets the ResourceFile to localize permissions. - /// + } + + /// + /// Gets or sets and Sets the ResourceFile to localize permissions. + /// public string ResourceFile { get; set; } /// @@ -212,6 +212,66 @@ private IList CurrentRoleSelection } } + /// + /// Load the ViewState. + /// + /// The saved state. + protected override void LoadViewState(object savedState) + { + if (savedState != null) + { + // Load State from the array of objects that was saved with SaveViewState. + var myState = (object[])savedState; + + // Load Base Controls ViewState + if (myState[0] != null) + { + base.LoadViewState(myState[0]); + } + + // Load TabPermissions + if (myState[1] != null) + { + string state = Convert.ToString(myState[1]); + this.CurrentRoleSelection = state != string.Empty + ? new List(state.Split(new[] { "##" }, StringSplitOptions.None)) + : new List(); + } + } + } + + /// + /// Saves the ViewState. + /// + /// + protected override object SaveViewState() + { + var allStates = new object[2]; + + // Save the Base Controls ViewState + allStates[0] = base.SaveViewState(); + + // Persist the TabPermisisons + var sb = new StringBuilder(); + bool addDelimiter = false; + foreach (string role in this.CurrentRoleSelection) + { + if (addDelimiter) + { + sb.Append("##"); + } + else + { + addDelimiter = true; + } + + sb.Append(role); + } + + allStates[1] = sb.ToString(); + return allStates; + } + /// /// Bind the data to the controls. /// @@ -315,66 +375,6 @@ private void SetUpRolesGrid() checkCol.HeaderStyle.Wrap = true; this.dgRoleSelection.Columns.Add(checkCol); } - - /// - /// Load the ViewState. - /// - /// The saved state. - protected override void LoadViewState(object savedState) - { - if (savedState != null) - { - // Load State from the array of objects that was saved with SaveViewState. - var myState = (object[])savedState; - - // Load Base Controls ViewState - if (myState[0] != null) - { - base.LoadViewState(myState[0]); - } - - // Load TabPermissions - if (myState[1] != null) - { - string state = Convert.ToString(myState[1]); - this.CurrentRoleSelection = state != string.Empty - ? new List(state.Split(new[] { "##" }, StringSplitOptions.None)) - : new List(); - } - } - } - - /// - /// Saves the ViewState. - /// - /// - protected override object SaveViewState() - { - var allStates = new object[2]; - - // Save the Base Controls ViewState - allStates[0] = base.SaveViewState(); - - // Persist the TabPermisisons - var sb = new StringBuilder(); - bool addDelimiter = false; - foreach (string role in this.CurrentRoleSelection) - { - if (addDelimiter) - { - sb.Append("##"); - } - else - { - addDelimiter = true; - } - - sb.Append(role); - } - - allStates[1] = sb.ToString(); - return allStates; - } /// /// Creates the Child Controls. diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs index 5aaafb20aba..dfb57d4a06c 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs @@ -16,31 +16,53 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class TextColumn : TemplateColumn - { - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Data Field is the field that binds to the Text Column. - /// - /// A String. - /// ----------------------------------------------------------------------------- - public string DataField { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Text (for Header/Footer Templates). - /// - /// A String. - /// ----------------------------------------------------------------------------- - public string Text { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Width of the Column. - /// - /// A Unit. - /// ----------------------------------------------------------------------------- + { + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Data Field is the field that binds to the Text Column. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string DataField { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Text (for Header/Footer Templates). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string Text { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Width of the Column. + /// + /// A Unit. + /// ----------------------------------------------------------------------------- public Unit Width { get; set; } + /// ----------------------------------------------------------------------------- + /// + /// Initialises the Column. + /// + /// ----------------------------------------------------------------------------- + public override void Initialize() + { + this.ItemTemplate = this.CreateTemplate(ListItemType.Item); + this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); + this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); + if (HttpContext.Current == null) + { + this.ItemStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.ItemStyle.Font.Size = new FontUnit("10pt"); + this.ItemStyle.HorizontalAlign = HorizontalAlign.Left; + this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; + this.HeaderStyle.Font.Size = new FontUnit("10pt"); + this.HeaderStyle.Font.Bold = true; + this.HeaderStyle.HorizontalAlign = HorizontalAlign.Left; + } + } + /// ----------------------------------------------------------------------------- /// /// Creates a TextColumnTemplate. @@ -74,27 +96,5 @@ private TextColumnTemplate CreateTemplate(ListItemType type) template.DesignMode = isDesignMode; return template; } - - /// ----------------------------------------------------------------------------- - /// - /// Initialises the Column. - /// - /// ----------------------------------------------------------------------------- - public override void Initialize() - { - this.ItemTemplate = this.CreateTemplate(ListItemType.Item); - this.EditItemTemplate = this.CreateTemplate(ListItemType.EditItem); - this.HeaderTemplate = this.CreateTemplate(ListItemType.Header); - if (HttpContext.Current == null) - { - this.ItemStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; - this.ItemStyle.Font.Size = new FontUnit("10pt"); - this.ItemStyle.HorizontalAlign = HorizontalAlign.Left; - this.HeaderStyle.Font.Names = new[] { "Tahoma, Verdana, Arial" }; - this.HeaderStyle.Font.Size = new FontUnit("10pt"); - this.HeaderStyle.Font.Bold = true; - this.HeaderStyle.HorizontalAlign = HorizontalAlign.Left; - } - } } } diff --git a/DNN Platform/Library/UI/WebControls/DualListBox.cs b/DNN Platform/Library/UI/WebControls/DualListBox.cs index b489b5203ee..ab32b367192 100644 --- a/DNN Platform/Library/UI/WebControls/DualListBox.cs +++ b/DNN Platform/Library/UI/WebControls/DualListBox.cs @@ -33,6 +33,12 @@ public DualListBox() this.ShowRemoveAllButton = true; } + public event DualListBoxEventHandler AddButtonClick; + + public event EventHandler AddAllButtonClick; + + public event DualListBoxEventHandler RemoveButtonClick; + public string AddAllImageURL { get; set; } public string AddAllKey { get; set; } @@ -78,14 +84,6 @@ public DualListBox() public bool CausesValidation { get; set; } public string ValidationGroup { get; set; } - - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } /// ----------------------------------------------------------------------------- /// @@ -127,6 +125,14 @@ public Style ButtonStyle } } + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the value of the Container Style. @@ -240,13 +246,28 @@ public void RaisePostBackEvent(string eventArgument) } } - public event DualListBoxEventHandler AddButtonClick; - - public event EventHandler AddAllButtonClick; + public event EventHandler RemoveAllButtonClick; + + protected virtual PostBackOptions GetPostBackOptions(string argument) + { + var postBackOptions = new PostBackOptions(this, argument) { RequiresJavaScriptProtocol = true }; + + if (this.CausesValidation && this.Page.GetValidators(this.ValidationGroup).Count > 0) + { + postBackOptions.PerformValidation = true; + postBackOptions.ValidationGroup = this.ValidationGroup; + } - public event DualListBoxEventHandler RemoveButtonClick; + return postBackOptions; + } - public event EventHandler RemoveAllButtonClick; + protected void OnAddButtonClick(DualListBoxEventArgs e) + { + if (this.AddButtonClick != null) + { + this.AddButtonClick(this, e); + } + } private NameValueCollection GetList(string listType, object dataSource) { @@ -463,27 +484,6 @@ private void RenderListBoxes(HtmlTextWriter writer) writer.RenderEndTag(); } - protected virtual PostBackOptions GetPostBackOptions(string argument) - { - var postBackOptions = new PostBackOptions(this, argument) { RequiresJavaScriptProtocol = true }; - - if (this.CausesValidation && this.Page.GetValidators(this.ValidationGroup).Count > 0) - { - postBackOptions.PerformValidation = true; - postBackOptions.ValidationGroup = this.ValidationGroup; - } - - return postBackOptions; - } - - protected void OnAddButtonClick(DualListBoxEventArgs e) - { - if (this.AddButtonClick != null) - { - this.AddButtonClick(this, e); - } - } - protected void OnAddAllButtonClick(EventArgs e) { if (this.AddAllButtonClick != null) diff --git a/DNN Platform/Library/UI/WebControls/LanguageSelector.cs b/DNN Platform/Library/UI/WebControls/LanguageSelector.cs index 3cf71ee1ab2..1d254d00673 100644 --- a/DNN Platform/Library/UI/WebControls/LanguageSelector.cs +++ b/DNN Platform/Library/UI/WebControls/LanguageSelector.cs @@ -18,6 +18,8 @@ namespace DotNetNuke.UI.WebControls /// public class LanguageSelector : Control, INamingContainer { + private Panel pnlControl; + public enum LanguageItemStyle { FlagOnly = 1, @@ -49,8 +51,6 @@ public enum LanguageSelectionObject SpecificCulture = 2, } - private Panel pnlControl; - /// /// Gets or sets selection mode (single, multiple). /// diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs index 76d62b3fe2a..bb381b02efa 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs @@ -103,42 +103,6 @@ public virtual string Type return "NavDataPageHierarchyData"; } } - - /// - /// Gets an enumeration object that represents all the child nodes of the current hierarchical node. - /// - /// - /// - public virtual IHierarchicalEnumerable GetChildren() - { - var objNodes = new NavDataPageHierarchicalEnumerable(); - if (this.m_objNode != null) - { - foreach (DNNNode objNode in this.m_objNode.DNNNodes) - { - objNodes.Add(new NavDataPageHierarchyData(objNode)); - } - } - - return objNodes; - } - - /// - /// Gets an enumeration object that represents the parent node of the current hierarchical node. - /// - /// - /// - public virtual IHierarchyData GetParent() - { - if (this.m_objNode != null) - { - return new NavDataPageHierarchyData(this.m_objNode.ParentNode); - } - else - { - return null; - } - } /// /// Gets node name. @@ -188,6 +152,42 @@ public virtual string NavigateUrl } } + /// + /// Gets an enumeration object that represents all the child nodes of the current hierarchical node. + /// + /// + /// + public virtual IHierarchicalEnumerable GetChildren() + { + var objNodes = new NavDataPageHierarchicalEnumerable(); + if (this.m_objNode != null) + { + foreach (DNNNode objNode in this.m_objNode.DNNNodes) + { + objNodes.Add(new NavDataPageHierarchyData(objNode)); + } + } + + return objNodes; + } + + /// + /// Gets an enumeration object that represents the parent node of the current hierarchical node. + /// + /// + /// + public virtual IHierarchyData GetParent() + { + if (this.m_objNode != null) + { + return new NavDataPageHierarchyData(this.m_objNode.ParentNode); + } + else + { + return null; + } + } + /// /// Gets node description. /// diff --git a/DNN Platform/Library/UI/WebControls/PagingControl.cs b/DNN Platform/Library/UI/WebControls/PagingControl.cs index acc68d9616e..25a50f5e8ba 100644 --- a/DNN Platform/Library/UI/WebControls/PagingControl.cs +++ b/DNN Platform/Library/UI/WebControls/PagingControl.cs @@ -18,15 +18,17 @@ namespace DotNetNuke.UI.WebControls public class PagingControl : WebControl, IPostBackEventHandler { protected Repeater PageNumbers; + protected TableCell cellDisplayLinks; + protected TableCell cellDisplayStatus; private int _totalPages = -1; private string _CSSClassLinkActive; private string _CSSClassLinkInactive; private string _CSSClassPagingStatus; private PagingControlMode _Mode = PagingControlMode.URL; - protected TableCell cellDisplayLinks; - protected TableCell cellDisplayStatus; protected Table tablePageNumbers; + public event EventHandler PageChanged; + [Bindable(true)] [Category("Behavior")] [DefaultValue("")] @@ -119,7 +121,46 @@ public void RaisePostBackEvent(string eventArgument) this.OnPageChanged(new EventArgs()); } - public event EventHandler PageChanged; + protected override void CreateChildControls() + { + this.tablePageNumbers = new Table(); + this.cellDisplayStatus = new TableCell(); + this.cellDisplayLinks = new TableCell(); + + // cellDisplayStatus.CssClass = "Normal"; + // cellDisplayLinks.CssClass = "Normal"; + this.tablePageNumbers.CssClass = string.IsNullOrEmpty(this.CssClass) ? "PagingTable" : this.CssClass; + var intRowIndex = this.tablePageNumbers.Rows.Add(new TableRow()); + this.PageNumbers = new Repeater(); + var I = new PageNumberLinkTemplate(this); + this.PageNumbers.ItemTemplate = I; + this.BindPageNumbers(this.TotalRecords, this.PageSize); + this.cellDisplayStatus.HorizontalAlign = HorizontalAlign.Left; + + // cellDisplayStatus.Width = new Unit("50%"); + this.cellDisplayLinks.HorizontalAlign = HorizontalAlign.Right; + + // cellDisplayLinks.Width = new Unit("50%"); + var intTotalPages = this._totalPages; + if (intTotalPages == 0) + { + intTotalPages = 1; + } + + var str = string.Format(Localization.GetString("Pages"), this.CurrentPage, intTotalPages); + var lit = new LiteralControl(str); + this.cellDisplayStatus.Controls.Add(lit); + this.tablePageNumbers.Rows[intRowIndex].Cells.Add(this.cellDisplayStatus); + this.tablePageNumbers.Rows[intRowIndex].Cells.Add(this.cellDisplayLinks); + } + + protected void OnPageChanged(EventArgs e) + { + if (this.PageChanged != null) + { + this.PageChanged(this, e); + } + } private void BindPageNumbers(int TotalRecords, int RecordsPerPage) { @@ -293,47 +334,6 @@ private string GetLastLink() : "" + Localization.GetString("Last", Localization.SharedResourceFile) + ""; } - protected override void CreateChildControls() - { - this.tablePageNumbers = new Table(); - this.cellDisplayStatus = new TableCell(); - this.cellDisplayLinks = new TableCell(); - - // cellDisplayStatus.CssClass = "Normal"; - // cellDisplayLinks.CssClass = "Normal"; - this.tablePageNumbers.CssClass = string.IsNullOrEmpty(this.CssClass) ? "PagingTable" : this.CssClass; - var intRowIndex = this.tablePageNumbers.Rows.Add(new TableRow()); - this.PageNumbers = new Repeater(); - var I = new PageNumberLinkTemplate(this); - this.PageNumbers.ItemTemplate = I; - this.BindPageNumbers(this.TotalRecords, this.PageSize); - this.cellDisplayStatus.HorizontalAlign = HorizontalAlign.Left; - - // cellDisplayStatus.Width = new Unit("50%"); - this.cellDisplayLinks.HorizontalAlign = HorizontalAlign.Right; - - // cellDisplayLinks.Width = new Unit("50%"); - var intTotalPages = this._totalPages; - if (intTotalPages == 0) - { - intTotalPages = 1; - } - - var str = string.Format(Localization.GetString("Pages"), this.CurrentPage, intTotalPages); - var lit = new LiteralControl(str); - this.cellDisplayStatus.Controls.Add(lit); - this.tablePageNumbers.Rows[intRowIndex].Cells.Add(this.cellDisplayStatus); - this.tablePageNumbers.Rows[intRowIndex].Cells.Add(this.cellDisplayLinks); - } - - protected void OnPageChanged(EventArgs e) - { - if (this.PageChanged != null) - { - this.PageChanged(this, e); - } - } - protected override void Render(HtmlTextWriter output) { if (this.PageNumbers == null) diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs index c92fc37e109..f951cd7e603 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs @@ -68,7 +68,7 @@ public bool UpdateValue(PropertyEditorEventArgs e) objProperty = this.DataSource.GetType().GetProperty(ValueDataField); // Set the Value property to the new value - if ((! ReferenceEquals(newValue, oldValue)) || changed) + if ((!ReferenceEquals(newValue, oldValue)) || changed) { if (objProperty.PropertyType.FullName == "System.String") { @@ -216,10 +216,10 @@ private EditorInfo GetEditorInfo() editInfo.ControlStyle = new Style(); // Get Visibility Field - editInfo.ProfileVisibility = new ProfileVisibility - { - VisibilityMode = UserVisibilityMode.AllUsers, - }; + editInfo.ProfileVisibility = new ProfileVisibility + { + VisibilityMode = UserVisibilityMode.AllUsers, + }; if (!string.IsNullOrEmpty(VisibilityDataField)) { property = this.DataSource.GetType().GetProperty(VisibilityDataField); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs index 96a6807fea3..0f8aefe6fd4 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs @@ -91,7 +91,7 @@ public bool UpdateValue(PropertyEditorEventArgs e) if (key == name) { // Set the Value property to the new value - if ((! ReferenceEquals(newValue, oldValue)) || changed) + if ((!ReferenceEquals(newValue, oldValue)) || changed) { settings[key] = newValue; _IsDirty = true; diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs index 24c838c69ff..4c710d3c0ab 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs @@ -56,7 +56,7 @@ public bool UpdateValue(PropertyEditorEventArgs e) PropertyInfo objProperty = this.DataSource.GetType().GetProperty(e.Name); if (objProperty != null) { - if ((! ReferenceEquals(newValue, oldValue)) || changed) + if ((!ReferenceEquals(newValue, oldValue)) || changed) { objProperty.SetValue(this.DataSource, newValue, null); _IsDirty = true; @@ -187,10 +187,10 @@ private EditorInfo GetEditorInfo(object dataSource, PropertyInfo objProperty) } // Set Visibility - editInfo.ProfileVisibility = new ProfileVisibility - { - VisibilityMode = UserVisibilityMode.AllUsers, - }; + editInfo.ProfileVisibility = new ProfileVisibility + { + VisibilityMode = UserVisibilityMode.AllUsers, + }; return editInfo; } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs index e1499634a0a..633d165788d 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs @@ -28,20 +28,6 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:CollectionEditorControl runat=server>")] public class CollectionEditorControl : PropertyEditorControl { - /// ----------------------------------------------------------------------------- - /// - /// Gets the Underlying DataSource. - /// - /// An IEnumerable. - /// ----------------------------------------------------------------------------- - protected override IEnumerable UnderlyingDataSource - { - get - { - return (IEnumerable)this.DataSource; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the value of the Category. @@ -65,6 +51,20 @@ protected override IEnumerable UnderlyingDataSource [DefaultValue("")] [Description("Enter the name of the field that is data bound to the Editor Type.")] public string EditorDataField { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Underlying DataSource. + /// + /// An IEnumerable. + /// ----------------------------------------------------------------------------- + protected override IEnumerable UnderlyingDataSource + { + get + { + return (IEnumerable)this.DataSource; + } + } /// ----------------------------------------------------------------------------- /// @@ -163,6 +163,16 @@ protected override IEnumerable UnderlyingDataSource [Description("Enter the name of the field that determines the visibility.")] public string VisibilityDataField { get; set; } + protected override void AddEditorRow(Table table, object obj) + { + this.AddEditorRow(table, this.NameDataField, new CollectionEditorInfoAdapter(obj, this.ID, this.NameDataField, this.GetFieldNames())); + } + + protected override void AddEditorRow(Panel container, object obj) + { + this.AddEditorRow(container, this.NameDataField, new CollectionEditorInfoAdapter(obj, this.ID, this.NameDataField, this.GetFieldNames())); + } + private Hashtable GetFieldNames() { var fields = new Hashtable(); @@ -178,16 +188,6 @@ private Hashtable GetFieldNames() return fields; } - - protected override void AddEditorRow(Table table, object obj) - { - this.AddEditorRow(table, this.NameDataField, new CollectionEditorInfoAdapter(obj, this.ID, this.NameDataField, this.GetFieldNames())); - } - - protected override void AddEditorRow(Panel container, object obj) - { - this.AddEditorRow(container, this.NameDataField, new CollectionEditorInfoAdapter(obj, this.ID, this.NameDataField, this.GetFieldNames())); - } protected override void AddEditorRow(object obj) { 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 f13fa94d009..a763276822a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs @@ -28,18 +28,6 @@ public AutoCompleteControl() this.Load += this.AutoCompleteControl_Load; } - 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) - { - } - protected override void RenderEditMode(HtmlTextWriter writer) { int length = Null.NullInteger; @@ -72,5 +60,17 @@ protected override void RenderEditMode(HtmlTextWriter writer) 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 d72c18cc27e..6427137b25a 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 @@ -19,34 +19,19 @@ namespace DotNetNuke.UI.WebControls public class DnnCountryAutocompleteControl : EditControl { private TextBox _CountryName; - - private TextBox CountryName - { - get - { - if (this._CountryName == null) - { - this._CountryName = new TextBox(); - } - - return this._CountryName; - } - } private HiddenField _CountryId; - private HiddenField CountryId + public DnnCountryAutocompleteControl() { - get - { - if (this._CountryId == null) - { - this._CountryId = new HiddenField(); - } - - return this._CountryId; - } + this.Init += this.DnnCountryRegionControl_Init; } + + public DnnCountryAutocompleteControl(string type) + { + this.Init += this.DnnCountryRegionControl_Init; + this.SystemType = type; + } public override string EditControlClientId { @@ -72,22 +57,51 @@ protected override string StringValue set { this.Value = value; } } + + private TextBox CountryName + { + get + { + if (this._CountryName == null) + { + this._CountryName = new TextBox(); + } + + return this._CountryName; + } + } + + private HiddenField CountryId + { + get + { + if (this._CountryId == null) + { + this._CountryId = new HiddenField(); + } + + return this._CountryId; + } + } protected string OldStringValue { get { return Convert.ToString(this.OldValue); } } - - public DnnCountryAutocompleteControl() + + public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { - this.Init += this.DnnCountryRegionControl_Init; - } + bool dataChanged = false; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "_id"]; + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue; + dataChanged = true; + } - public DnnCountryAutocompleteControl(string type) - { - this.Init += this.DnnCountryRegionControl_Init; - this.SystemType = type; - } + return dataChanged; + } protected override void OnDataChanged(EventArgs e) { @@ -115,20 +129,6 @@ protected override void CreateChildControls() this.Controls.Add(this.CountryId); } - public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) - { - bool dataChanged = false; - string presentValue = this.StringValue; - string postedValue = postCollection[postDataKey + "_id"]; - if (!presentValue.Equals(postedValue)) - { - this.Value = postedValue; - dataChanged = true; - } - - return dataChanged; - } - protected override void OnPreRender(System.EventArgs e) { base.OnPreRender(e); 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 2100eda28ea..11d1cc4d0c1 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 @@ -40,6 +40,8 @@ public DNNListEditControl() this.ParentKey = string.Empty; this.SortAlphabetically = false; } + + public event PropertyChangedEventHandler ItemChanged; /// ----------------------------------------------------------------------------- /// @@ -248,28 +250,6 @@ public void RaisePostBackEvent(string eventArgument) } } - public event PropertyChangedEventHandler ItemChanged; - - private PropertyEditorEventArgs GetEventArgs() - { - var args = new PropertyEditorEventArgs(this.Name); - if (this.ValueField == ListBoundField.Id) - { - // This is an Integer Value - args.Value = this.IntegerValue; - args.OldValue = this.OldIntegerValue; - } - else - { - // This is a String Value - args.Value = this.StringValue; - args.OldValue = this.OldStringValue; - } - - args.StringValue = this.StringValue; - return args; - } - /// ----------------------------------------------------------------------------- /// /// OnAttributesChanged runs when the CustomAttributes property has changed. @@ -305,6 +285,26 @@ protected override void OnDataChanged(EventArgs e) { this.OnValueChanged(this.GetEventArgs()); } + + private PropertyEditorEventArgs GetEventArgs() + { + var args = new PropertyEditorEventArgs(this.Name); + if (this.ValueField == ListBoundField.Id) + { + // This is an Integer Value + args.Value = this.IntegerValue; + args.OldValue = this.OldIntegerValue; + } + else + { + // This is a String Value + args.Value = this.StringValue; + args.OldValue = this.OldStringValue; + } + + args.StringValue = this.StringValue; + return args; + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNLocaleEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNLocaleEditControl.cs index 2441d932d59..1bd721ad2e8 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNLocaleEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNLocaleEditControl.cs @@ -52,6 +52,44 @@ public void RaisePostBackEvent(string eventArgument) this._DisplayMode = eventArgument; } + /// + /// OnAttributesChanged runs when the CustomAttributes property has changed. + /// + protected override void OnAttributesChanged() + { + // Get the List settings out of the "Attributes" + if (this.CustomAttributes != null) + { + foreach (Attribute attribute in this.CustomAttributes) + { + var listAtt = attribute as LanguagesListTypeAttribute; + if (listAtt != null) + { + this._ListType = listAtt.ListType; + break; + } + } + } + } + + /// + /// RenderViewMode renders the View (readonly) mode of the control. + /// + /// A HtmlTextWriter. + protected override void RenderViewMode(HtmlTextWriter writer) + { + Locale locale = LocaleController.Instance.GetLocale(this.StringValue); + + this.ControlStyle.AddAttributesToRender(writer); + writer.RenderBeginTag(HtmlTextWriterTag.Div); + if (locale != null) + { + writer.Write(locale.Text); + } + + writer.RenderEndTag(); + } + private bool IsSelected(string locale) { return locale == this.StringValue; @@ -118,44 +156,6 @@ private void RenderOption(HtmlTextWriter writer, CultureInfo culture) writer.Write(localeName); writer.RenderEndTag(); } - - /// - /// OnAttributesChanged runs when the CustomAttributes property has changed. - /// - protected override void OnAttributesChanged() - { - // Get the List settings out of the "Attributes" - if (this.CustomAttributes != null) - { - foreach (Attribute attribute in this.CustomAttributes) - { - var listAtt = attribute as LanguagesListTypeAttribute; - if (listAtt != null) - { - this._ListType = listAtt.ListType; - break; - } - } - } - } - - /// - /// RenderViewMode renders the View (readonly) mode of the control. - /// - /// A HtmlTextWriter. - protected override void RenderViewMode(HtmlTextWriter writer) - { - Locale locale = LocaleController.Instance.GetLocale(this.StringValue); - - this.ControlStyle.AddAttributesToRender(writer); - writer.RenderBeginTag(HtmlTextWriterTag.Div); - if (locale != null) - { - writer.Write(locale.Text); - } - - writer.RenderEndTag(); - } /// /// RenderEditMode renders the Edit mode of the control. 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 fedf25c502a..32b02addf70 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 @@ -2,7 +2,8 @@ // 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; using System.Collections.Generic; using System.Linq; using System.Web.UI; @@ -16,9 +17,9 @@ namespace DotNetNuke.UI.WebControls using DotNetNuke.Framework.JavaScriptLibraries; using DotNetNuke.Services.Localization; using DotNetNuke.Web.Client; - using DotNetNuke.Web.Client.ClientResourceManagement; + using DotNetNuke.Web.Client.ClientResourceManagement; -/// ----------------------------------------------------------------------------- + /// ----------------------------------------------------------------------------- /// Project: DotNetNuke /// Namespace: DotNetNuke.UI.WebControls /// Class: DNNRegionEditControl @@ -32,6 +33,49 @@ namespace DotNetNuke.UI.WebControls public class DNNRegionEditControl : EditControl { private DropDownList _Regions; + + private TextBox _Region; + + private HtmlInputHidden _InitialValue; + + private List _listEntries; + + public DNNRegionEditControl() + { + this.Init += this.DnnRegionControl_Init; + } + + public DNNRegionEditControl(string type) + { + this.Init += this.DnnRegionControl_Init; + this.SystemType = type; + } + + /// + /// Gets or sets the parent key of the List to display. + /// + public string ParentKey { get; set; } + + protected override string StringValue + { + get + { + string strValue = Null.NullString; + if (this.Value != null) + { + strValue = Convert.ToString(this.Value); + } + + return strValue; + } + + set { this.Value = value; } + } + + protected string OldStringValue + { + get { return Convert.ToString(this.OldValue); } + } private DropDownList Regions { @@ -45,8 +89,6 @@ private DropDownList Regions return this._Regions; } } - - private TextBox _Region; private TextBox Region { @@ -60,8 +102,6 @@ private TextBox Region return this._Region; } } - - private HtmlInputHidden _InitialValue; private HtmlInputHidden RegionCode { @@ -76,34 +116,6 @@ private HtmlInputHidden RegionCode } } - protected override string StringValue - { - get - { - string strValue = Null.NullString; - if (this.Value != null) - { - strValue = Convert.ToString(this.Value); - } - - return strValue; - } - - set { this.Value = value; } - } - - protected string OldStringValue - { - get { return Convert.ToString(this.OldValue); } - } - - /// - /// Gets or sets the parent key of the List to display. - /// - public string ParentKey { get; set; } - - private List _listEntries; - /// /// Gets the ListEntryInfo objects associated witht the control. /// @@ -128,17 +140,20 @@ protected int PortalId return PortalController.GetEffectivePortalId(PortalSettings.Current.PortalId); } } - - public DNNRegionEditControl() + + public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { - this.Init += this.DnnRegionControl_Init; - } + bool dataChanged = false; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "_value"]; + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue; + dataChanged = true; + } - public DNNRegionEditControl(string type) - { - this.Init += this.DnnRegionControl_Init; - this.SystemType = type; - } + return dataChanged; + } /// ----------------------------------------------------------------------------- /// @@ -193,20 +208,6 @@ protected override void CreateChildControls() this.Controls.Add(this.RegionCode); } - public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) - { - bool dataChanged = false; - string presentValue = this.StringValue; - string postedValue = postCollection[postDataKey + "_value"]; - if (!presentValue.Equals(postedValue)) - { - this.Value = postedValue; - dataChanged = true; - } - - return dataChanged; - } - protected override void OnPreRender(System.EventArgs e) { base.OnPreRender(e); 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 bd222696e64..db3b7659971 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 @@ -60,6 +60,20 @@ protected string EditorText } } + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + var dataChanged = false; + var presentValue = this.StringValue; + var postedValue = this.EditorText; + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue; + dataChanged = true; + } + + return dataChanged; + } + protected override void CreateChildControls() { if (this.EditMode == PropertyEditorMode.Edit) @@ -90,13 +104,13 @@ protected override void CreateChildControls() } else { - this._defaultTextEditor = new TextBox - { - ID = this.ID + "edit", - Width = this.ControlStyle.Width.IsEmpty ? new Unit(300) : this.ControlStyle.Width, - Height = this.ControlStyle.Height.IsEmpty ? new Unit(250) : this.ControlStyle.Height, - TextMode = TextBoxMode.MultiLine, - }; + this._defaultTextEditor = new TextBox + { + ID = this.ID + "edit", + Width = this.ControlStyle.Width.IsEmpty ? new Unit(300) : this.ControlStyle.Width, + Height = this.ControlStyle.Height.IsEmpty ? new Unit(250) : this.ControlStyle.Height, + TextMode = TextBoxMode.MultiLine, + }; this._defaultTextEditor.Attributes.Add("aria-label", "editor"); } @@ -108,20 +122,6 @@ protected override void CreateChildControls() base.CreateChildControls(); } - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - var dataChanged = false; - var presentValue = this.StringValue; - var postedValue = this.EditorText; - if (!presentValue.Equals(postedValue)) - { - this.Value = postedValue; - dataChanged = true; - } - - return dataChanged; - } - protected override void OnDataChanged(EventArgs e) { var strValue = this.RemoveBaseTags(Convert.ToString(this.Value)); @@ -130,11 +130,6 @@ protected override void OnDataChanged(EventArgs e) this.OnValueChanged(args); } - private string RemoveBaseTags(string strInput) - { - return Globals.BaseTagRegex.Replace(strInput, " "); - } - protected override void OnInit(EventArgs e) { this.EnsureChildControls(); @@ -155,6 +150,11 @@ protected override void OnPreRender(EventArgs e) } } + private string RemoveBaseTags(string strInput) + { + return Globals.BaseTagRegex.Replace(strInput, " "); + } + protected override void RenderEditMode(HtmlTextWriter writer) { this.RenderChildren(writer); 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 8d8e67af476..d954242d792 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs @@ -152,6 +152,21 @@ protected override string StringValue this.Value = DateTime.Parse(value); } } + + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + this.EnsureChildControls(); + bool dataChanged = false; + string presentValue = this.StringValue; + string postedValue = postCollection[postDataKey + "date"]; + if (!presentValue.Equals(postedValue)) + { + this.Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); + dataChanged = true; + } + + return dataChanged; + } protected override void CreateChildControls() { @@ -179,21 +194,6 @@ protected virtual void LoadDateControls() } } - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - this.EnsureChildControls(); - bool dataChanged = false; - string presentValue = this.StringValue; - string postedValue = postCollection[postDataKey + "date"]; - if (!presentValue.Equals(postedValue)) - { - this.Value = DateTime.Parse(postedValue).ToString(CultureInfo.InvariantCulture); - dataChanged = true; - } - - return dataChanged; - } - /// /// OnDataChanged is called by the PostBack Handler when the Data has changed. /// 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 c8f87601fea..890ea5ebc8a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs @@ -47,6 +47,44 @@ protected override string DefaultFormat } } + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + bool dataChanged = false; + DateTime presentValue = this.OldDateValue; + string postedDate = postCollection[postDataKey + "date"]; + string postedHours = postCollection[postDataKey + "hours"]; + string postedMinutes = postCollection[postDataKey + "minutes"]; + string postedAMPM = postCollection[postDataKey + "ampm"]; + DateTime postedValue = Null.NullDate; + if (!string.IsNullOrEmpty(postedDate)) + { + DateTime.TryParse(postedDate, out postedValue); + } + + if (postedHours != "12" || this.is24HourClock) + { + int hours = 0; + if (int.TryParse(postedHours, out hours)) + { + postedValue = postedValue.AddHours(hours); + } + } + + postedValue = postedValue.AddMinutes(int.Parse(postedMinutes)); + if (!this.is24HourClock && postedAMPM.Equals("PM")) + { + postedValue = postedValue.AddHours(12); + } + + if (!presentValue.Equals(postedValue)) + { + this.Value = postedValue.ToString(CultureInfo.InvariantCulture); + dataChanged = true; + } + + return dataChanged; + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -141,43 +179,5 @@ protected override void LoadDateControls() } } } - - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - bool dataChanged = false; - DateTime presentValue = this.OldDateValue; - string postedDate = postCollection[postDataKey + "date"]; - string postedHours = postCollection[postDataKey + "hours"]; - string postedMinutes = postCollection[postDataKey + "minutes"]; - string postedAMPM = postCollection[postDataKey + "ampm"]; - DateTime postedValue = Null.NullDate; - if (!string.IsNullOrEmpty(postedDate)) - { - DateTime.TryParse(postedDate, out postedValue); - } - - if (postedHours != "12" || this.is24HourClock) - { - int hours = 0; - if (int.TryParse(postedHours, out hours)) - { - postedValue = postedValue.AddHours(hours); - } - } - - postedValue = postedValue.AddMinutes(int.Parse(postedMinutes)); - if (!this.is24HourClock && postedAMPM.Equals("PM")) - { - postedValue = postedValue.AddHours(12); - } - - if (!presentValue.Equals(postedValue)) - { - this.Value = postedValue.ToString(CultureInfo.InvariantCulture); - dataChanged = true; - } - - return dataChanged; - } } } 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 6576ab87a72..cffd578b371 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs @@ -28,6 +28,12 @@ public abstract class EditControl : WebControl, IPostBackDataHandler { private object[] _CustomAttributes; + public event PropertyChangedEventHandler ItemAdded; + + public event PropertyChangedEventHandler ItemDeleted; + + public event PropertyChangedEventHandler ValueChanged; + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Custom Attributes for this Control. @@ -134,14 +140,6 @@ public virtual bool IsValid /// public string DataField { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets stringValue is the value of the control expressed as a String. - /// - /// A string representing the Value. - /// ----------------------------------------------------------------------------- - protected abstract string StringValue { get; set; } - public UserInfo User { get; set; } public virtual string EditControlClientId @@ -152,6 +150,14 @@ public virtual string EditControlClientId } } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets stringValue is the value of the control expressed as a String. + /// + /// A string representing the Value. + /// ----------------------------------------------------------------------------- + protected abstract string StringValue { get; set; } + /// ----------------------------------------------------------------------------- /// /// LoadPostData loads the Post Back Data and determines whether the value has change. @@ -185,12 +191,6 @@ public void RaisePostDataChangedEvent() this.OnDataChanged(EventArgs.Empty); } - public event PropertyChangedEventHandler ItemAdded; - - public event PropertyChangedEventHandler ItemDeleted; - - public event PropertyChangedEventHandler ValueChanged; - /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged 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 ac209158ae1..a5272269387 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs @@ -78,8 +78,8 @@ protected override void OnDataChanged(EventArgs e) int intValue = Convert.ToInt32(this.Value); int intOldValue = Convert.ToInt32(this.OldValue); - var args = new PropertyEditorEventArgs(this.Name) - { Value = Enum.ToObject(this.EnumType, intValue), OldValue = Enum.ToObject(this.EnumType, intOldValue) }; + var args = new PropertyEditorEventArgs(this.Name) + { Value = Enum.ToObject(this.EnumType, intValue), OldValue = Enum.ToObject(this.EnumType, intOldValue) }; this.OnValueChanged(args); } 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 93e067f696e..3d3956fea8a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs @@ -46,6 +46,23 @@ protected Version Version return this.Value as Version; } } + + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) + { + string majorVersion = postCollection[postDataKey + "_Major"]; + string minorVersion = postCollection[postDataKey + "_Minor"]; + string buildVersion = postCollection[postDataKey + "_Build"]; + bool dataChanged = false; + Version presentValue = this.Version; + var postedValue = new Version(majorVersion + "." + minorVersion + "." + buildVersion); + if (!postedValue.Equals(presentValue)) + { + this.Value = postedValue; + dataChanged = true; + } + + return dataChanged; + } protected void RenderDropDownList(HtmlTextWriter writer, string type, int val) { @@ -152,22 +169,5 @@ protected override void RenderViewMode(HtmlTextWriter writer) writer.RenderEndTag(); } - - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) - { - string majorVersion = postCollection[postDataKey + "_Major"]; - string minorVersion = postCollection[postDataKey + "_Minor"]; - string buildVersion = postCollection[postDataKey + "_Build"]; - bool dataChanged = false; - Version presentValue = this.Version; - var postedValue = new Version(majorVersion + "." + minorVersion + "." + buildVersion); - if (!postedValue.Equals(presentValue)) - { - this.Value = postedValue; - dataChanged = true; - } - - return dataChanged; - } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs index c41ea37d85c..a219e91e3bc 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs @@ -65,13 +65,11 @@ public FieldEditorControl() this.ViewStateMode = ViewStateMode.Disabled; } - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } + public event PropertyChangedEventHandler ItemAdded; + + public event PropertyChangedEventHandler ItemChanged; + + public event EditorCreatedEventHandler ItemCreated; /// ----------------------------------------------------------------------------- /// @@ -93,6 +91,14 @@ protected override HtmlTextWriterTag TagKey [DefaultValue("")] [Description("Enter the name of the field that is data bound to the Control.")] public string DataField { get; set; } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } /// ----------------------------------------------------------------------------- /// @@ -330,13 +336,130 @@ public bool IsValid [Description("Set the Style for the Visibility Control")] public Style VisibilityStyle { get; private set; } - public event PropertyChangedEventHandler ItemAdded; + public event PropertyChangedEventHandler ItemDeleted; - public event PropertyChangedEventHandler ItemChanged; + /// ----------------------------------------------------------------------------- + /// + /// Binds the controls to the DataSource. + /// + /// ----------------------------------------------------------------------------- + public override void DataBind() + { + // Invoke OnDataBinding so DataBinding Event is raised + this.OnDataBinding(EventArgs.Empty); + + // Clear Existing Controls + this.Controls.Clear(); + + // Clear Child View State as controls will be loaded from DataSource + this.ClearChildViewState(); + + // Start Tracking ViewState + this.TrackViewState(); + + // Create the editor + this.CreateEditor(); + + // Set flag so CreateChildConrols should not be invoked later in control's lifecycle + this.ChildControlsCreated = true; + } + + /// ----------------------------------------------------------------------------- + /// + /// Validates the data, and sets the IsValid Property. + /// + /// ----------------------------------------------------------------------------- + public virtual void Validate() + { + this._IsValid = this.Editor.IsValid; + + if (this._IsValid) + { + IEnumerator valEnumerator = this.Validators.GetEnumerator(); + while (valEnumerator.MoveNext()) + { + var validator = (IValidator)valEnumerator.Current; + validator.Validate(); + if (!validator.IsValid) + { + this._IsValid = false; + break; + } + } - public event EditorCreatedEventHandler ItemCreated; + this._Validated = true; + } + } - public event PropertyChangedEventHandler ItemDeleted; + /// ----------------------------------------------------------------------------- + /// + /// CreateEditor creates the control collection for this control. + /// + /// ----------------------------------------------------------------------------- + protected virtual void CreateEditor() + { + EditorInfo editInfo = this.EditorInfoAdapter.CreateEditControl(); + + this.ID = editInfo.Name; + + if (editInfo != null) + { + editInfo.User = this.User; + + if (editInfo.EditMode == PropertyEditorMode.Edit) + { + editInfo.EditMode = this.EditMode; + } + + // Get the Editor Type to use (if specified) + if (!string.IsNullOrEmpty(this.EditorTypeName)) + { + editInfo.Editor = this.EditorTypeName; + } + + // Get the Label Mode to use (if specified) + if (this.LabelMode != LabelMode.Left) + { + editInfo.LabelMode = this.LabelMode; + } + + // if Required is specified set editors property + if (this.Required) + { + editInfo.Required = this.Required; + } + + // Get the ValidationExpression to use (if specified) + if (!string.IsNullOrEmpty(this.ValidationExpression)) + { + editInfo.ValidationExpression = this.ValidationExpression; + } + + // Raise the ItemCreated Event + this.OnItemCreated(new PropertyEditorItemEventArgs(editInfo)); + + this.Visible = editInfo.Visible; + + if (this.EditorDisplayMode == EditorDisplayMode.Div) + { + this.BuildDiv(editInfo); + } + else + { + this.BuildTable(editInfo); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an item is added to a collection type property. + /// + /// ----------------------------------------------------------------------------- + protected virtual void CollectionItemAdded(object sender, PropertyEditorEventArgs e) + { + this.OnItemAdded(e); + } /// /// BuildDiv creates the Control as a Div. @@ -656,89 +779,19 @@ private VisibilityControl BuildVisibility(EditorInfo editInfo) if (this.ShowVisibility) { - visControl = new VisibilityControl - { - ID = "_visibility", - Name = editInfo.Name, - User = this.User, - Value = editInfo.ProfileVisibility, - }; + visControl = new VisibilityControl + { + ID = "_visibility", + Name = editInfo.Name, + User = this.User, + Value = editInfo.ProfileVisibility, + }; visControl.ControlStyle.CopyFrom(this.VisibilityStyle); visControl.VisibilityChanged += this.VisibilityChanged; } return visControl; } - - /// ----------------------------------------------------------------------------- - /// - /// CreateEditor creates the control collection for this control. - /// - /// ----------------------------------------------------------------------------- - protected virtual void CreateEditor() - { - EditorInfo editInfo = this.EditorInfoAdapter.CreateEditControl(); - - this.ID = editInfo.Name; - - if (editInfo != null) - { - editInfo.User = this.User; - - if (editInfo.EditMode == PropertyEditorMode.Edit) - { - editInfo.EditMode = this.EditMode; - } - - // Get the Editor Type to use (if specified) - if (!string.IsNullOrEmpty(this.EditorTypeName)) - { - editInfo.Editor = this.EditorTypeName; - } - - // Get the Label Mode to use (if specified) - if (this.LabelMode != LabelMode.Left) - { - editInfo.LabelMode = this.LabelMode; - } - - // if Required is specified set editors property - if (this.Required) - { - editInfo.Required = this.Required; - } - - // Get the ValidationExpression to use (if specified) - if (!string.IsNullOrEmpty(this.ValidationExpression)) - { - editInfo.ValidationExpression = this.ValidationExpression; - } - - // Raise the ItemCreated Event - this.OnItemCreated(new PropertyEditorItemEventArgs(editInfo)); - - this.Visible = editInfo.Visible; - - if (this.EditorDisplayMode == EditorDisplayMode.Div) - { - this.BuildDiv(editInfo); - } - else - { - this.BuildTable(editInfo); - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is added to a collection type property. - /// - /// ----------------------------------------------------------------------------- - protected virtual void CollectionItemAdded(object sender, PropertyEditorEventArgs e) - { - this.OnItemAdded(e); - } /// ----------------------------------------------------------------------------- /// @@ -819,59 +872,6 @@ protected virtual void VisibilityChanged(object sender, PropertyEditorEventArgs this.IsDirty = this.EditorInfoAdapter.UpdateVisibility(e); } - /// ----------------------------------------------------------------------------- - /// - /// Binds the controls to the DataSource. - /// - /// ----------------------------------------------------------------------------- - public override void DataBind() - { - // Invoke OnDataBinding so DataBinding Event is raised - this.OnDataBinding(EventArgs.Empty); - - // Clear Existing Controls - this.Controls.Clear(); - - // Clear Child View State as controls will be loaded from DataSource - this.ClearChildViewState(); - - // Start Tracking ViewState - this.TrackViewState(); - - // Create the editor - this.CreateEditor(); - - // Set flag so CreateChildConrols should not be invoked later in control's lifecycle - this.ChildControlsCreated = true; - } - - /// ----------------------------------------------------------------------------- - /// - /// Validates the data, and sets the IsValid Property. - /// - /// ----------------------------------------------------------------------------- - public virtual void Validate() - { - this._IsValid = this.Editor.IsValid; - - if (this._IsValid) - { - IEnumerator valEnumerator = this.Validators.GetEnumerator(); - while (valEnumerator.MoveNext()) - { - var validator = (IValidator)valEnumerator.Current; - validator.Validate(); - if (!validator.IsValid) - { - this._IsValid = false; - break; - } - } - - this._Validated = true; - } - } - /// ----------------------------------------------------------------------------- /// /// Runs when an Item in the List Is Changed. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs index 3979a76e389..f5099522114 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs @@ -17,8 +17,6 @@ public SortOrderAttribute(int order) this.Order = order; } - public int Order { get; set; } - public static int DefaultOrder { get @@ -26,5 +24,7 @@ public static int DefaultOrder return int.MaxValue; } } + + public int Order { get; set; } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs index 45cc6975fd0..52389aa4173 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs @@ -52,24 +52,11 @@ public PropertyEditorControl() this.AutoGenerate = true; } - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the Underlying DataSource. - /// - /// An IEnumerable Boolean. - /// ----------------------------------------------------------------------------- - protected virtual IEnumerable UnderlyingDataSource - { - get { return this.GetProperties(); } - } + public event PropertyChangedEventHandler ItemAdded; + + public event EditorCreatedEventHandler ItemCreated; + + public event PropertyChangedEventHandler ItemDeleted; /// ----------------------------------------------------------------------------- /// @@ -89,6 +76,25 @@ protected virtual IEnumerable UnderlyingDataSource [Browsable(false)] [Category("Data")] public object DataSource { get; set; } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Underlying DataSource. + /// + /// An IEnumerable Boolean. + /// ----------------------------------------------------------------------------- + protected virtual IEnumerable UnderlyingDataSource + { + get { return this.GetProperties(); } + } /// ----------------------------------------------------------------------------- /// @@ -351,11 +357,85 @@ public bool IsValid [Description("Set the Style for the Visibility Control")] public Style VisibilityStyle { get; private set; } - public event PropertyChangedEventHandler ItemAdded; - - public event EditorCreatedEventHandler ItemCreated; + /// ----------------------------------------------------------------------------- + /// + /// Binds the controls to the DataSource. + /// + /// ----------------------------------------------------------------------------- + public override void DataBind() + { + // Invoke OnDataBinding so DataBinding Event is raised + this.OnDataBinding(EventArgs.Empty); + + // Clear Existing Controls + this.Controls.Clear(); + + // Clear Child View State as controls will be loaded from DataSource + this.ClearChildViewState(); + + // Start Tracking ViewState + this.TrackViewState(); + + // Create the Editor + this.CreateEditor(); + + // Set flag so CreateChildConrols should not be invoked later in control's lifecycle + this.ChildControlsCreated = true; + } - public event PropertyChangedEventHandler ItemDeleted; + /// ----------------------------------------------------------------------------- + /// + /// AddEditorRow builds a sigle editor row and adds it to the Table, using the + /// specified adapter. + /// + /// The Table Control to add the row to. + /// The name of property being added. + /// An IEditorInfoAdapter. + /// ----------------------------------------------------------------------------- + protected void AddEditorRow(Table table, string name, IEditorInfoAdapter adapter) + { + var row = new TableRow(); + table.Rows.Add(row); + + var cell = new TableCell(); + row.Cells.Add(cell); + + // Create a FieldEditor for this Row + var editor = new FieldEditorControl + { + DataSource = this.DataSource, + EditorInfoAdapter = adapter, + DataField = name, + EditorDisplayMode = this.DisplayMode, + EnableClientValidation = this.EnableClientValidation, + EditMode = this.EditMode, + HelpDisplayMode = this.HelpDisplayMode, + LabelMode = this.LabelMode, + LabelWidth = this.LabelWidth, + }; + this.AddEditorRow(editor, cell); + + this.Fields.Add(editor); + } + + protected void AddEditorRow(WebControl container, string name, IEditorInfoAdapter adapter) + { + var editor = new FieldEditorControl + { + DataSource = this.DataSource, + EditorInfoAdapter = adapter, + DataField = name, + EditorDisplayMode = this.DisplayMode, + EnableClientValidation = this.EnableClientValidation, + EditMode = this.EditMode, + HelpDisplayMode = this.HelpDisplayMode, + LabelMode = this.LabelMode, + LabelWidth = this.LabelWidth, + }; + this.AddEditorRow(editor, container); + + this.Fields.Add(editor); + } /// ----------------------------------------------------------------------------- /// @@ -424,60 +504,6 @@ private void AddEditorRow(FieldEditorControl editor, WebControl container) editor.DataBind(); container.Controls.Add(editor); } - - /// ----------------------------------------------------------------------------- - /// - /// AddEditorRow builds a sigle editor row and adds it to the Table, using the - /// specified adapter. - /// - /// The Table Control to add the row to. - /// The name of property being added. - /// An IEditorInfoAdapter. - /// ----------------------------------------------------------------------------- - protected void AddEditorRow(Table table, string name, IEditorInfoAdapter adapter) - { - var row = new TableRow(); - table.Rows.Add(row); - - var cell = new TableCell(); - row.Cells.Add(cell); - - // Create a FieldEditor for this Row - var editor = new FieldEditorControl - { - DataSource = this.DataSource, - EditorInfoAdapter = adapter, - DataField = name, - EditorDisplayMode = this.DisplayMode, - EnableClientValidation = this.EnableClientValidation, - EditMode = this.EditMode, - HelpDisplayMode = this.HelpDisplayMode, - LabelMode = this.LabelMode, - LabelWidth = this.LabelWidth, - }; - this.AddEditorRow(editor, cell); - - this.Fields.Add(editor); - } - - protected void AddEditorRow(WebControl container, string name, IEditorInfoAdapter adapter) - { - var editor = new FieldEditorControl - { - DataSource = this.DataSource, - EditorInfoAdapter = adapter, - DataField = name, - EditorDisplayMode = this.DisplayMode, - EnableClientValidation = this.EnableClientValidation, - EditMode = this.EditMode, - HelpDisplayMode = this.HelpDisplayMode, - LabelMode = this.LabelMode, - LabelWidth = this.LabelWidth, - }; - this.AddEditorRow(editor, container); - - this.Fields.Add(editor); - } /// ----------------------------------------------------------------------------- /// @@ -921,32 +947,6 @@ protected override void OnPreRender(EventArgs e) base.OnPreRender(e); } - /// ----------------------------------------------------------------------------- - /// - /// Binds the controls to the DataSource. - /// - /// ----------------------------------------------------------------------------- - public override void DataBind() - { - // Invoke OnDataBinding so DataBinding Event is raised - this.OnDataBinding(EventArgs.Empty); - - // Clear Existing Controls - this.Controls.Clear(); - - // Clear Child View State as controls will be loaded from DataSource - this.ClearChildViewState(); - - // Start Tracking ViewState - this.TrackViewState(); - - // Create the Editor - this.CreateEditor(); - - // Set flag so CreateChildConrols should not be invoked later in control's lifecycle - this.ChildControlsCreated = true; - } - /// ----------------------------------------------------------------------------- /// /// Runs when an item is added to a collection type property. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs index 7317eb00840..b91117e7165 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs @@ -25,9 +25,9 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:PropertyLabelControl runat=server>")] public class PropertyLabelControl : WebControl { - private string _ResourceKey; protected LinkButton cmdHelp; protected HtmlGenericControl label; + private string _ResourceKey; protected Label lblHelp; protected Label lblLabel; protected Panel pnlTooltip; @@ -37,14 +37,6 @@ public PropertyLabelControl() { } - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - /// /// Gets or sets and Sets the Caption Text if no ResourceKey is provided. /// @@ -82,6 +74,14 @@ public string AssociatedControlId this.lblLabel.AssociatedControlID = value; } } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } /// /// Gets or sets and Sets the related Edit Control. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs index cb1ecb7531e..f972a980dec 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs @@ -25,20 +25,6 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:SettingsEditorControl runat=server>")] public class SettingsEditorControl : PropertyEditorControl { - /// ----------------------------------------------------------------------------- - /// - /// Gets the Underlying DataSource. - /// - /// An IEnumerable. - /// ----------------------------------------------------------------------------- - protected override IEnumerable UnderlyingDataSource - { - get - { - return this.GetSettings(); - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the CustomEditors that are used by this control. @@ -56,6 +42,32 @@ protected override IEnumerable UnderlyingDataSource /// ----------------------------------------------------------------------------- public Hashtable Visibility { get; set; } + /// ----------------------------------------------------------------------------- + /// + /// Gets the Underlying DataSource. + /// + /// An IEnumerable. + /// ----------------------------------------------------------------------------- + protected override IEnumerable UnderlyingDataSource + { + get + { + return this.GetSettings(); + } + } + + protected override void AddEditorRow(Table table, object obj) + { + var info = (SettingInfo)obj; + this.AddEditorRow(table, info.Name, new SettingsEditorInfoAdapter(this.DataSource, obj, this.ID)); + } + + protected override void AddEditorRow(Panel container, object obj) + { + var info = (SettingInfo)obj; + this.AddEditorRow(container, info.Name, new SettingsEditorInfoAdapter(this.DataSource, obj, this.ID)); + } + /// ----------------------------------------------------------------------------- /// /// GetSettings converts the DataSource into an ArrayList (IEnumerable). @@ -80,18 +92,6 @@ private ArrayList GetSettings() arrSettings.Sort(new SettingNameComparer()); return arrSettings; } - - protected override void AddEditorRow(Table table, object obj) - { - var info = (SettingInfo)obj; - this.AddEditorRow(table, info.Name, new SettingsEditorInfoAdapter(this.DataSource, obj, this.ID)); - } - - protected override void AddEditorRow(Panel container, object obj) - { - var info = (SettingInfo)obj; - this.AddEditorRow(container, info.Name, new SettingsEditorInfoAdapter(this.DataSource, obj, this.ID)); - } protected override void AddEditorRow(object obj) { diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs index b4fc4b3f172..2244c67add4 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs @@ -32,11 +32,7 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:VisibilityControl runat=server>")] public class VisibilityControl : WebControl, IPostBackDataHandler, INamingContainer { - protected ProfileVisibility Visibility - { - get { return this.Value as ProfileVisibility; } - set { this.Value = value; } - } + public event PropertyChangedEventHandler VisibilityChanged; /// /// Gets or sets caption. @@ -49,6 +45,12 @@ protected ProfileVisibility Visibility /// /// A string representing the Name of the property. public string Name { get; set; } + + protected ProfileVisibility Visibility + { + get { return this.Value as ProfileVisibility; } + set { this.Value = value; } + } /// /// Gets or sets the UserInfo object that represents the User whose profile is being displayed. @@ -96,17 +98,17 @@ public virtual bool LoadPostData(string postDataKey, NameValueCollection postCol } } - this.Value = new ProfileVisibility(this.User.PortalID, sb.ToString()) - { - VisibilityMode = postedVisibility, - }; + this.Value = new ProfileVisibility(this.User.PortalID, sb.ToString()) + { + VisibilityMode = postedVisibility, + }; } else { - this.Value = new ProfileVisibility - { - VisibilityMode = postedVisibility, - }; + this.Value = new ProfileVisibility + { + VisibilityMode = postedVisibility, + }; } dataChanged = true; @@ -126,7 +128,20 @@ public void RaisePostDataChangedEvent() this.OnVisibilityChanged(args); } - public event PropertyChangedEventHandler VisibilityChanged; + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + JavaScript.RequestRegistration(CommonJs.jQuery); + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + this.Page.RegisterRequiresPostBack(this); + this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "visibleChange", "$(document).ready(function(){$('.dnnFormVisibility').on('click', 'input[type=radio]', function(){$(this).parent().parent().find('ul').hide();$(this).parent().next('ul').show();});});", true); + } private void RenderVisibility(HtmlTextWriter writer, string optionValue, UserVisibilityMode selectedVisibility, string optionText) { @@ -193,21 +208,6 @@ private void RenderRelationships(HtmlTextWriter writer) this.Visibility.RelationshipVisibilities.Count(r => r.RelationshipId == relationship.RelationshipId) == 1); } } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - JavaScript.RequestRegistration(CommonJs.jQuery); - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - this.Page.RegisterRequiresPostBack(this); - this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "visibleChange", "$(document).ready(function(){$('.dnnFormVisibility').on('click', 'input[type=radio]', function(){$(this).parent().parent().find('ul').hide();$(this).parent().next('ul').show();});});", true); - } /// /// OnVisibilityChanged runs when the Visibility has changed. It raises the VisibilityChanged diff --git a/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs b/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs index f19f462213d..489aec3f998 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs @@ -6,6 +6,11 @@ namespace DotNetNuke.Modules.CoreMessaging.Services { public class FilesStatus { + // ReSharper restore InconsistentNaming + public FilesStatus() + { + } + // ReSharper disable InconsistentNaming public bool success { get; set; } @@ -26,10 +31,5 @@ public class FilesStatus public string message { get; set; } public int id { get; set; } - - // ReSharper restore InconsistentNaming - public FilesStatus() - { - } } } diff --git a/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs b/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs index 2eda06080d4..3a7d22425bc 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs @@ -370,18 +370,6 @@ public HttpResponseMessage DismissAllNotifications() } } - public class ConversationDTO - { - public int ConversationId { get; set; } - } - - public class ReplyDTO : ConversationDTO - { - public string Body { get; set; } - - public IList FileIds { get; set; } - } - private string LocalizeActionString(string key, int desktopModuleId) { if (string.IsNullOrEmpty(key)) @@ -434,5 +422,17 @@ private dynamic ToExpandoObject(Message message) return messageObj; } + + public class ConversationDTO + { + public int ConversationId { get; set; } + } + + public class ReplyDTO : ConversationDTO + { + public string Body { get; set; } + + public IList FileIds { get; set; } + } } } diff --git a/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs b/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs index c7441de814d..7eae090255a 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs @@ -83,12 +83,12 @@ public HttpResponseMessage GetSubscriptions(int pageIndex, int pageSize, string } } - var response = new - { - Success = true, - Results = sortedList.Skip(pageIndex * pageSize).Take(pageSize).ToList(), - TotalResults = sortedList.Count(), - }; + var response = new + { + Success = true, + Results = sortedList.Skip(pageIndex * pageSize).Take(pageSize).ToList(), + TotalResults = sortedList.Count(), + }; return this.Request.CreateResponse(HttpStatusCode.OK, response); } @@ -106,13 +106,13 @@ public HttpResponseMessage UpdateSystemSubscription(InboxSubscriptionViewModel p try { var userPreferencesController = UserPreferencesController.Instance; - var userPreference = new UserPreference - { - PortalId = this.UserInfo.PortalID, - UserId = this.UserInfo.UserID, - MessagesEmailFrequency = (Frequency)post.MsgFreq, - NotificationsEmailFrequency = (Frequency)post.NotifyFreq, - }; + var userPreference = new UserPreference + { + PortalId = this.UserInfo.PortalID, + UserId = this.UserInfo.UserID, + MessagesEmailFrequency = (Frequency)post.MsgFreq, + NotificationsEmailFrequency = (Frequency)post.NotifyFreq, + }; userPreferencesController.SetUserPreference(userPreference); return this.Request.CreateResponse(HttpStatusCode.OK, userPreferencesController.GetUserPreference(this.UserInfo)); diff --git a/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs b/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs index 54965f33275..a7e80124f31 100644 --- a/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs +++ b/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs @@ -43,11 +43,6 @@ public ModuleInfo ModuleConfiguration public string LocalResourceFile { get; set; } - protected string LocalizeString(string key) - { - return Localization.GetString(key, this.LocalResourceFile); - } - public string GetSettingsAsJson() { var settings = GetModuleSettings(PortalSettings.Current, this.ModuleConfiguration, Null.NullInteger); @@ -66,6 +61,11 @@ public string GetSettingsAsJson() return settings.ToJson(); } + protected string LocalizeString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -84,33 +84,6 @@ protected override void OnLoad(EventArgs e) this.Response.Redirect(Globals.AccessDeniedURL(), false); } } - - /// - /// These values are passed in as the 'settings' parameter of the JavaScript initialization function, together with - /// values that are automatically retrieved by Social Library such as portalId and moduleId. - /// - private Hashtable GetViewSettings() - { - var portalSettings = PortalSettings.Current; - var userPreferenceController = UserPreferencesController.Instance; - var user = UserController.GetUserById(portalSettings.PortalId, portalSettings.UserId); - UserPreference userPreference = null; - if (user != null) - { - userPreference = userPreferenceController.GetUserPreference(user); - } - - const int notifyFrequency = 2; - const int messageFrequency = 0; - - return new Hashtable - { - { "moduleScope", string.Format("#{0}", this.ScopeWrapper.ClientID) }, - { "pageSize", 25 }, - { "notifyFrequency", userPreference != null ? (int)userPreference.NotificationsEmailFrequency : notifyFrequency }, - { "msgFrequency", userPreference != null ? (int)userPreference.MessagesEmailFrequency : messageFrequency }, - }; - } private static Hashtable GetModuleSettings(PortalSettings portalSettings, ModuleInfo moduleInfo, int uniqueId) { @@ -176,6 +149,33 @@ private static string GetHistoryNavigationKey(string moduleName) { return HttpContext.Current.Server.HtmlEncode(moduleName.ToLowerInvariant().Replace(" ", string.Empty)); } + + /// + /// These values are passed in as the 'settings' parameter of the JavaScript initialization function, together with + /// values that are automatically retrieved by Social Library such as portalId and moduleId. + /// + private Hashtable GetViewSettings() + { + var portalSettings = PortalSettings.Current; + var userPreferenceController = UserPreferencesController.Instance; + var user = UserController.GetUserById(portalSettings.PortalId, portalSettings.UserId); + UserPreference userPreference = null; + if (user != null) + { + userPreference = userPreferenceController.GetUserPreference(user); + } + + const int notifyFrequency = 2; + const int messageFrequency = 0; + + return new Hashtable + { + { "moduleScope", string.Format("#{0}", this.ScopeWrapper.ClientID) }, + { "pageSize", 25 }, + { "notifyFrequency", userPreference != null ? (int)userPreference.NotificationsEmailFrequency : notifyFrequency }, + { "msgFrequency", userPreference != null ? (int)userPreference.MessagesEmailFrequency : messageFrequency }, + }; + } private static TimeSpan GetSessionTimeout() { diff --git a/DNN Platform/Modules/CoreMessaging/View.ascx.cs b/DNN Platform/Modules/CoreMessaging/View.ascx.cs index d53f546525d..9d47e9fbc35 100644 --- a/DNN Platform/Modules/CoreMessaging/View.ascx.cs +++ b/DNN Platform/Modules/CoreMessaging/View.ascx.cs @@ -99,6 +99,11 @@ protected override void OnInit(EventArgs e) base.OnInit(e); } + + private static bool PermissionPredicate(PermissionInfoBase p) + { + return p.PermissionKey == "VIEW" && p.AllowAccess && (p.RoleName == Globals.glbRoleAllUsersName || p.RoleName == Globals.glbRoleUnauthUserName); + } private void AddIe7StyleSheet() { @@ -126,10 +131,5 @@ private bool PermissionsNotProperlySet() return permissions.Find(PermissionPredicate) != null; } - - private static bool PermissionPredicate(PermissionInfoBase p) - { - return p.PermissionKey == "VIEW" && p.AllowAccess && (p.RoleName == Globals.glbRoleAllUsersName || p.RoleName == Globals.glbRoleUnauthUserName); - } } } diff --git a/DNN Platform/Modules/DDRMenu/Actions.cs b/DNN Platform/Modules/DDRMenu/Actions.cs index a8c948a6d4f..efdf301648d 100644 --- a/DNN Platform/Modules/DDRMenu/Actions.cs +++ b/DNN Platform/Modules/DDRMenu/Actions.cs @@ -21,6 +21,9 @@ namespace DotNetNuke.Web.DDRMenu public class Actions : ActionBase { + private DDRMenuNavigationProvider navProvider; + private Dictionary actions; + public string PathSystemScript { get; set; } public string MenuStyle { get; set; } @@ -33,9 +36,6 @@ public class Actions : ActionBase [PersistenceMode(PersistenceMode.InnerProperty)] public List TemplateArguments { get; set; } - private DDRMenuNavigationProvider navProvider; - private Dictionary actions; - protected override void OnInit(EventArgs e) { using (new DNNContext(this)) diff --git a/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs b/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs index c0ad031b9ea..d0c93911861 100644 --- a/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs +++ b/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs @@ -16,52 +16,41 @@ namespace DotNetNuke.Web.DDRMenu.DNNCommon public class DNNContext : IDisposable { - public static DNNContext Current - { - get { return (DNNContext)HttpContext.Current.Items[DataName]; } private set { HttpContext.Current.Items[DataName] = value; } - } + private static string _ModuleName; - private readonly DNNContext savedContext; + private static string _ModuleFolder; - public Control HostControl { get; private set; } + private static string _DataName; - private Page _Page; + private readonly DNNContext savedContext; - public Page Page - { - get { return this._Page ?? (this._Page = this.HostControl.Page); } - } + private Page _Page; private PortalSettings _PortalSettings; - public PortalSettings PortalSettings - { - get { return this._PortalSettings ?? (this._PortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } - } - private TabInfo _ActiveTab; - public TabInfo ActiveTab - { - get { return this._ActiveTab ?? (this._ActiveTab = this.PortalSettings.ActiveTab); } - } - private string _SkinPath; - public string SkinPath + public DNNContext(Control hostControl) { - get { return this._SkinPath ?? (this._SkinPath = this.ActiveTab.SkinPath); } + this.HostControl = hostControl; + + this.savedContext = Current; + Current = this; } - private static string _ModuleName; + public static DNNContext Current + { + get { return (DNNContext)HttpContext.Current.Items[DataName]; } + private set { HttpContext.Current.Items[DataName] = value; } + } public static string ModuleName { get { return _ModuleName ?? (_ModuleName = GetModuleNameFromAssembly()); } } - private static string _ModuleFolder; - public static string ModuleFolder { get @@ -73,19 +62,31 @@ public static string ModuleFolder } } - private static string _DataName; + public Control HostControl { get; private set; } - private static string DataName + public Page Page { - get { return _DataName ?? (_DataName = "DDRMenu.DNNContext." + ModuleName); } + get { return this._Page ?? (this._Page = this.HostControl.Page); } } - public DNNContext(Control hostControl) + public PortalSettings PortalSettings { - this.HostControl = hostControl; + get { return this._PortalSettings ?? (this._PortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } + } - this.savedContext = Current; - Current = this; + public TabInfo ActiveTab + { + get { return this._ActiveTab ?? (this._ActiveTab = this.PortalSettings.ActiveTab); } + } + + public string SkinPath + { + get { return this._SkinPath ?? (this._SkinPath = this.ActiveTab.SkinPath); } + } + + private static string DataName + { + get { return _DataName ?? (_DataName = "DDRMenu.DNNContext." + ModuleName); } } public string ResolveUrl(string relativeUrl) @@ -93,19 +94,19 @@ public string ResolveUrl(string relativeUrl) return this.HostControl.ResolveUrl(relativeUrl); } + public void Dispose() + { + Current = this.savedContext; + } + private static string GetModuleNameFromAssembly() { var moduleFullName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); -// ReSharper disable PossibleNullReferenceException + // ReSharper disable PossibleNullReferenceException return moduleFullName.Substring(moduleFullName.LastIndexOf('.') + 1); -// ReSharper restore PossibleNullReferenceException - } - - public void Dispose() - { - Current = this.savedContext; + // ReSharper restore PossibleNullReferenceException } } } diff --git a/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs b/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs index 0218ba6a97f..8b606aad474 100644 --- a/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs +++ b/DNN Platform/Modules/DDRMenu/Common/PathResolver.cs @@ -11,6 +11,13 @@ namespace DotNetNuke.Web.DDRMenu.DNNCommon public class PathResolver { + private readonly string manifestFolder; + + public PathResolver(string manifestFolder) + { + this.manifestFolder = manifestFolder; + } + public enum RelativeTo { Container, @@ -21,13 +28,6 @@ public enum RelativeTo Skin, } - private readonly string manifestFolder; - - public PathResolver(string manifestFolder) - { - this.manifestFolder = manifestFolder; - } - public string Resolve(string path, params RelativeTo[] roots) { var context = DNNContext.Current; @@ -74,10 +74,10 @@ public string Resolve(string path, params RelativeTo[] roots) var containerRoot = (container == null) ? context.SkinPath -// ReSharper disable PossibleNullReferenceException + // ReSharper disable PossibleNullReferenceException : Path.GetDirectoryName(((UI.Containers.Container)container).AppRelativeVirtualPath).Replace( -// ReSharper restore PossibleNullReferenceException + // ReSharper restore PossibleNullReferenceException '\\', '/') + "/"; resolvedPath = Path.Combine(containerRoot, path); break; diff --git a/DNN Platform/Modules/DDRMenu/Controller.cs b/DNN Platform/Modules/DDRMenu/Controller.cs index fbbba30a31f..50b1bad8ff7 100644 --- a/DNN Platform/Modules/DDRMenu/Controller.cs +++ b/DNN Platform/Modules/DDRMenu/Controller.cs @@ -19,11 +19,11 @@ namespace DotNetNuke.Web.DDRMenu public class Controller : IUpgradeable, IPortable { - private const string ddrMenuModuleName = "DDRMenu"; - private const string ddrMenuMmoduleDefinitionName = "DDR Menu"; - public static readonly Regex AscxText1Regex = new Regex(Regex.Escape(@"Namespace=""DNNDoneRight.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); public static readonly Regex AscxText2Regex = new Regex(Regex.Escape(@"Namespace=""DNNGarden.TemplateEngine"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private const string ddrMenuModuleName = "DDRMenu"; + private const string ddrMenuMmoduleDefinitionName = "DDR Menu"; public static readonly Regex AscxText3Regex = new Regex(Regex.Escape(@"Assembly=""DNNDoneRight.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); public static readonly Regex AscxText4Regex = new Regex(Regex.Escape(@"Assembly=""DNNGarden.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); @@ -46,19 +46,19 @@ public string ExportModule(int moduleId) var moduleSettings = module.ModuleSettings; var settings = new Settings - { - MenuStyle = Convert.ToString(moduleSettings["MenuStyle"]), - NodeXmlPath = Convert.ToString(moduleSettings["NodeXmlPath"]), - NodeSelector = Convert.ToString(moduleSettings["NodeSelector"]), - IncludeNodes = Convert.ToString(moduleSettings["IncludeNodes"]), - ExcludeNodes = Convert.ToString(moduleSettings["ExcludeNodes"]), - NodeManipulator = Convert.ToString(moduleSettings["NodeManipulator"]), - IncludeContext = Convert.ToBoolean(moduleSettings["IncludeContext"]), - IncludeHidden = Convert.ToBoolean(moduleSettings["IncludeHidden"]), - ClientOptions = Settings.ClientOptionsFromSettingString(Convert.ToString(moduleSettings["ClientOptions"])), - TemplateArguments = + { + MenuStyle = Convert.ToString(moduleSettings["MenuStyle"]), + NodeXmlPath = Convert.ToString(moduleSettings["NodeXmlPath"]), + NodeSelector = Convert.ToString(moduleSettings["NodeSelector"]), + IncludeNodes = Convert.ToString(moduleSettings["IncludeNodes"]), + ExcludeNodes = Convert.ToString(moduleSettings["ExcludeNodes"]), + NodeManipulator = Convert.ToString(moduleSettings["NodeManipulator"]), + IncludeContext = Convert.ToBoolean(moduleSettings["IncludeContext"]), + IncludeHidden = Convert.ToBoolean(moduleSettings["IncludeHidden"]), + ClientOptions = Settings.ClientOptionsFromSettingString(Convert.ToString(moduleSettings["ClientOptions"])), + TemplateArguments = Settings.TemplateArgumentsFromSettingString(Convert.ToString(moduleSettings["TemplateArguments"])), - }; + }; return settings.ToXml(); } @@ -90,10 +90,10 @@ private static void UpdateWebConfig() configXml.Load(webConfig); var navProviders = configXml.SelectSingleNode("/configuration/dotnetnuke/navigationControl/providers") as XmlElement; -// ReSharper disable PossibleNullReferenceException + // ReSharper disable PossibleNullReferenceException var addProvider = navProviders.SelectSingleNode("add[@name='" + navName + "']") as XmlElement; -// ReSharper restore PossibleNullReferenceException + // ReSharper restore PossibleNullReferenceException var needsUpdate = true; if (addProvider == null) { diff --git a/DNN Platform/Modules/DDRMenu/DDRMenuControl.cs b/DNN Platform/Modules/DDRMenu/DDRMenuControl.cs index 10514194a04..fac99a45cad 100644 --- a/DNN Platform/Modules/DDRMenu/DDRMenuControl.cs +++ b/DNN Platform/Modules/DDRMenu/DDRMenuControl.cs @@ -12,9 +12,16 @@ namespace DotNetNuke.Web.DDRMenu internal class DDRMenuControl : WebControl, IPostBackEventHandler { + private MenuBase menu; + + public delegate void MenuClickEventHandler(string id); + + public event MenuClickEventHandler NodeClick; + public override bool EnableViewState { - get { return false; } set { } + get { return false; } + set { } } internal MenuNode RootNode { get; set; } @@ -23,11 +30,16 @@ public override bool EnableViewState internal Settings MenuSettings { get; set; } - public delegate void MenuClickEventHandler(string id); - - public event MenuClickEventHandler NodeClick; - - private MenuBase menu; + public void RaisePostBackEvent(string eventArgument) + { + using (new DNNContext(this)) + { + if (this.NodeClick != null) + { + this.NodeClick(eventArgument); + } + } + } protected override void OnPreRender(EventArgs e) { @@ -52,16 +64,5 @@ protected override void Render(HtmlTextWriter htmlWriter) this.menu.Render(htmlWriter); } } - - public void RaisePostBackEvent(string eventArgument) - { - using (new DNNContext(this)) - { - if (this.NodeClick != null) - { - this.NodeClick(eventArgument); - } - } - } } } diff --git a/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs b/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs index ae01f3ca08e..d6f13fc60b3 100644 --- a/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs +++ b/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs @@ -17,6 +17,8 @@ namespace DotNetNuke.Web.DDRMenu public class DDRMenuNavigationProvider : NavigationProvider { + private DDRMenuControl menuControl; + public override Alignment ControlAlignment { get; set; } public override bool IndicateChildren { get; set; } @@ -171,8 +173,6 @@ public class DDRMenuNavigationProvider : NavigationProvider public override List CustomAttributes { get; set; } - private DDRMenuControl menuControl; - public override Control NavigationControl { get { return this.menuControl; } @@ -263,18 +263,18 @@ public void Bind(DNNNodeCollection objNodes, bool localise) this.menuControl.RootNode = new MenuNode(objNodes); this.menuControl.SkipLocalisation = !localise; this.menuControl.MenuSettings = new Settings - { - MenuStyle = this.GetCustomAttribute("MenuStyle") ?? this.MenuStyle ?? "DNNMenu", - NodeXmlPath = this.GetCustomAttribute("NodeXmlPath"), - NodeSelector = this.GetCustomAttribute("NodeSelector"), - IncludeContext = Convert.ToBoolean(this.GetCustomAttribute("IncludeContext") ?? "false"), - IncludeHidden = Convert.ToBoolean(this.GetCustomAttribute("IncludeHidden") ?? "false"), - IncludeNodes = this.GetCustomAttribute("IncludeNodes"), - ExcludeNodes = this.GetCustomAttribute("ExcludeNodes"), - NodeManipulator = this.GetCustomAttribute("NodeManipulator"), - ClientOptions = clientOptions, - TemplateArguments = this.TemplateArguments, - }; + { + MenuStyle = this.GetCustomAttribute("MenuStyle") ?? this.MenuStyle ?? "DNNMenu", + NodeXmlPath = this.GetCustomAttribute("NodeXmlPath"), + NodeSelector = this.GetCustomAttribute("NodeSelector"), + IncludeContext = Convert.ToBoolean(this.GetCustomAttribute("IncludeContext") ?? "false"), + IncludeHidden = Convert.ToBoolean(this.GetCustomAttribute("IncludeHidden") ?? "false"), + IncludeNodes = this.GetCustomAttribute("IncludeNodes"), + ExcludeNodes = this.GetCustomAttribute("ExcludeNodes"), + NodeManipulator = this.GetCustomAttribute("NodeManipulator"), + ClientOptions = clientOptions, + TemplateArguments = this.TemplateArguments, + }; } private string GetCustomAttribute(string attributeName) diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs b/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs index ac86ba8441d..d395eb65460 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs @@ -34,10 +34,10 @@ public bool HaveApi() } } -// ReSharper disable EmptyGeneralCatchClause + // ReSharper disable EmptyGeneralCatchClause catch -// ReSharper restore EmptyGeneralCatchClause + // ReSharper restore EmptyGeneralCatchClause { } diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Generic.cs b/DNN Platform/Modules/DDRMenu/Localisation/Generic.cs index 73c0fcd5acf..a46d03c9334 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Generic.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Generic.cs @@ -55,12 +55,12 @@ public bool HaveApi() } } -// ReSharper disable EmptyGeneralCatchClause + // ReSharper disable EmptyGeneralCatchClause catch { } -// ReSharper restore EmptyGeneralCatchClause + // ReSharper restore EmptyGeneralCatchClause } } diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Localiser.cs b/DNN Platform/Modules/DDRMenu/Localisation/Localiser.cs index cb66f1161a6..4af7e792a39 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Localiser.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Localiser.cs @@ -12,9 +12,14 @@ namespace DotNetNuke.Web.DDRMenu.Localisation public class Localiser { - private readonly int portalId; private static bool apiChecked; private static ILocalisation _LocalisationApi; + private readonly int portalId; + + public Localiser(int portalId) + { + this.portalId = portalId; + } private static ILocalisation LocalisationApi { @@ -43,11 +48,6 @@ public static DNNNodeCollection LocaliseDNNNodeCollection(DNNNodeCollection node return (LocalisationApi == null) ? nodes : (LocalisationApi.LocaliseNodes(nodes) ?? nodes); } - public Localiser(int portalId) - { - this.portalId = portalId; - } - public void LocaliseNode(MenuNode node) { var tab = (node.TabId > 0) ? TabController.Instance.GetTab(node.TabId, Null.NullInteger, false) : null; diff --git a/DNN Platform/Modules/DDRMenu/MenuBase.cs b/DNN Platform/Modules/DDRMenu/MenuBase.cs index f71fcd6bdcd..862921f6a49 100644 --- a/DNN Platform/Modules/DDRMenu/MenuBase.cs +++ b/DNN Platform/Modules/DDRMenu/MenuBase.cs @@ -28,6 +28,25 @@ namespace DotNetNuke.Web.DDRMenu public class MenuBase { + private readonly Dictionary nodeSelectorAliases = new Dictionary + { + { "rootonly", "*,0,0" }, + { "rootchildren", "+0" }, + { "currentchildren", "." }, + }; + + private Settings menuSettings; + + private HttpContext currentContext; + + private PortalSettings hostPortalSettings; + + public TemplateDefinition TemplateDef { get; set; } + + internal MenuNode RootNode { get; set; } + + internal bool SkipLocalisation { get; set; } + public static MenuBase Instantiate(string menuStyle) { try @@ -41,34 +60,15 @@ public static MenuBase Instantiate(string menuStyle) } } - private Settings menuSettings; - - internal MenuNode RootNode { get; set; } - - internal bool SkipLocalisation { get; set; } - - public TemplateDefinition TemplateDef { get; set; } - - private HttpContext currentContext; - - private HttpContext CurrentContext - { - get { return this.currentContext ?? (this.currentContext = HttpContext.Current); } - } - - private PortalSettings hostPortalSettings; - internal PortalSettings HostPortalSettings { get { return this.hostPortalSettings ?? (this.hostPortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } } - private readonly Dictionary nodeSelectorAliases = new Dictionary - { - { "rootonly", "*,0,0" }, - { "rootchildren", "+0" }, - { "currentchildren", "." }, - }; + private HttpContext CurrentContext + { + get { return this.currentContext ?? (this.currentContext = HttpContext.Current); } + } internal void ApplySettings(Settings settings) { @@ -142,6 +142,16 @@ internal void Render(HtmlTextWriter htmlWriter) this.TemplateDef.Render(new MenuXml { root = this.RootNode, user = user }, htmlWriter); } + protected string MapPath(string path) + { + return string.IsNullOrEmpty(path) ? string.Empty : Path.GetFullPath(this.CurrentContext.Server.MapPath(path)); + } + + private static List SplitAndTrim(string str) + { + return new List(str.Split(',')).ConvertAll(s => s.Trim().ToLowerInvariant()); + } + private void LoadNodeXml() { this.menuSettings.NodeXmlPath = @@ -164,7 +174,7 @@ private void LoadNodeXml() using (var reader = XmlReader.Create(this.menuSettings.NodeXmlPath)) { reader.ReadToFollowing("root"); - this.RootNode = (MenuNode) new XmlSerializer(typeof(MenuNode), string.Empty).Deserialize(reader); + this.RootNode = (MenuNode)new XmlSerializer(typeof(MenuNode), string.Empty).Deserialize(reader); } cache.Insert(this.menuSettings.NodeXmlPath, this.RootNode, new CacheDependency(this.menuSettings.NodeXmlPath)); @@ -320,10 +330,10 @@ private void ApplyNodeSelector() } } -// ReSharper disable PossibleNullReferenceException + // ReSharper disable PossibleNullReferenceException this.RootNode = new MenuNode(newRoot.Children); -// ReSharper restore PossibleNullReferenceException + // ReSharper restore PossibleNullReferenceException if (selectorSplit.Count > 1) { for (var n = Convert.ToInt32(selectorSplit[1]); n > 0; n--) @@ -366,15 +376,5 @@ private void ApplyNodeManipulator() ((INodeManipulator)Activator.CreateInstance(BuildManager.GetType(this.menuSettings.NodeManipulator, true, true))). ManipulateNodes(this.RootNode.Children, this.HostPortalSettings)); } - - protected string MapPath(string path) - { - return string.IsNullOrEmpty(path) ? string.Empty : Path.GetFullPath(this.CurrentContext.Server.MapPath(path)); - } - - private static List SplitAndTrim(string str) - { - return new List(str.Split(',')).ConvertAll(s => s.Trim().ToLowerInvariant()); - } } } diff --git a/DNN Platform/Modules/DDRMenu/MenuNode.cs b/DNN Platform/Modules/DDRMenu/MenuNode.cs index def5579eb52..5c0877e25fb 100644 --- a/DNN Platform/Modules/DDRMenu/MenuNode.cs +++ b/DNN Platform/Modules/DDRMenu/MenuNode.cs @@ -18,6 +18,29 @@ namespace DotNetNuke.Web.DDRMenu [XmlRoot("root", Namespace = "")] public class MenuNode : IXmlSerializable { + private List _Children; + + public MenuNode() + { + } + + public MenuNode(DNNNodeCollection dnnNodes) + { + this.Children = ConvertDNNNodeCollection(dnnNodes, this); + } + + public MenuNode(List nodes) + { + this.Children = nodes; + this.Children.ForEach(c => c.Parent = this); + } + + public int TabId { get; set; } + + public string Text { get; set; } + + public string Title { get; set; } + public static List ConvertDNNNodeCollection(DNNNodeCollection dnnNodes, MenuNode parent) { var result = new List(); @@ -29,12 +52,6 @@ public static List ConvertDNNNodeCollection(DNNNodeCollection dnnNodes return result; } - public int TabId { get; set; } - - public string Text { get; set; } - - public string Title { get; set; } - public string Url { get; set; } public bool Enabled { get; set; } @@ -85,30 +102,14 @@ public int Depth public string Description { get; set; } - private List _Children; - public List Children { - get { return this._Children ?? (this._Children = new List()); } set { this._Children = value; } + get { return this._Children ?? (this._Children = new List()); } + set { this._Children = value; } } public MenuNode Parent { get; set; } - public MenuNode() - { - } - - public MenuNode(DNNNodeCollection dnnNodes) - { - this.Children = ConvertDNNNodeCollection(dnnNodes, this); - } - - public MenuNode(List nodes) - { - this.Children = nodes; - this.Children.ForEach(c => c.Parent = this); - } - public MenuNode(DNNNode dnnNode, MenuNode parent) { this.TabId = Convert.ToInt32(dnnNode.ID); @@ -220,52 +221,11 @@ public MenuNode FindByNameOrId(string tabNameOrId) return null; } - internal void RemoveAll(List filteredNodes) - { - this.Children.RemoveAll(filteredNodes.Contains); - foreach (var child in this.Children) - { - child.RemoveAll(filteredNodes); - } - } - public bool HasChildren() { return this.Children.Count > 0; } - internal void ApplyContext(string defaultImagePath) - { - this.Icon = this.ApplyContextToImagePath(this.Icon, defaultImagePath); - this.LargeImage = this.ApplyContextToImagePath(this.LargeImage, defaultImagePath); - - if (this.Url != null && this.Url.StartsWith("postback:")) - { - var postbackControl = DNNContext.Current.HostControl; - this.Url = postbackControl.Page.ClientScript.GetPostBackClientHyperlink(postbackControl, this.Url.Substring(9)); - } - - this.Children.ForEach(c => c.ApplyContext(defaultImagePath)); - } - - private string ApplyContextToImagePath(string imagePath, string defaultImagePath) - { - var result = imagePath; - if (!string.IsNullOrEmpty(result)) - { - if (result.StartsWith("~", StringComparison.InvariantCultureIgnoreCase)) - { - result = Globals.ResolveUrl(result); - } - else if (!(result.Contains("://") || result.StartsWith("/"))) - { - result = defaultImagePath + result; - } - } - - return result; - } - public XmlSchema GetSchema() { return null; @@ -321,8 +281,8 @@ public void ReadXml(XmlReader reader) this.Target = reader.Value; break; - // default: - // throw new XmlException(String.Format("Unexpected attribute '{0}'", reader.Name)); + // default: + // throw new XmlException(String.Format("Unexpected attribute '{0}'", reader.Name)); } } while (reader.MoveToNextAttribute()); @@ -365,6 +325,47 @@ public void ReadXml(XmlReader reader) } } + internal void RemoveAll(List filteredNodes) + { + this.Children.RemoveAll(filteredNodes.Contains); + foreach (var child in this.Children) + { + child.RemoveAll(filteredNodes); + } + } + + internal void ApplyContext(string defaultImagePath) + { + this.Icon = this.ApplyContextToImagePath(this.Icon, defaultImagePath); + this.LargeImage = this.ApplyContextToImagePath(this.LargeImage, defaultImagePath); + + if (this.Url != null && this.Url.StartsWith("postback:")) + { + var postbackControl = DNNContext.Current.HostControl; + this.Url = postbackControl.Page.ClientScript.GetPostBackClientHyperlink(postbackControl, this.Url.Substring(9)); + } + + this.Children.ForEach(c => c.ApplyContext(defaultImagePath)); + } + + private string ApplyContextToImagePath(string imagePath, string defaultImagePath) + { + var result = imagePath; + if (!string.IsNullOrEmpty(result)) + { + if (result.StartsWith("~", StringComparison.InvariantCultureIgnoreCase)) + { + result = Globals.ResolveUrl(result); + } + else if (!(result.Contains("://") || result.StartsWith("/"))) + { + result = defaultImagePath + result; + } + } + + return result; + } + public void WriteXml(XmlWriter writer) { if (this.Parent != null) diff --git a/DNN Platform/Modules/DDRMenu/MenuView.ascx.cs b/DNN Platform/Modules/DDRMenu/MenuView.ascx.cs index f1645e360e7..07e38064420 100644 --- a/DNN Platform/Modules/DDRMenu/MenuView.ascx.cs +++ b/DNN Platform/Modules/DDRMenu/MenuView.ascx.cs @@ -32,20 +32,20 @@ protected override void OnPreRender(EventArgs e) } var menuSettings = new Settings - { - MenuStyle = this.GetStringSetting("MenuStyle"), - NodeXmlPath = this.GetStringSetting("NodeXmlPath"), - NodeSelector = this.GetStringSetting("NodeSelector"), - IncludeContext = this.GetBoolSetting("IncludeContext"), - IncludeHidden = this.GetBoolSetting("IncludeHidden"), - IncludeNodes = this.GetStringSetting("IncludeNodes"), - ExcludeNodes = this.GetStringSetting("ExcludeNodes"), - NodeManipulator = this.GetStringSetting("NodeManipulator"), - TemplateArguments = + { + MenuStyle = this.GetStringSetting("MenuStyle"), + NodeXmlPath = this.GetStringSetting("NodeXmlPath"), + NodeSelector = this.GetStringSetting("NodeSelector"), + IncludeContext = this.GetBoolSetting("IncludeContext"), + IncludeHidden = this.GetBoolSetting("IncludeHidden"), + IncludeNodes = this.GetStringSetting("IncludeNodes"), + ExcludeNodes = this.GetStringSetting("ExcludeNodes"), + NodeManipulator = this.GetStringSetting("NodeManipulator"), + TemplateArguments = DDRMenu.Settings.TemplateArgumentsFromSettingString(this.GetStringSetting("TemplateArguments")), - ClientOptions = + ClientOptions = DDRMenu.Settings.ClientOptionsFromSettingString(this.GetStringSetting("ClientOptions")), - }; + }; MenuNode rootNode = null; if (string.IsNullOrEmpty(menuSettings.NodeXmlPath)) diff --git a/DNN Platform/Modules/DDRMenu/MenuXml.cs b/DNN Platform/Modules/DDRMenu/MenuXml.cs index a3f66523137..8062e44a08b 100644 --- a/DNN Platform/Modules/DDRMenu/MenuXml.cs +++ b/DNN Platform/Modules/DDRMenu/MenuXml.cs @@ -13,11 +13,11 @@ namespace DotNetNuke.Web.DDRMenu [XmlRoot("xmlroot", Namespace = "")] public class MenuXml { -// ReSharper disable InconsistentNaming + // ReSharper disable InconsistentNaming public MenuNode root { get; set; } public UserInfo user { get; set; } -// ReSharper restore InconsistentNaming + // ReSharper restore InconsistentNaming } } diff --git a/DNN Platform/Modules/DDRMenu/Settings.cs b/DNN Platform/Modules/DDRMenu/Settings.cs index 62f42ccdd0c..9c91c538144 100644 --- a/DNN Platform/Modules/DDRMenu/Settings.cs +++ b/DNN Platform/Modules/DDRMenu/Settings.cs @@ -14,6 +14,10 @@ namespace DotNetNuke.Web.DDRMenu public class Settings { + private List clientOptions; + + private List templateArguments; + public string MenuStyle { get; set; } public string NodeXmlPath { get; set; } @@ -30,18 +34,16 @@ public class Settings public bool IncludeHidden { get; set; } - private List clientOptions; - public List ClientOptions { - get { return this.clientOptions ?? (this.clientOptions = new List()); } set { this.clientOptions = value; } + get { return this.clientOptions ?? (this.clientOptions = new List()); } + set { this.clientOptions = value; } } - private List templateArguments; - public List TemplateArguments { - get { return this.templateArguments ?? (this.templateArguments = new List()); } set { this.templateArguments = value; } + get { return this.templateArguments ?? (this.templateArguments = new List()); } + set { this.templateArguments = value; } } public static Settings FromXml(string xml) @@ -53,30 +55,6 @@ public static Settings FromXml(string xml) } } - public string ToXml() - { - var sb = new StringBuilder(); - var ser = new XmlSerializer(typeof(Settings)); - using (var writer = new StringWriter(sb)) - { - ser.Serialize(writer, this); - } - - return sb.ToString(); - } - - public override string ToString() - { - try - { - return this.ToXml(); - } - catch (Exception exc) - { - return exc.ToString(); - } - } - public static List ClientOptionsFromSettingString(string s) { var result = new List(); @@ -107,6 +85,30 @@ public static List TemplateArgumentsFromSettingString(string s return result; } + public string ToXml() + { + var sb = new StringBuilder(); + var ser = new XmlSerializer(typeof(Settings)); + using (var writer = new StringWriter(sb)) + { + ser.Serialize(writer, this); + } + + return sb.ToString(); + } + + public override string ToString() + { + try + { + return this.ToXml(); + } + catch (Exception exc) + { + return exc.ToString(); + } + } + public static string ToSettingString(List clientOptions) { return string.Join("\r\n", clientOptions.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); diff --git a/DNN Platform/Modules/DDRMenu/SkinObject.cs b/DNN Platform/Modules/DDRMenu/SkinObject.cs index 386d5518b53..7792d4584ab 100644 --- a/DNN Platform/Modules/DDRMenu/SkinObject.cs +++ b/DNN Platform/Modules/DDRMenu/SkinObject.cs @@ -18,6 +18,8 @@ namespace DotNetNuke.Web.DDRMenu public class SkinObject : SkinObjectBase { + private MenuBase menu; + public string MenuStyle { get; set; } public string NodeXmlPath { get; set; } @@ -42,8 +44,6 @@ public class SkinObject : SkinObjectBase [PersistenceMode(PersistenceMode.InnerProperty)] public List TemplateArguments { get; set; } - private MenuBase menu; - protected override void OnPreRender(EventArgs e) { using (new DNNContext(this)) diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/ClientOption.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/ClientOption.cs index 7803f9e3b29..639fce94018 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/ClientOption.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/ClientOption.cs @@ -11,10 +11,6 @@ namespace DotNetNuke.Web.DDRMenu.TemplateEngine [XmlInclude(typeof(ClientString))] public class ClientOption { - public string Name { get; set; } - - public string Value { get; set; } - public ClientOption() { } @@ -24,6 +20,10 @@ public ClientOption(string name, string value) this.Name = name; this.Value = value; } + + public string Name { get; set; } + + public string Value { get; set; } } public class ClientString : ClientOption diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/RazorTemplateProcessor.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/RazorTemplateProcessor.cs index 50375d86937..f71ef651bab 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/RazorTemplateProcessor.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/RazorTemplateProcessor.cs @@ -33,7 +33,7 @@ public bool LoadDefinition(TemplateDefinition baseDefinition) public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition liveDefinition) { - if (! string.IsNullOrEmpty(liveDefinition.TemplateVirtualPath)) + if (!string.IsNullOrEmpty(liveDefinition.TemplateVirtualPath)) { var resolver = new PathResolver(liveDefinition.Folder); dynamic model = new ExpandoObject(); @@ -50,27 +50,6 @@ public void Render(object source, HtmlTextWriter htmlWriter, TemplateDefinition } } - private StringWriter RenderTemplate(string virtualPath, dynamic model) - { - var page = WebPageBase.CreateInstanceFromVirtualPath(virtualPath); - var httpContext = new HttpContextWrapper(HttpContext.Current); - var pageContext = new WebPageContext(httpContext, page, model); - - var writer = new StringWriter(); - - if (page is WebPage) - { - page.ExecutePageHierarchy(pageContext, writer); - } - else - { - var razorEngine = new RazorEngine(virtualPath, null, null); - razorEngine.Render(writer, model); - } - - return writer; - } - protected static string ConvertToJson(List options) { var result = new StringBuilder(); @@ -108,5 +87,26 @@ protected static string ConvertToJson(List options) result.Append("}"); return result.ToString(); } + + private StringWriter RenderTemplate(string virtualPath, dynamic model) + { + var page = WebPageBase.CreateInstanceFromVirtualPath(virtualPath); + var httpContext = new HttpContextWrapper(HttpContext.Current); + var pageContext = new WebPageContext(httpContext, page, model); + + var writer = new StringWriter(); + + if (page is WebPage) + { + page.ExecutePageHierarchy(pageContext, writer); + } + else + { + var razorEngine = new RazorEngine(virtualPath, null, null); + razorEngine.Render(writer, model); + } + + return writer; + } } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateArgument.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateArgument.cs index ce28f908e57..80bf8bd707c 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateArgument.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateArgument.cs @@ -6,10 +6,6 @@ namespace DotNetNuke.Web.DDRMenu.TemplateEngine { public class TemplateArgument { - public string Name { get; set; } - - public string Value { get; set; } - public TemplateArgument() { } @@ -19,5 +15,9 @@ public TemplateArgument(string name, string value) this.Name = name; this.Value = value; } + + public string Name { get; set; } + + public string Value { get; set; } } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs index b0ebaea5ab1..dd253c12942 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs @@ -22,6 +22,9 @@ namespace DotNetNuke.Web.DDRMenu.TemplateEngine public class TemplateDefinition { + public List ClientOptions = new List(); + public List TemplateArguments = new List(); + internal string Folder; internal string TemplatePath; internal string TemplateVirtualPath; @@ -35,14 +38,22 @@ public class TemplateDefinition internal readonly List DefaultTemplateArguments = new List(); internal ITemplateProcessor Processor; - public List ClientOptions = new List(); - public List TemplateArguments = new List(); - private static readonly Regex RegexLinks = new Regex( "( (href|src)=['\"]?)(?!http:|ftp:|mailto:|file:|javascript:|/)([^'\">]+['\">])", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + public TemplateDefinition Clone() + { + return (TemplateDefinition)this.MemberwiseClone(); + } + + public void Reset() + { + this.ClientOptions = new List(this.DefaultClientOptions); + this.TemplateArguments = new List(this.DefaultTemplateArguments); + } + internal static TemplateDefinition FromName(string templateName, string manifestName) { var manifestUrl = new PathResolver(null).Resolve( @@ -74,7 +85,7 @@ internal static TemplateDefinition FromManifest(string manifestUrl) // ReSharper disable PossibleNullReferenceException foreach (XmlNode node in xml.DocumentElement.ChildNodes) - // ReSharper restore PossibleNullReferenceException + // ReSharper restore PossibleNullReferenceException { if (node.NodeType == XmlNodeType.Element) { @@ -285,17 +296,6 @@ private static string GetObjectCheckScript(string jsObject) return string.Join(" && ", objectsToCheck.ToArray()); } - public TemplateDefinition Clone() - { - return (TemplateDefinition)this.MemberwiseClone(); - } - - public void Reset() - { - this.ClientOptions = new List(this.DefaultClientOptions); - this.TemplateArguments = new List(this.DefaultTemplateArguments); - } - public void AddClientOptions(List options, bool replace) { if (options != null) diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs index 852a2f7db8e..039b8a02d35 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs @@ -18,15 +18,15 @@ namespace DotNetNuke.Web.DDRMenu.TemplateEngine public class TokenTemplateProcessor : ITemplateProcessor { - private XslCompiledTransform xsl; private static readonly Dictionary aliases = new Dictionary { { "page", "node" }, { "name", "text" } }; - private static readonly Regex TemplatesRegex = new Regex( @"(\[(?(\*|\*\>|\/\*|\>|\/\>|\?|\?!|\/\?|\=))(?[A-Z]*)(-(?[0-9A-Z]*))?\])", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private XslCompiledTransform xsl; + public bool LoadDefinition(TemplateDefinition baseDefinition) { if (!baseDefinition.TemplateVirtualPath.EndsWith(".txt", StringComparison.InvariantCultureIgnoreCase)) @@ -52,7 +52,7 @@ public bool LoadDefinition(TemplateDefinition baseDefinition) validParams.AddRange(new[] { "controlid", "options", "dnnpath", "manifestpath", "portalpath", "skinpath" }); var docElt = xml.DocumentElement; - var outputElt = (XmlElement) docElt.GetElementsByTagName("output", xmlNs)[0]; + var outputElt = (XmlElement)docElt.GetElementsByTagName("output", xmlNs)[0]; foreach (var param in validParams) { var elt = xml.CreateElement("param", xmlNs); @@ -60,7 +60,7 @@ public bool LoadDefinition(TemplateDefinition baseDefinition) docElt.InsertAfter(elt, outputElt); } - var current = (XmlElement) docElt.GetElementsByTagName("template", xmlNs)[1]; + var current = (XmlElement)docElt.GetElementsByTagName("template", xmlNs)[1]; var stack = new Stack(); var index = 0; diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltFunctions.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltFunctions.cs index ab62f7e5906..46a80ab8c9e 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltFunctions.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/XsltFunctions.cs @@ -59,7 +59,7 @@ public string GetUserText() (HttpContext.Current.Items["DDRMenuHostControl"] as Control).ResolveUrl( "~/Admin/Skins/" + Localization.LocalResourceDirectory + "/User.ascx")); -// ReSharper restore PossibleNullReferenceException + // ReSharper restore PossibleNullReferenceException } catch (Exception exc) { diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs index 500accebd96..ba6b3ccbd3a 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs @@ -49,6 +49,34 @@ private static bool IsHostMenu return Globals.IsHostTab(PortalSettings.Current.ActiveTab.TabID); } } + + public IEnumerable GetDefaultFolderProviderValues(int moduleId) + { + var portalId = this.GetCurrentPortalId(moduleId); + + return new List + { + FolderMappingController.Instance.GetFolderMapping(portalId, "Standard"), + FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"), + FolderMappingController.Instance.GetFolderMapping(portalId, "Database"), + }; + } + + public int? GetDefaultFolderTypeId(int moduleId) + { + if (PortalSettings.Current.UserInfo.IsSuperUser && SettingsRepository.GetMode(moduleId) == DigitalAssestsMode.User) + { + return null; + } + + var folderTypeId = SettingsRepository.GetDefaultFolderTypeId(moduleId); + if (!folderTypeId.HasValue) + { + folderTypeId = FolderMappingController.Instance.GetDefaultFolderMapping(this.GetCurrentPortalId(moduleId)).FolderMappingID; + } + + return folderTypeId; + } private static string GetFileIconUrl(string extension) { @@ -222,34 +250,6 @@ private string GetUnlinkAllowedStatus(IFolderInfo folder) return "false"; } - public IEnumerable GetDefaultFolderProviderValues(int moduleId) - { - var portalId = this.GetCurrentPortalId(moduleId); - - return new List - { - FolderMappingController.Instance.GetFolderMapping(portalId, "Standard"), - FolderMappingController.Instance.GetFolderMapping(portalId, "Secure"), - FolderMappingController.Instance.GetFolderMapping(portalId, "Database"), - }; - } - - public int? GetDefaultFolderTypeId(int moduleId) - { - if (PortalSettings.Current.UserInfo.IsSuperUser && SettingsRepository.GetMode(moduleId) == DigitalAssestsMode.User) - { - return null; - } - - var folderTypeId = SettingsRepository.GetDefaultFolderTypeId(moduleId); - if (!folderTypeId.HasValue) - { - folderTypeId = FolderMappingController.Instance.GetDefaultFolderMapping(this.GetCurrentPortalId(moduleId)).FolderMappingID; - } - - return folderTypeId; - } - public int GetCurrentPortalId(int moduleId) { if (PortalSettings.Current.UserInfo.IsSuperUser) @@ -367,6 +367,18 @@ public FolderViewModel GetGroupFolder(int groupId, PortalSettings portalSettings return folderViewModel; } + public FolderViewModel GetUserFolder(UserInfo userInfo) + { + var folder = this.GetFolderViewModel(FolderManager.Instance.GetUserFolder(userInfo)); + folder.FolderName = LocalizationHelper.GetString("MyFolder"); + return folder; + } + + public FolderViewModel CreateFolder(string folderName, int folderParentID, int folderMappingID, string mappedPath) + { + return this.GetFolderViewModel(AssetManager.Instance.CreateFolder(folderName, folderParentID, folderMappingID, mappedPath)); + } + private IFolderInfo EnsureGroupFolder(int groupId, PortalSettings portalSettings) { const int AllUsersRoleId = -1; @@ -403,18 +415,6 @@ private IFolderInfo EnsureGroupFolder(int groupId, PortalSettings portalSettings return FolderManager.Instance.GetFolder(portalSettings.PortalId, groupFolderPath); } - public FolderViewModel GetUserFolder(UserInfo userInfo) - { - var folder = this.GetFolderViewModel(FolderManager.Instance.GetUserFolder(userInfo)); - folder.FolderName = LocalizationHelper.GetString("MyFolder"); - return folder; - } - - public FolderViewModel CreateFolder(string folderName, int folderParentID, int folderMappingID, string mappedPath) - { - return this.GetFolderViewModel(AssetManager.Instance.CreateFolder(folderName, folderParentID, folderMappingID, mappedPath)); - } - public ItemViewModel GetFile(int fileID) { return this.GetItemViewModel(FileManager.Instance.GetFile(fileID, true)); @@ -496,11 +496,11 @@ public Stream GetFileContent(int fileId, out string fileName, out string content fileName = file.FileName; contentType = file.ContentType; - EventManager.Instance.OnFileDownloaded(new FileDownloadedEventArgs() - { - FileInfo = file, - UserId = UserController.Instance.GetCurrentUserInfo().UserID, - }); + EventManager.Instance.OnFileDownloaded(new FileDownloadedEventArgs() + { + FileInfo = file, + UserId = UserController.Instance.GetCurrentUserInfo().UserID, + }); return content; } @@ -662,6 +662,57 @@ public bool HasPermission(IFolderInfo folder, string permissionKey) return hasPermision; } + + public string UpgradeModule(string version) + { + try + { + switch (version) + { + case "07.01.00": + ModuleDefinitionInfo mDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Digital Asset Management"); + + // Add tab to Admin Menu + if (mDef != null) + { + var hostPage = Upgrade.AddHostPage( + "File Management", + "Manage assets.", + "~/Icons/Sigma/Files_16X16_Standard.png", + "~/Icons/Sigma/Files_32X32_Standard.png", + true); + + // Add module to page + Upgrade.AddModuleToPage(hostPage, mDef.ModuleDefID, "File Management", "~/Icons/Sigma/Files_32X32_Standard.png", true); + + Upgrade.AddAdminPages( + "File Management", + "Manage assets within the portal", + "~/Icons/Sigma/Files_16X16_Standard.png", + "~/Icons/Sigma/Files_32X32_Standard.png", + true, + mDef.ModuleDefID, + "File Management", + "~/Icons/Sigma/Files_16X16_Standard.png", + true); + } + + // Remove Host File Manager page + Upgrade.RemoveHostPage("File Manager"); + + // Remove Admin File Manager Pages + Upgrade.RemoveAdminPages("//Admin//FileManager"); + + break; + } + + return "Success"; + } + catch (Exception) + { + return "Failed"; + } + } protected ItemPathViewModel GetItemPathViewModel(IFolderInfo folder) { @@ -707,18 +758,6 @@ protected virtual FolderViewModel GetFolderViewModel(IFolderInfo folder) return folderViewModel; } - private ItemViewModel GetItemViewModel(object item) - { - var folder = item as IFolderInfo; - if (folder != null) - { - return this.GetItemViewModel(folder); - } - - var file = item as IFileInfo; - return this.GetItemViewModel(file); - } - protected virtual ItemViewModel GetItemViewModel(IFolderInfo folder) { var parentFolderId = Null.NullInteger; @@ -766,6 +805,18 @@ protected virtual ItemViewModel GetItemViewModel(IFileInfo file) }; } + private ItemViewModel GetItemViewModel(object item) + { + var folder = item as IFolderInfo; + if (folder != null) + { + return this.GetItemViewModel(folder); + } + + var file = item as IFileInfo; + return this.GetItemViewModel(file); + } + protected string GetFolderIconUrl(int portalId, int folderMappingID) { var imageUrl = IconController.IconURL("ExtClosedFolder", "32x32", "Standard"); @@ -778,56 +829,5 @@ protected string GetFolderIconUrl(int portalId, int folderMappingID) return imageUrl; } - - public string UpgradeModule(string version) - { - try - { - switch (version) - { - case "07.01.00": - ModuleDefinitionInfo mDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Digital Asset Management"); - - // Add tab to Admin Menu - if (mDef != null) - { - var hostPage = Upgrade.AddHostPage( - "File Management", - "Manage assets.", - "~/Icons/Sigma/Files_16X16_Standard.png", - "~/Icons/Sigma/Files_32X32_Standard.png", - true); - - // Add module to page - Upgrade.AddModuleToPage(hostPage, mDef.ModuleDefID, "File Management", "~/Icons/Sigma/Files_32X32_Standard.png", true); - - Upgrade.AddAdminPages( - "File Management", - "Manage assets within the portal", - "~/Icons/Sigma/Files_16X16_Standard.png", - "~/Icons/Sigma/Files_32X32_Standard.png", - true, - mDef.ModuleDefID, - "File Management", - "~/Icons/Sigma/Files_16X16_Standard.png", - true); - } - - // Remove Host File Manager page - Upgrade.RemoveHostPage("File Manager"); - - // Remove Admin File Manager Pages - Upgrade.RemoveAdminPages("//Admin//FileManager"); - - break; - } - - return "Success"; - } - catch (Exception) - { - return "Failed"; - } - } } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs index f67480d6e33..0e82983c477 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs @@ -10,6 +10,19 @@ namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Services.Assets; + + public enum DigitalAssestsMode + { + Normal, + Group, + User, + } + + public enum FilterCondition + { + NotSet, + FilterByFolder, + } public class DigitalAssetsSettingsRepository { @@ -56,18 +69,6 @@ public DigitalAssestsMode GetMode(int moduleId) return mode; } - private bool IsGroupMode(int moduleId) - { - var groupMode = this.GetSettingByKey(moduleId, GroupModeSetting); - - if (string.IsNullOrEmpty(groupMode)) - { - return false; - } - - return Convert.ToBoolean(groupMode); - } - public FilterCondition GetFilterCondition(int moduleId) { var setting = this.GetSettingByKey(moduleId, FilterConditionSetting); @@ -82,6 +83,18 @@ public SubfolderFilter GetSubfolderFilter(int moduleId) return !Enum.TryParse(setting, true, out excludeSubfolders) ? SubfolderFilter.IncludeSubfoldersFolderStructure : excludeSubfolders; } + private bool IsGroupMode(int moduleId) + { + var groupMode = this.GetSettingByKey(moduleId, GroupModeSetting); + + if (string.IsNullOrEmpty(groupMode)) + { + return false; + } + + return Convert.ToBoolean(groupMode); + } + public void SaveDefaultFolderTypeId(int moduleId, int defaultFolderTypeId) { ModuleController.Instance.UpdateModuleSetting(moduleId, DefaultFolderTypeIdSetting, defaultFolderTypeId.ToString(CultureInfo.InvariantCulture)); @@ -107,13 +120,6 @@ public void SaveFilterCondition(int moduleId, FilterCondition filterCondition) ModuleController.Instance.UpdateModuleSetting(moduleId, FilterConditionSetting, filterCondition.ToString()); } - private string GetSettingByKey(int moduleId, string key) - { - var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); - var moduleSettings = module.ModuleSettings; - return (string)moduleSettings[key]; - } - internal bool SettingExists(int moduleId, string settingName) { return !string.IsNullOrEmpty(this.GetSettingByKey(moduleId, settingName)); @@ -127,18 +133,12 @@ internal void SetDefaultFilterCondition(int moduleId) this.SaveFilterCondition(moduleId, FilterCondition.FilterByFolder); } } - } - public enum DigitalAssestsMode - { - Normal, - Group, - User, - } - - public enum FilterCondition - { - NotSet, - FilterByFolder, + private string GetSettingByKey(int moduleId, string key) + { + var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); + var moduleSettings = module.ModuleSettings; + return (string)moduleSettings[key]; + } } } diff --git a/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs b/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs index 87209b713f9..0250971fc19 100644 --- a/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs @@ -22,14 +22,14 @@ public partial class EditFolderMapping : PortalModuleBase { private readonly INavigationManager _navigationManager; + private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; + private int _folderMappingID = Null.NullInteger; + public EditFolderMapping() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; - private int _folderMappingID = Null.NullInteger; - public int FolderPortalID { get @@ -107,6 +107,11 @@ protected override void OnLoad(EventArgs e) } } + protected void cboFolderProviders_SelectedIndexChanged(object sender, EventArgs e) + { + this.BindFolderMappingSettings(); + } + private void cmdUpdate_Click(object sender, EventArgs e) { this.Page.Validate("vgEditFolderMapping"); @@ -197,11 +202,6 @@ private void cmdUpdate_Click(object sender, EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - - protected void cboFolderProviders_SelectedIndexChanged(object sender, EventArgs e) - { - this.BindFolderMappingSettings(); - } private void BindFolderProviders() { diff --git a/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs index 1205ce24d6c..182d69904f2 100644 --- a/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs @@ -18,6 +18,12 @@ namespace DotNetNuke.Modules.DigitalAssets public partial class FileFieldsControl : PortalModuleBase, IFieldsControl { + public IDigitalAssetsController Controller { get; private set; } + + public ItemViewModel Item { get; private set; } + + protected IFileInfo File { get; private set; } + public virtual void PrepareProperties() { this.FileNameInput.Text = this.Item.ItemName; @@ -43,11 +49,15 @@ private FileAttributes GetFileAttributesUpdated(FileAttributes? attributes) return result.Value; } - public IDigitalAssetsController Controller { get; private set; } - - public ItemViewModel Item { get; private set; } + public void SetController(IDigitalAssetsController damController) + { + this.Controller = damController; + } - protected IFileInfo File { get; private set; } + public void SetModuleConfiguration(ModuleInfo moduleConfiguration) + { + this.ModuleConfiguration = moduleConfiguration; + } protected override void OnInit(EventArgs e) { @@ -70,16 +80,6 @@ protected override void OnLoad(EventArgs e) } } - public void SetController(IDigitalAssetsController damController) - { - this.Controller = damController; - } - - public void SetModuleConfiguration(ModuleInfo moduleConfiguration) - { - this.ModuleConfiguration = moduleConfiguration; - } - public void SetItemViewModel(ItemViewModel itemViewModel) { this.Item = itemViewModel; diff --git a/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs b/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs index 4bb776cf3e1..488ffc601ea 100644 --- a/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs @@ -26,13 +26,13 @@ public partial class FolderMappings : PortalModuleBase { private readonly INavigationManager _navigationManager; + private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; + public FolderMappings() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; - public int FolderPortalID { get diff --git a/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs b/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs index 8198179a52e..ab39be08eb3 100644 --- a/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs @@ -130,6 +130,38 @@ protected override void OnInit(EventArgs e) } } + protected override void OnLoad(EventArgs e) + { + try + { + if (!this.Page.IsPostBack) + { + this.SetupPermissionGrid(); + this.PrepareFolderProperties(); + this.SetPropertiesAvailability(FolderPermissionController.CanManageFolder((FolderInfo)this.Folder)); + } + + if (!FolderPermissionController.CanViewFolder((FolderInfo)this.Folder)) + { + this.SaveButton.Visible = false; + this.SetPropertiesVisibility(false); + UI.Skins.Skin.AddModuleMessage(this, this.LocalizeString("UserCannotReadFolderError"), ModuleMessage.ModuleMessageType.RedError); + } + else + { + this.SaveButton.Visible = FolderPermissionController.CanViewFolder((FolderInfo)this.Folder) && FolderPermissionController.CanManageFolder((FolderInfo)this.Folder); + } + } + catch (DotNetNukeException dnnex) + { + UI.Skins.Skin.AddModuleMessage(this, dnnex.Message, ModuleMessage.ModuleMessageType.RedError); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private void OnSaveClick(object sender, EventArgs e) { try @@ -209,38 +241,6 @@ private void cmdCopyPerm_Click(object sender, EventArgs e) } } - protected override void OnLoad(EventArgs e) - { - try - { - if (!this.Page.IsPostBack) - { - this.SetupPermissionGrid(); - this.PrepareFolderProperties(); - this.SetPropertiesAvailability(FolderPermissionController.CanManageFolder((FolderInfo)this.Folder)); - } - - if (!FolderPermissionController.CanViewFolder((FolderInfo)this.Folder)) - { - this.SaveButton.Visible = false; - this.SetPropertiesVisibility(false); - UI.Skins.Skin.AddModuleMessage(this, this.LocalizeString("UserCannotReadFolderError"), ModuleMessage.ModuleMessageType.RedError); - } - else - { - this.SaveButton.Visible = FolderPermissionController.CanViewFolder((FolderInfo)this.Folder) && FolderPermissionController.CanManageFolder((FolderInfo)this.Folder); - } - } - catch (DotNetNukeException dnnex) - { - UI.Skins.Skin.AddModuleMessage(this, dnnex.Message, ModuleMessage.ModuleMessageType.RedError); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - private void SetPropertiesAvailability(bool availability) { this.FolderNameInput.Enabled = (!this.isRootFolder) && availability; diff --git a/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs index 958915ce25d..d6d31b4ea50 100644 --- a/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs @@ -13,6 +13,8 @@ namespace DotNetNuke.Modules.DigitalAssets public partial class PreviewFieldsControl : UserControl { + public List Fields { get; set; } + public void GenerateFieldsTable() { this.FieldsTable.Rows.Clear(); @@ -24,7 +26,5 @@ public void GenerateFieldsTable() this.FieldsTable.Rows.Add(rowField); } } - - public List Fields { get; set; } } } diff --git a/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs b/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs index 0f446d61b56..110e72cc3f1 100644 --- a/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs @@ -40,11 +40,6 @@ private FilterCondition SelectedFilterCondition } } - protected override void OnInit(EventArgs e) - { - ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.FilterViewSettings.js", FileOrder.Js.DefaultPriority); - } - /// ----------------------------------------------------------------------------- /// /// LoadSettings loads the settings from the Database and displays them. @@ -105,6 +100,11 @@ public override void UpdateSettings() } } + protected override void OnInit(EventArgs e) + { + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.FilterViewSettings.js", FileOrder.Js.DefaultPriority); + } + protected void ValidateFolderIsSelected(object source, ServerValidateEventArgs args) { if (this.SelectedFilterCondition == FilterCondition.FilterByFolder && this.FilterByFolderDropDownList.SelectedFolder == null) diff --git a/DNN Platform/Modules/DigitalAssets/View.ascx.cs b/DNN Platform/Modules/DigitalAssets/View.ascx.cs index c1369fc410f..c86396010b0 100644 --- a/DNN Platform/Modules/DigitalAssets/View.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/View.ascx.cs @@ -56,29 +56,28 @@ public View() this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private IExtensionPointFilter Filter + public ModuleActionCollection ModuleActions { get { - return new CompositeFilter() - .And(new FilterByHostMenu(this.IsHostPortal)) - .And(new FilterByUnauthenticated(HttpContext.Current.Request.IsAuthenticated)); - } - } + var actions = new ModuleActionCollection(); + if (ModulePermissionController.CanManageModule(this.ModuleConfiguration)) + { + actions.Add(this.GetNextActionID(), Localization.GetString("ManageFolderTypes", this.LocalResourceFile), string.Empty, string.Empty, "../DesktopModules/DigitalAssets/Images/manageFolderTypes.png", this.EditUrl("FolderMappings"), false, SecurityAccessLevel.Edit, true, false); - private NameValueCollection DAMState - { - get - { - if (this.damState == null) + foreach (var item in this.epm.GetMenuItemExtensionPoints("DigitalAssets", "ModuleActions", this.Filter)) + { + actions.Add(this.GetNextActionID(), item.Text, string.Empty, string.Empty, item.Icon, this.EditUrl(item.Value), false, SecurityAccessLevel.Edit, true, false); + } + } + else { - var stateCookie = this.Request.Cookies["damState-" + this.UserId]; - this.damState = HttpUtility.ParseQueryString(Uri.UnescapeDataString(stateCookie != null ? stateCookie.Value : string.Empty)); + actions = new ModuleActionCollection(); } - return this.damState; + return actions; } - } + } protected int InitialTab { @@ -96,6 +95,30 @@ protected bool IsHostPortal } } + private IExtensionPointFilter Filter + { + get + { + return new CompositeFilter() + .And(new FilterByHostMenu(this.IsHostPortal)) + .And(new FilterByUnauthenticated(HttpContext.Current.Request.IsAuthenticated)); + } + } + + private NameValueCollection DAMState + { + get + { + if (this.damState == null) + { + var stateCookie = this.Request.Cookies["damState-" + this.UserId]; + this.damState = HttpUtility.ParseQueryString(Uri.UnescapeDataString(stateCookie != null ? stateCookie.Value : string.Empty)); + } + + return this.damState; + } + } + protected string InvalidCharacters { get @@ -163,6 +186,125 @@ protected bool FilteredContent protected string ActiveView { get; private set; } + protected FolderViewModel RootFolderViewModel { get; private set; } + + protected override void OnLoad(EventArgs e) + { + try + { + base.OnLoad(e); + + // if (IsPostBack) return; + switch (SettingsRepository.GetMode(this.ModuleId)) + { + case DigitalAssestsMode.Group: + int groupId; + if (string.IsNullOrEmpty(this.Request["groupId"]) || !int.TryParse(this.Request["groupId"], out groupId)) + { + Skin.AddModuleMessage(this, Localization.GetString("InvalidGroup.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + return; + } + + var groupFolder = this.controller.GetGroupFolder(groupId, this.PortalSettings); + if (groupFolder == null) + { + Skin.AddModuleMessage(this, Localization.GetString("InvalidGroup.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + return; + } + + this.RootFolderViewModel = groupFolder; + break; + + case DigitalAssestsMode.User: + if (this.PortalSettings.UserId == Null.NullInteger) + { + Skin.AddModuleMessage(this, Localization.GetString("InvalidUser.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + return; + } + + this.RootFolderViewModel = this.controller.GetUserFolder(this.PortalSettings.UserInfo); + break; + + default: + // handle upgrades where FilterCondition didn't exist + SettingsRepository.SetDefaultFilterCondition(this.ModuleId); + this.RootFolderViewModel = this.controller.GetRootFolder(this.ModuleId); + break; + } + + var initialPath = string.Empty; + int folderId; + if (int.TryParse(this.Request["folderId"] ?? this.DAMState["folderId"], out folderId)) + { + var folder = FolderManager.Instance.GetFolder(folderId); + if (folder != null && folder.FolderPath.StartsWith(this.RootFolderViewModel.FolderPath)) + { + initialPath = PathUtils.Instance.RemoveTrailingSlash(folder.FolderPath.Substring(this.RootFolderViewModel.FolderPath.Length)); + } + } + + this.PageSize = this.Request["pageSize"] ?? this.DAMState["pageSize"] ?? "10"; + this.ActiveView = this.Request["view"] ?? this.DAMState["view"] ?? "gridview"; + + this.Page.DataBind(); + this.InitializeTreeViews(initialPath); + this.InitializeSearchBox(); + this.InitializeFolderType(); + this.InitializeGridContextMenu(); + this.InitializeEmptySpaceContextMenu(); + + this.FolderNameRegExValidator.ErrorMessage = this.controller.GetInvalidCharsErrorText(); + this.FolderNameRegExValidator.ValidationExpression = "^([^" + Regex.Escape(this.controller.GetInvalidChars()) + "]+)$"; + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected override void OnInit(EventArgs e) + { + try + { + base.OnInit(e); + + this.fileUpload.ModuleId = this.ModuleId; + this.fileUpload.Options.Parameters.Add("isHostPortal", this.IsHostPortal ? "true" : "false"); + + ServicesFramework.Instance.RequestAjaxScriptSupport(); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + + // register the telerik core js manually + var telerikCoreJs = this.Page.ClientScript.GetWebResourceUrl(typeof(RadGrid), "Telerik.Web.UI.Common.Core.js"); + ClientResourceManager.RegisterScript(this.Page, telerikCoreJs, FileOrder.Js.jQuery + 3); + + var popupFilePath = HttpContext.Current.IsDebuggingEnabled + ? "~/js/Debug/dnn.modalpopup.js" + : "~/js/dnn.modalpopup.js"; + ClientResourceManager.RegisterScript(this.Page, popupFilePath, FileOrder.Js.DnnModalPopup); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssetsController.js", FileOrder.Js.DefaultPriority); + + var i = 1; + foreach (var script in this.epm.GetScriptItemExtensionPoints("DigitalAssets")) + { + ClientResourceManager.RegisterScript(this.Page, script.ScriptName, FileOrder.Js.DefaultPriority + i++); + } + + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.js", FileOrder.Js.DefaultPriority + i); + + this.InitializeGrid(); + this.FolderTypeComboBox.ItemDataBound += this.OnItemDataBoundFolderTypeComboBox; + + this.MainToolBar.ModuleContext = this.ModuleContext; + this.SelectionToolBar.ModuleContext = this.ModuleContext; + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private static string GetNoControlCharsString(string text) { var result = new StringBuilder(); @@ -190,16 +332,16 @@ private void InitializeGrid() foreach (var columnExtension in this.epm.GetGridColumnExtensionPoints("DigitalAssets", "GridColumns", this.Filter)) { - var column = new DnnGridBoundColumn - { - HeaderText = columnExtension.HeaderText, - DataField = columnExtension.DataField, - UniqueName = columnExtension.UniqueName, - ReadOnly = columnExtension.ReadOnly, - Reorderable = columnExtension.Reorderable, - SortExpression = columnExtension.SortExpression, - HeaderTooltip = columnExtension.HeaderText, - }; + var column = new DnnGridBoundColumn + { + HeaderText = columnExtension.HeaderText, + DataField = columnExtension.DataField, + UniqueName = columnExtension.UniqueName, + ReadOnly = columnExtension.ReadOnly, + Reorderable = columnExtension.Reorderable, + SortExpression = columnExtension.SortExpression, + HeaderTooltip = columnExtension.HeaderText, + }; column.HeaderStyle.Width = columnExtension.HeaderStyleWidth; var index = Math.Min(columnExtension.ColumnAt, this.Grid.Columns.Count - 1); @@ -449,13 +591,13 @@ private void InitializeGridContextMenu() // Dnn Menu Item Extension Point foreach (var menuItem in this.epm.GetMenuItemExtensionPoints("DigitalAssets", "GridContextMenu", this.Filter)) { - this.GridMenu.Items.Add(new DnnMenuItem - { - Text = menuItem.Text, - Value = menuItem.Value, - CssClass = menuItem.CssClass, - ImageUrl = menuItem.Icon, - }); + this.GridMenu.Items.Add(new DnnMenuItem + { + Text = menuItem.Text, + Value = menuItem.Value, + CssClass = menuItem.CssClass, + ImageUrl = menuItem.Icon, + }); } } @@ -520,148 +662,6 @@ private void OnItemDataBoundFolderTypeComboBox(object sender, RadComboBoxItemEve var dataSource = (FolderMappingViewModel)e.Item.DataItem; e.Item.Attributes["SupportsMappedPaths"] = FolderProvider.GetProviderList()[dataSource.FolderTypeName].SupportsMappedPaths.ToString().ToLowerInvariant(); } - - protected FolderViewModel RootFolderViewModel { get; private set; } - - protected override void OnLoad(EventArgs e) - { - try - { - base.OnLoad(e); - - // if (IsPostBack) return; - switch (SettingsRepository.GetMode(this.ModuleId)) - { - case DigitalAssestsMode.Group: - int groupId; - if (string.IsNullOrEmpty(this.Request["groupId"]) || !int.TryParse(this.Request["groupId"], out groupId)) - { - Skin.AddModuleMessage(this, Localization.GetString("InvalidGroup.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - return; - } - - var groupFolder = this.controller.GetGroupFolder(groupId, this.PortalSettings); - if (groupFolder == null) - { - Skin.AddModuleMessage(this, Localization.GetString("InvalidGroup.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - return; - } - - this.RootFolderViewModel = groupFolder; - break; - - case DigitalAssestsMode.User: - if (this.PortalSettings.UserId == Null.NullInteger) - { - Skin.AddModuleMessage(this, Localization.GetString("InvalidUser.Error", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - return; - } - - this.RootFolderViewModel = this.controller.GetUserFolder(this.PortalSettings.UserInfo); - break; - - default: - // handle upgrades where FilterCondition didn't exist - SettingsRepository.SetDefaultFilterCondition(this.ModuleId); - this.RootFolderViewModel = this.controller.GetRootFolder(this.ModuleId); - break; - } - - var initialPath = string.Empty; - int folderId; - if (int.TryParse(this.Request["folderId"] ?? this.DAMState["folderId"], out folderId)) - { - var folder = FolderManager.Instance.GetFolder(folderId); - if (folder != null && folder.FolderPath.StartsWith(this.RootFolderViewModel.FolderPath)) - { - initialPath = PathUtils.Instance.RemoveTrailingSlash(folder.FolderPath.Substring(this.RootFolderViewModel.FolderPath.Length)); - } - } - - this.PageSize = this.Request["pageSize"] ?? this.DAMState["pageSize"] ?? "10"; - this.ActiveView = this.Request["view"] ?? this.DAMState["view"] ?? "gridview"; - - this.Page.DataBind(); - this.InitializeTreeViews(initialPath); - this.InitializeSearchBox(); - this.InitializeFolderType(); - this.InitializeGridContextMenu(); - this.InitializeEmptySpaceContextMenu(); - - this.FolderNameRegExValidator.ErrorMessage = this.controller.GetInvalidCharsErrorText(); - this.FolderNameRegExValidator.ValidationExpression = "^([^" + Regex.Escape(this.controller.GetInvalidChars()) + "]+)$"; - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected override void OnInit(EventArgs e) - { - try - { - base.OnInit(e); - - this.fileUpload.ModuleId = this.ModuleId; - this.fileUpload.Options.Parameters.Add("isHostPortal", this.IsHostPortal ? "true" : "false"); - - ServicesFramework.Instance.RequestAjaxScriptSupport(); - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - - // register the telerik core js manually - var telerikCoreJs = this.Page.ClientScript.GetWebResourceUrl(typeof(RadGrid), "Telerik.Web.UI.Common.Core.js"); - ClientResourceManager.RegisterScript(this.Page, telerikCoreJs, FileOrder.Js.jQuery + 3); - - var popupFilePath = HttpContext.Current.IsDebuggingEnabled - ? "~/js/Debug/dnn.modalpopup.js" - : "~/js/dnn.modalpopup.js"; - ClientResourceManager.RegisterScript(this.Page, popupFilePath, FileOrder.Js.DnnModalPopup); - ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssetsController.js", FileOrder.Js.DefaultPriority); - - var i = 1; - foreach (var script in this.epm.GetScriptItemExtensionPoints("DigitalAssets")) - { - ClientResourceManager.RegisterScript(this.Page, script.ScriptName, FileOrder.Js.DefaultPriority + i++); - } - - ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/DigitalAssets/ClientScripts/dnn.DigitalAssets.js", FileOrder.Js.DefaultPriority + i); - - this.InitializeGrid(); - this.FolderTypeComboBox.ItemDataBound += this.OnItemDataBoundFolderTypeComboBox; - - this.MainToolBar.ModuleContext = this.ModuleContext; - this.SelectionToolBar.ModuleContext = this.ModuleContext; - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - public ModuleActionCollection ModuleActions - { - get - { - var actions = new ModuleActionCollection(); - if (ModulePermissionController.CanManageModule(this.ModuleConfiguration)) - { - actions.Add(this.GetNextActionID(), Localization.GetString("ManageFolderTypes", this.LocalResourceFile), string.Empty, string.Empty, "../DesktopModules/DigitalAssets/Images/manageFolderTypes.png", this.EditUrl("FolderMappings"), false, SecurityAccessLevel.Edit, true, false); - - foreach (var item in this.epm.GetMenuItemExtensionPoints("DigitalAssets", "ModuleActions", this.Filter)) - { - actions.Add(this.GetNextActionID(), item.Text, string.Empty, string.Empty, item.Icon, this.EditUrl(item.Value), false, SecurityAccessLevel.Edit, true, false); - } - } - else - { - actions = new ModuleActionCollection(); - } - - return actions; - } - } protected void GridOnItemCreated(object sender, GridItemEventArgs e) { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs index ff9ce869d6c..bd120ad62d8 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs @@ -15,6 +15,10 @@ public class Constants /// public const string CurrentSchemaVersion = "1.0.2"; + // these are set by the API caller + public const string Category_Users = "USERS"; + public const string Category_Vocabularies = "VOCABULARIES"; + internal const string ExportFolder = @"\App_Data\ExportImport\"; internal const string ExportManifestName = "export.json"; // export manifest file name internal const string ExportDbName = "export.dnndb"; // export database file name @@ -36,15 +40,11 @@ public class Constants internal const int LogColumnLength = 255; + internal const string SharedResources = "/DesktopModules/SiteExportImport/App_LocalResources/ExportImport.resx"; + internal static DateTime MinDbTime = new DateTime(1980, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal static DateTime MaxDbTime = new DateTime(3000, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal static int MaxZipFilesMemory = 104857600; // 100 MB - - internal const string SharedResources = "/DesktopModules/SiteExportImport/App_LocalResources/ExportImport.resx"; - - // these are set by the API caller - public const string Category_Users = "USERS"; - public const string Category_Vocabularies = "VOCABULARIES"; public const string Category_Roles = "ROLES"; public const string Category_ProfileProps = "PROFILE_PROPERTIES"; public const string Category_Content = "CONTENT"; diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs index 6ac000100a6..ac48ae0c359 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs @@ -26,9 +26,9 @@ namespace Dnn.ExportImport.Components.Controllers public class BaseController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BaseController)); - public static readonly string ExportFolder; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BaseController)); static BaseController() { @@ -39,28 +39,6 @@ static BaseController() } } - protected void AddEventLog(int portalId, int userId, int jobId, string logTypeKey) - { - var objSecurity = PortalSecurity.Instance; - var portalInfo = PortalController.Instance.GetPortal(portalId); - var userInfo = UserController.Instance.GetUser(portalId, userId); - var username = objSecurity.InputFilter( - userInfo.Username, - PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); - - var log = new LogInfo - { - LogTypeKey = logTypeKey, - LogPortalID = portalId, - LogPortalName = portalInfo.PortalName, - LogUserName = username, - LogUserID = userId, - }; - - log.AddProperty("JobID", jobId.ToString()); - LogController.Instance.AddLog(log); - } - public bool CancelJob(int portalId, int jobId) { var controller = EntitiesController.Instance; @@ -92,6 +70,28 @@ public bool RemoveJob(int portalId, int jobId) return true; } + protected void AddEventLog(int portalId, int userId, int jobId, string logTypeKey) + { + var objSecurity = PortalSecurity.Instance; + var portalInfo = PortalController.Instance.GetPortal(portalId); + var userInfo = UserController.Instance.GetUser(portalId, userId); + var username = objSecurity.InputFilter( + userInfo.Username, + PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); + + var log = new LogInfo + { + LogTypeKey = logTypeKey, + LogPortalID = portalId, + LogPortalName = portalInfo.PortalName, + LogUserName = username, + LogUserID = userId, + }; + + log.AddProperty("JobID", jobId.ToString()); + LogController.Instance.AddLog(log); + } + /// /// Retrieves one page of paginated proceessed jobs. /// @@ -154,6 +154,35 @@ public JobItem GetJobDetails(int portalId, int jobId) return EntitiesController.Instance.GetLastJobTime(portalId, jobType); } + protected internal static void BuildJobSummary(string packageId, IExportImportRepository repository, ImportExportSummary summary) + { + var summaryItems = new SummaryList(); + var implementors = Util.GetPortableImplementors(); + var exportDto = repository.GetSingleItem(); + + foreach (var implementor in implementors) + { + implementor.Repository = repository; + summaryItems.Add(new SummaryItem + { + TotalItems = implementor.GetImportTotal(), + Category = implementor.Category, + Order = implementor.Priority, + }); + } + + summary.ExportFileInfo = GetExportFileInfo(Path.Combine(ExportFolder, packageId, Constants.ExportManifestName)); + summary.FromDate = exportDto.FromDateUtc; + summary.ToDate = exportDto.ToDateUtc; + summary.SummaryItems = summaryItems; + summary.IncludeDeletions = exportDto.IncludeDeletions; + summary.IncludeContent = exportDto.IncludeContent; + summary.IncludeExtensions = exportDto.IncludeExtensions; + summary.IncludePermissions = exportDto.IncludePermissions; + summary.IncludeProfileProperties = exportDto.IncludeProperfileProperties; + summary.ExportMode = exportDto.ExportMode; + } + protected static ImportExportSummary BuildJobSummary(int jobId) { var summaryItems = new SummaryList(); @@ -199,35 +228,6 @@ protected static ImportExportSummary BuildJobSummary(int jobId) return importExportSummary; } - protected internal static void BuildJobSummary(string packageId, IExportImportRepository repository, ImportExportSummary summary) - { - var summaryItems = new SummaryList(); - var implementors = Util.GetPortableImplementors(); - var exportDto = repository.GetSingleItem(); - - foreach (var implementor in implementors) - { - implementor.Repository = repository; - summaryItems.Add(new SummaryItem - { - TotalItems = implementor.GetImportTotal(), - Category = implementor.Category, - Order = implementor.Priority, - }); - } - - summary.ExportFileInfo = GetExportFileInfo(Path.Combine(ExportFolder, packageId, Constants.ExportManifestName)); - summary.FromDate = exportDto.FromDateUtc; - summary.ToDate = exportDto.ToDateUtc; - summary.SummaryItems = summaryItems; - summary.IncludeDeletions = exportDto.IncludeDeletions; - summary.IncludeContent = exportDto.IncludeContent; - summary.IncludeExtensions = exportDto.IncludeExtensions; - summary.IncludePermissions = exportDto.IncludePermissions; - summary.IncludeProfileProperties = exportDto.IncludeProperfileProperties; - summary.ExportMode = exportDto.ExportMode; - } - protected static ExportFileInfo GetExportFileInfo(string manifestPath) { ImportPackageInfo packageInfo = null; diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs index 09365fdda80..b3e2846fbe5 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs @@ -24,11 +24,6 @@ public class EntitiesController : ServiceLocator GetFactory() - { - return () => new EntitiesController(); - } - public ExportImportJob GetFirstActiveJob() { return CBO.Instance.FillObject(this._dataProvider.GetFirstActiveJob()); @@ -42,6 +37,11 @@ public ExportImportJob GetJobById(int jobId) return job; } + protected override Func GetFactory() + { + return () => new EntitiesController(); + } + public IList GetJobSummaryLog(int jobId) { return CBO.Instance.FillCollection(this._dataProvider.GetJobSummaryLog(jobId)); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs index 52399384519..c0448f04057 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs @@ -19,11 +19,6 @@ public class SettingsController : ServiceLocator GetFactory() - { - return () => new SettingsController(); - } public IEnumerable GetAllSettings() { @@ -36,6 +31,11 @@ public ExportImportSetting GetSetting(string settingName) { return this.GetAllSettings().ToList().FirstOrDefault(x => x.SettingName == settingName); } + + protected override Func GetFactory() + { + return () => new SettingsController(); + } public void AddSetting(ExportImportSetting exportImportSetting) { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs index 4402d23f6c9..861167d2608 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs @@ -8,6 +8,21 @@ namespace Dnn.ExportImport.Components.Dto using Dnn.ExportImport.Components.Common; using Newtonsoft.Json; + + public enum TriCheckedState + { +#if false + // for schema 1.0.0 + Checked = 0, + UnChecked = 1, + Partial = 2, +#else + UnChecked = 0, + Checked = 1, + CheckedWithAllChildren = 2, +#endif + + } [JsonObject] public class ExportDto @@ -164,19 +179,4 @@ public class PageToExport public TriCheckedState CheckedState { get; set; } } - - public enum TriCheckedState - { -#if false - // for schema 1.0.0 - Checked = 0, - UnChecked = 1, - Partial = 2, -#else - UnChecked = 0, - Checked = 1, - CheckedWithAllChildren = 2, -#endif - - } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs b/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs index 1bcedf1b185..a1f348427f2 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs @@ -38,12 +38,24 @@ namespace Dnn.ExportImport.Components.Engines public class ExportImportEngine { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); - private const StringComparison IgnoreCaseComp = StringComparison.InvariantCultureIgnoreCase; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); private static readonly string ExportFolder; + private static readonly Tuple[] DatasetColumns = + { + new Tuple("JobId", typeof(int)), + new Tuple("Name", typeof(string)), + new Tuple("Value", typeof(string)), + new Tuple("Level", typeof(int)), + new Tuple("CreatedOnDate", typeof(DateTime)), + }; + + private readonly Stopwatch _stopWatch = Stopwatch.StartNew(); + private int _timeoutSeconds; + static ExportImportEngine() { ExportFolder = Globals.ApplicationMapPath + Constants.ExportFolder; @@ -53,8 +65,43 @@ static ExportImportEngine() } } - private readonly Stopwatch _stopWatch = Stopwatch.StartNew(); - private int _timeoutSeconds; + private static string[] NotAllowedCategoriesinRequestArray => new[] + { + Constants.Category_Content, + Constants.Category_Pages, + Constants.Category_Portal, + Constants.Category_Content, + Constants.Category_Assets, + Constants.Category_Users, + Constants.Category_UsersData, + Constants.Category_Roles, + Constants.Category_Vocabularies, + Constants.Category_Templates, + Constants.Category_ProfileProps, + Constants.Category_Packages, + Constants.Category_Workflows, + }; + + private static string[] CleanUpIgnoredClasses => new[] + { + typeof(ExportFile).Name, + typeof(ExportFolder).Name, + typeof(ExportFolderMapping).Name, + typeof(ExportFolderPermission).Name, + typeof(ExportPageTemplate).Name, + typeof(ExportPortalSetting).Name, + typeof(ExportPortalLanguage).Name, + typeof(ExportProfileProperty).Name, + typeof(ExportUser).Name, + typeof(ExportAspnetUser).Name, + typeof(ExportAspnetMembership).Name, + typeof(ExportUserAuthentication).Name, + typeof(ExportUserPortal).Name, + typeof(ExportUserProfile).Name, + typeof(ExportUserRole).Name, + }; + + private bool TimeIsUp => this._stopWatch.Elapsed.TotalSeconds > this._timeoutSeconds; public void Export(ExportImportJob exportJob, ExportImportResult result, ScheduleHistoryItem scheduleHistoryItem) { @@ -405,6 +452,67 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul } } + public void AddLogsToDatabase(int jobId, ICollection completeLog) + { + if (completeLog == null || completeLog.Count == 0) + { + return; + } + + using (var table = new DataTable("ExportImportJobLogs")) + { + // must create the columns from scratch with each iteration + table.Columns.AddRange(DatasetColumns.Select( + column => new DataColumn(column.Item1, column.Item2)).ToArray()); + + // batch specific amount of record each time + const int batchSize = 500; + var toSkip = 0; + while (toSkip < completeLog.Count) + { + foreach (var item in completeLog.Skip(toSkip).Take(batchSize)) + { + var row = table.NewRow(); + row["JobId"] = jobId; + row["Name"] = item.Name.TrimToLength(Constants.LogColumnLength); + row["Value"] = item.Value.TrimToLength(Constants.LogColumnLength); + row["Level"] = (int)item.ReportLevel; + row["CreatedOnDate"] = item.CreatedOnDate; + table.Rows.Add(row); + } + + PlatformDataProvider.Instance().BulkInsert("ExportImportJobLogs_AddBulk", "@DataTable", table); + toSkip += batchSize; + table.Rows.Clear(); + } + } + + completeLog.Clear(); + } + + private static bool CheckCancelledCallBack(ExportImportJob job) + { + var job2 = CachingProvider.Instance().GetItem(Util.GetExpImpJobCacheKey(job)) as ExportImportJob; + if (job2 == null) + { + job2 = EntitiesController.Instance.GetJobById(job.JobId); + job.IsCancelled = job2.IsCancelled; + AddJobToCache(job2); + } + + return job2.IsCancelled; + } + + private static void AddJobToCache(ExportImportJob job) + { + CachingProvider.Instance().Insert(Util.GetExpImpJobCacheKey(job), job); + } + + private static void RemoveTokenFromCache(ExportImportJob job) + { + CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job)); + } + private void PrepareCheckPoints(int jobId, List parentServices, List implementors, HashSet includedItems, IList checkpoints) { @@ -461,19 +569,6 @@ private void PrepareCheckPoints(int jobId, List parentServi while (parentServices.Count > 0); } - private static bool CheckCancelledCallBack(ExportImportJob job) - { - var job2 = CachingProvider.Instance().GetItem(Util.GetExpImpJobCacheKey(job)) as ExportImportJob; - if (job2 == null) - { - job2 = EntitiesController.Instance.GetJobById(job.JobId); - job.IsCancelled = job2.IsCancelled; - AddJobToCache(job2); - } - - return job2.IsCancelled; - } - /// /// Callback function to provide a checkpoint mechanism for an implementation. /// @@ -485,18 +580,6 @@ private bool CheckpointCallback(BasePortableService service) return this.TimeIsUp; } - private bool TimeIsUp => this._stopWatch.Elapsed.TotalSeconds > this._timeoutSeconds; - - private static void AddJobToCache(ExportImportJob job) - { - CachingProvider.Instance().Insert(Util.GetExpImpJobCacheKey(job), job); - } - - private static void RemoveTokenFromCache(ExportImportJob job) - { - CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job)); - } - private static HashSet GetAllCategoriesToInclude( ExportDto exportDto, List implementors) @@ -678,88 +761,5 @@ private static void CleanupDatabaseIfDirty(IExportImportRepository repository) } } } - - private static string[] NotAllowedCategoriesinRequestArray => new[] - { - Constants.Category_Content, - Constants.Category_Pages, - Constants.Category_Portal, - Constants.Category_Content, - Constants.Category_Assets, - Constants.Category_Users, - Constants.Category_UsersData, - Constants.Category_Roles, - Constants.Category_Vocabularies, - Constants.Category_Templates, - Constants.Category_ProfileProps, - Constants.Category_Packages, - Constants.Category_Workflows, - }; - - private static string[] CleanUpIgnoredClasses => new[] - { - typeof(ExportFile).Name, - typeof(ExportFolder).Name, - typeof(ExportFolderMapping).Name, - typeof(ExportFolderPermission).Name, - typeof(ExportPageTemplate).Name, - typeof(ExportPortalSetting).Name, - typeof(ExportPortalLanguage).Name, - typeof(ExportProfileProperty).Name, - typeof(ExportUser).Name, - typeof(ExportAspnetUser).Name, - typeof(ExportAspnetMembership).Name, - typeof(ExportUserAuthentication).Name, - typeof(ExportUserPortal).Name, - typeof(ExportUserProfile).Name, - typeof(ExportUserRole).Name, - }; - - public void AddLogsToDatabase(int jobId, ICollection completeLog) - { - if (completeLog == null || completeLog.Count == 0) - { - return; - } - - using (var table = new DataTable("ExportImportJobLogs")) - { - // must create the columns from scratch with each iteration - table.Columns.AddRange(DatasetColumns.Select( - column => new DataColumn(column.Item1, column.Item2)).ToArray()); - - // batch specific amount of record each time - const int batchSize = 500; - var toSkip = 0; - while (toSkip < completeLog.Count) - { - foreach (var item in completeLog.Skip(toSkip).Take(batchSize)) - { - var row = table.NewRow(); - row["JobId"] = jobId; - row["Name"] = item.Name.TrimToLength(Constants.LogColumnLength); - row["Value"] = item.Value.TrimToLength(Constants.LogColumnLength); - row["Level"] = (int)item.ReportLevel; - row["CreatedOnDate"] = item.CreatedOnDate; - table.Rows.Add(row); - } - - PlatformDataProvider.Instance().BulkInsert("ExportImportJobLogs_AddBulk", "@DataTable", table); - toSkip += batchSize; - table.Rows.Clear(); - } - } - - completeLog.Clear(); - } - - private static readonly Tuple[] DatasetColumns = - { - new Tuple("JobId", typeof(int)), - new Tuple("Name", typeof(string)), - new Tuple("Value", typeof(string)), - new Tuple("Level", typeof(int)), - new Tuple("CreatedOnDate", typeof(DateTime)), - }; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs b/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs index 4d7607274a6..40b2024adad 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs @@ -13,6 +13,11 @@ namespace Dnn.ExportImport.Components.Models public class ExportImportResult { + public ExportImportResult() + { + this.CompleteLog = this.CompleteLog = new List(); + } + public int JobId { get; set; } public IList CompleteLog { get; private set; } @@ -22,11 +27,6 @@ public IList Summary get { return this.CompleteLog.Where(item => item.ReportLevel >= ReportLevel.Info).ToList(); } } - public ExportImportResult() - { - this.CompleteLog = this.CompleteLog = new List(); - } - public LogItem AddSummary(string name, string value) { return this.AddLogEntry(name, value, ReportLevel.Info); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs b/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs index bae3f45c06a..b6c56dde2a0 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs @@ -25,15 +25,15 @@ static DataProvider() Provider = new DataProvider(); } - public static DataProvider Instance() - { - return Provider; - } - private DataProvider() { // so it can't be instantiated outside this class } + + public static DataProvider Instance() + { + return Provider; + } public void UpdateRecordChangers(string tableName, string primaryKeyName, int primaryKeyId, int? createdBy, int? modifiedBy) { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs b/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs index c0d7b103565..1e9c2386db3 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs @@ -22,10 +22,10 @@ namespace Dnn.ExportImport.Components.Scheduler /// public class ExportImportScheduler : SchedulerClient { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportScheduler)); - private const int EmergencyScheduleFrequency = 120; private const int DefaultScheduleFrequency = 1; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportScheduler)); private const string EmergencyScheduleFrequencyUnit = "m"; private const string DefaultScheduleFrequencyUnit = "d"; diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs index f7c02a7ca18..e6aada00f44 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs @@ -27,6 +27,8 @@ namespace Dnn.ExportImport.Components.Services public class AssetsExportService : BasePortableService { private const string DefaultUsersFoldersPath = "Users"; + + private const string UsersAssetsTempFolder = "{0}\\TempUsers\\"; private static readonly Regex UserFolderEx = new Regex( @"users/\d+/\d+/(\d+)/", @@ -34,8 +36,6 @@ public class AssetsExportService : BasePortableService private readonly string _assetsFolder = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{{0}}\\{Constants.ExportZipFiles}"; - - private const string UsersAssetsTempFolder = "{0}\\TempUsers\\"; public override string Category => Constants.Category_Assets; @@ -351,6 +351,18 @@ public override int GetImportTotal() return this.Repository.GetCount(); } + private static bool IsUserFolder(string folderPath, out int? userId) + { + userId = null; + var match = UserFolderEx.Match(folderPath); + if (match.Success) + { + userId = int.Parse(match.Groups[1].Value); + } + + return match.Success; + } + private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, ExportFolder folder) { var portalId = importJob.PortalId; @@ -587,9 +599,9 @@ private void ProcessFiles(ExportImportJob importJob, ImportDto importDto, Export file.Width ?? Null.NullInteger, file.Height ?? Null.NullInteger, file.ContentType, file.Folder, file.FolderId, createdBy, file.Sha1Hash, DateUtils.GetDatabaseLocalTime(), file.Title, file.Description, - file.StartDate, file.EndDate ?? Null.NullDate, file.EnablePublishPeriod, + file.StartDate, file.EndDate ?? Null.NullDate, file.EnablePublishPeriod, - // file.ContentItemId ?? Null.NullInteger);--If we keep it we will see FK_PK relationship errors. + // file.ContentItemId ?? Null.NullInteger);--If we keep it we will see FK_PK relationship errors. Null.NullInteger); if (file.Content != null) @@ -630,18 +642,6 @@ var mFile in } } - private static bool IsUserFolder(string folderPath, out int? userId) - { - userId = null; - var match = UserFolderEx.Match(folderPath); - if (match.Success) - { - userId = int.Parse(match.Groups[1].Value); - } - - return match.Success; - } - private string GetActualFileName(ExportFile objFile) { return (objFile.StorageLocation == (int)FolderController.StorageLocationTypes.SecureFileSystem) diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs index f0e995047ab..9b25b06eed4 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs @@ -133,6 +133,53 @@ public override int GetImportTotal() return this.Repository.GetCount(); } + public void InstallPackage(string filePath) + { + using (var stream = new FileStream(filePath, FileMode.Open)) + { + try + { + var installer = GetInstaller(stream); + + if (installer.IsValid) + { + // Reset Log + installer.InstallerInfo.Log.Logs.Clear(); + + // Set the IgnnoreWhiteList flag + installer.InstallerInfo.IgnoreWhiteList = true; + + // Set the Repair flag + installer.InstallerInfo.RepairInstall = true; + + // Install + installer.Install(); + } + } + catch (Exception ex) + { + this.Result.AddLogEntry("Import Package error", $"{filePath}. ERROR: {ex.Message}"); + Logger.Error(ex); + } + } + } + + private static Installer GetInstaller(Stream stream) + { + var installer = new Installer(stream, Globals.ApplicationMapPath, false, false) + { + InstallerInfo = { PortalID = Null.NullInteger }, + }; + + // Read the manifest + if (installer.InstallerInfo.ManifestFile != null) + { + installer.ReadManifest(true); + } + + return installer; + } + private int GetCurrentSkip() { if (!string.IsNullOrEmpty(this.CheckPoint.StageData)) @@ -271,52 +318,5 @@ private void ProcessImportModulePackages(ImportDto importDto) this.Result.AddLogEntry("PackagesFileNotFound", "Packages file not found. Skipping packages import", ReportLevel.Warn); } } - - public void InstallPackage(string filePath) - { - using (var stream = new FileStream(filePath, FileMode.Open)) - { - try - { - var installer = GetInstaller(stream); - - if (installer.IsValid) - { - // Reset Log - installer.InstallerInfo.Log.Logs.Clear(); - - // Set the IgnnoreWhiteList flag - installer.InstallerInfo.IgnoreWhiteList = true; - - // Set the Repair flag - installer.InstallerInfo.RepairInstall = true; - - // Install - installer.Install(); - } - } - catch (Exception ex) - { - this.Result.AddLogEntry("Import Package error", $"{filePath}. ERROR: {ex.Message}"); - Logger.Error(ex); - } - } - } - - private static Installer GetInstaller(Stream stream) - { - var installer = new Installer(stream, Globals.ApplicationMapPath, false, false) - { - InstallerInfo = { PortalID = Null.NullInteger }, - }; - - // Read the manifest - if (installer.InstallerInfo.ManifestFile != null) - { - installer.ReadManifest(true); - } - - return installer; - } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs index a067dfafe8b..a17c55df943 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs @@ -45,6 +45,12 @@ namespace Dnn.ExportImport.Components.Services /// public class PagesExportService : BasePortableService { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); + + private ProgressTotals _totals; + private DataProvider _dataProvider; + private ITabController _tabController; + public override string Category => Constants.Category_Pages; public override string ParentCategory => null; @@ -56,22 +62,37 @@ public class PagesExportService : BasePortableService public virtual bool IgnoreParentMatch { get; set; } = false; protected ImportDto ImportDto => this._importDto; - - private ProgressTotals _totals; - private DataProvider _dataProvider; - private ITabController _tabController; private IModuleController _moduleController; private ExportImportJob _exportImportJob; private ImportDto _importDto; private ExportDto _exportDto; private IList _exportedModuleDefinitions = new List(); - - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); private Dictionary _partialImportedTabs = new Dictionary(); private Dictionary _searchedParentTabs = new Dictionary(); private IList _importContentList = new List(); // map the exported module and local module. + public static void ResetContentsFlag(ExportImportRepository repository) + { + // reset restored flag; if it same extracted db is reused, then content will be restored + var toSkip = 0; + const int batchSize = 100; + var totalCount = repository.GetCount(); + while (totalCount > 0) + { + var items = repository.GetAllItems(skip: toSkip, max: batchSize) + .Where(item => item.IsRestored).ToList(); + if (items.Count > 0) + { + items.ForEach(item => item.IsRestored = false); + repository.UpdateItems(items); + } + + toSkip += batchSize; + totalCount -= batchSize; + } + } + public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { if (this.CheckPoint.Stage > 0) @@ -132,63 +153,23 @@ public override int GetImportTotal() { return this.Repository.GetCount(x => x.IsSystem == this.IncludeSystem); } - - private void ProcessImportPages() - { - this._dataProvider = DataProvider.Instance(); - this._totals = string.IsNullOrEmpty(this.CheckPoint.StageData) - ? new ProgressTotals() - : JsonConvert.DeserializeObject(this.CheckPoint.StageData); - var portalId = this._exportImportJob.PortalId; - - var localTabs = this._tabController.GetTabsByPortal(portalId).Values.ToList(); - - var exportedTabs = this.Repository.GetItems(x => x.IsSystem == (this.Category == Constants.Category_Templates)) - .OrderBy(t => t.Level).ThenBy(t => t.ParentId).ThenBy(t => t.TabOrder).ToList(); - - // Update the total items count in the check points. This should be updated only once. - this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? exportedTabs.Count : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - - var progressStep = 100.0 / exportedTabs.OrderByDescending(x => x.Id).Count(x => x.Id < this._totals.LastProcessedId); - - var index = 0; - var referenceTabs = new List(); - this._importContentList.Clear(); - foreach (var otherTab in exportedTabs) + public void RestoreTab(TabInfo tab, PortalSettings portalSettings) + { + var changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState(tab.PortalID, tab.TabID); + if (changeControlStateForTab.IsChangeControlEnabledForTab) { - if (this.CheckCancelled(this._exportImportJob)) - { - break; - } - - if (this._totals.LastProcessedId > index) - { - continue; // this is the exported DB row ID; not the TabID - } - - this.ProcessImportPage(otherTab, exportedTabs, localTabs, referenceTabs); - - this.CheckPoint.ProcessedItems++; - this.CheckPoint.Progress += progressStep; - if (this.CheckPointStageCallback(this)) - { - break; - } - - this._totals.LastProcessedId = index++; - this.CheckPoint.StageData = JsonConvert.SerializeObject(this._totals); + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); } - // repair pages which linked to other pages - this.RepairReferenceTabs(referenceTabs, localTabs, exportedTabs); + this._tabController.RestoreTab(tab, portalSettings); - this._searchedParentTabs.Clear(); - this.ReportImportTotals(); + if (changeControlStateForTab.IsChangeControlEnabledForTab) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, changeControlStateForTab.IsVersioningEnabledForTab); + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, changeControlStateForTab.IsWorkflowEnabledForTab); + } } protected virtual void ProcessImportPage(ExportTab otherTab, IList exportedTabs, IList localTabs, IList referenceTabs) @@ -367,22 +348,103 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex this.UpdateParentInPartialImportTabs(localTab, otherTab, portalId, exportedTabs, localTabs); } - public void RestoreTab(TabInfo tab, PortalSettings portalSettings) + private static int TryFindLocalParentTabId(ExportTab exportedTab, IEnumerable exportedTabs, IEnumerable localTabs) { - var changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState(tab.PortalID, tab.TabID); - if (changeControlStateForTab.IsChangeControlEnabledForTab) + return TryFindLocalTabId(exportedTab, exportedTabs, localTabs, exportedTab.ParentId); + } + + private static int TryFindLocalTabId(ExportTab exportedTab, IEnumerable exportedTabs, IEnumerable localTabs, int? tabId) + { + if (tabId.HasValue && tabId.Value > 0) { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); - TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); + var otherParent = exportedTabs.FirstOrDefault(t => t.TabId == tabId); + if (otherParent != null) + { + if (otherParent.LocalId.HasValue) + { + var localTab = localTabs.FirstOrDefault(t => t.TabID == otherParent.LocalId); + if (localTab != null) + { + return localTab.TabID; + } + } + } + else if (exportedTab.TabPath.HasValue()) + { + var index = exportedTab.TabPath.LastIndexOf(@"//", StringComparison.Ordinal); + if (index > 0) + { + var path = exportedTab.TabPath.Substring(0, index); + var localTab = localTabs.FirstOrDefault(t => + path.Equals(t.TabPath, StringComparison.InvariantCultureIgnoreCase) + && IsSameCulture(t.CultureCode, exportedTab.CultureCode)); + if (localTab != null) + { + return localTab.TabID; + } + } + } } - this._tabController.RestoreTab(tab, portalSettings); + return -1; + } + + private void ProcessImportPages() + { + this._dataProvider = DataProvider.Instance(); + this._totals = string.IsNullOrEmpty(this.CheckPoint.StageData) + ? new ProgressTotals() + : JsonConvert.DeserializeObject(this.CheckPoint.StageData); - if (changeControlStateForTab.IsChangeControlEnabledForTab) + var portalId = this._exportImportJob.PortalId; + + var localTabs = this._tabController.GetTabsByPortal(portalId).Values.ToList(); + + var exportedTabs = this.Repository.GetItems(x => x.IsSystem == (this.Category == Constants.Category_Templates)) + .OrderBy(t => t.Level).ThenBy(t => t.ParentId).ThenBy(t => t.TabOrder).ToList(); + + // Update the total items count in the check points. This should be updated only once. + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? exportedTabs.Count : this.CheckPoint.TotalItems; + if (this.CheckPointStageCallback(this)) + { + return; + } + + var progressStep = 100.0 / exportedTabs.OrderByDescending(x => x.Id).Count(x => x.Id < this._totals.LastProcessedId); + + var index = 0; + var referenceTabs = new List(); + this._importContentList.Clear(); + foreach (var otherTab in exportedTabs) { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, changeControlStateForTab.IsVersioningEnabledForTab); - TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, changeControlStateForTab.IsWorkflowEnabledForTab); + if (this.CheckCancelled(this._exportImportJob)) + { + break; + } + + if (this._totals.LastProcessedId > index) + { + continue; // this is the exported DB row ID; not the TabID + } + + this.ProcessImportPage(otherTab, exportedTabs, localTabs, referenceTabs); + + this.CheckPoint.ProcessedItems++; + this.CheckPoint.Progress += progressStep; + if (this.CheckPointStageCallback(this)) + { + break; + } + + this._totals.LastProcessedId = index++; + this.CheckPoint.StageData = JsonConvert.SerializeObject(this._totals); } + + // repair pages which linked to other pages + this.RepairReferenceTabs(referenceTabs, localTabs, exportedTabs); + + this._searchedParentTabs.Clear(); + this.ReportImportTotals(); } /// @@ -1404,47 +1466,6 @@ private int ImportTabModuleSettings(ModuleInfo localTabModule, ExportTabModule o return count; } - private static int TryFindLocalParentTabId(ExportTab exportedTab, IEnumerable exportedTabs, IEnumerable localTabs) - { - return TryFindLocalTabId(exportedTab, exportedTabs, localTabs, exportedTab.ParentId); - } - - private static int TryFindLocalTabId(ExportTab exportedTab, IEnumerable exportedTabs, IEnumerable localTabs, int? tabId) - { - if (tabId.HasValue && tabId.Value > 0) - { - var otherParent = exportedTabs.FirstOrDefault(t => t.TabId == tabId); - if (otherParent != null) - { - if (otherParent.LocalId.HasValue) - { - var localTab = localTabs.FirstOrDefault(t => t.TabID == otherParent.LocalId); - if (localTab != null) - { - return localTab.TabID; - } - } - } - else if (exportedTab.TabPath.HasValue()) - { - var index = exportedTab.TabPath.LastIndexOf(@"//", StringComparison.Ordinal); - if (index > 0) - { - var path = exportedTab.TabPath.Substring(0, index); - var localTab = localTabs.FirstOrDefault(t => - path.Equals(t.TabPath, StringComparison.InvariantCultureIgnoreCase) - && IsSameCulture(t.CultureCode, exportedTab.CultureCode)); - if (localTab != null) - { - return localTab.TabID; - } - } - } - } - - return -1; - } - private static bool IsSameCulture(string sourceCultureCode, string targetCultureCode) { sourceCultureCode = !string.IsNullOrWhiteSpace(sourceCultureCode) ? sourceCultureCode : Localization.SystemLocale; @@ -1488,6 +1509,34 @@ private static void SetTabData(TabInfo localTab, ExportTab otherTab) localTab.Terms.Clear(); localTab.Terms.AddRange(TermHelper.ToTabTerms(otherTab.Tags, localTab.PortalID)); } + + private static bool IsTabIncluded(ExportTabInfo tab, IList allTabs, PageToExport[] selectedPages) + { + var first = true; + while (tab != null) + { + var pg = selectedPages.FirstOrDefault(p => p.TabId == tab.TabID); + if (pg != null) + { + if (first) + { + // this is the current page we are checking for. + return pg.CheckedState == TriCheckedState.Checked || pg.CheckedState == TriCheckedState.CheckedWithAllChildren; + } + + // this is a [grand] parent of the page we are checking for. + if (pg.CheckedState == TriCheckedState.CheckedWithAllChildren) + { + return true; + } + } + + first = false; + tab = allTabs.FirstOrDefault(t => t.TabID == tab.ParentID); + } + + return false; + } private void RepairReferenceTabs(IList referenceTabs, IList localTabs, IList exportTabs) { @@ -1760,13 +1809,13 @@ private int ExportModulePackage(ExportModule exportModule) CompressionUtil.AddFileToArchive(filePath, packageZipFile, offset.GetValueOrDefault(0)); this.Repository.CreateItem( - new ExportPackage - { - PackageName = package.Name, - Version = package.Version, - PackageType = package.PackageType, - PackageFileName = InstallerUtil.GetPackageBackupName(package), - }, null); + new ExportPackage + { + PackageName = package.Name, + Version = package.Version, + PackageType = package.PackageType, + PackageFileName = InstallerUtil.GetPackageBackupName(package), + }, null); this._exportedModuleDefinitions.Add(exportModule.ModuleDefID); return 1; @@ -1907,55 +1956,6 @@ private ExportTab SaveExportPage(TabInfo tab) this.Result.AddLogEntry("Exported page", tab.TabName + " (" + tab.TabPath + ")"); return exportPage; } - - private static bool IsTabIncluded(ExportTabInfo tab, IList allTabs, PageToExport[] selectedPages) - { - var first = true; - while (tab != null) - { - var pg = selectedPages.FirstOrDefault(p => p.TabId == tab.TabID); - if (pg != null) - { - if (first) - { - // this is the current page we are checking for. - return pg.CheckedState == TriCheckedState.Checked || pg.CheckedState == TriCheckedState.CheckedWithAllChildren; - } - - // this is a [grand] parent of the page we are checking for. - if (pg.CheckedState == TriCheckedState.CheckedWithAllChildren) - { - return true; - } - } - - first = false; - tab = allTabs.FirstOrDefault(t => t.TabID == tab.ParentID); - } - - return false; - } - - public static void ResetContentsFlag(ExportImportRepository repository) - { - // reset restored flag; if it same extracted db is reused, then content will be restored - var toSkip = 0; - const int batchSize = 100; - var totalCount = repository.GetCount(); - while (totalCount > 0) - { - var items = repository.GetAllItems(skip: toSkip, max: batchSize) - .Where(item => item.IsRestored).ToList(); - if (items.Count > 0) - { - items.ForEach(item => item.IsRestored = false); - repository.UpdateItems(items); - } - - toSkip += batchSize; - totalCount -= batchSize; - } - } private void ReportExportTotals() { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs index 40f6b6216ff..23687b9cdd9 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs @@ -192,6 +192,26 @@ public override int GetImportTotal() this.Repository.GetCount(); } + private static void RefreshRecordsUserIds(IEnumerable roleGroupItems) + { + var provider = DataProvider.Instance(); + foreach (var roleGroupItem in roleGroupItems) + { + provider.UpdateRecordChangers("RoleGroups", "RoleGroupID", + roleGroupItem.RoleGroupId, roleGroupItem.CreatedBy, roleGroupItem.ModifiedBy); + } + } + + private static void RefreshRecordsUserIds(IEnumerable roleItems) + { + var provider = DataProvider.Instance(); + foreach (var roleItem in roleItems) + { + provider.UpdateRecordChangers("Roles", "RoleID", + roleItem.RoleId, roleItem.CreatedBy, roleItem.ModifiedBy); + } + } + private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, IEnumerable otherRoleGroups) { @@ -417,26 +437,6 @@ private void ProcessRoleSettings(ExportImportJob importJob, ImportDto importDto, RoleController.Instance.ClearRoleCache(importJob.PortalId); } - private static void RefreshRecordsUserIds(IEnumerable roleGroupItems) - { - var provider = DataProvider.Instance(); - foreach (var roleGroupItem in roleGroupItems) - { - provider.UpdateRecordChangers("RoleGroups", "RoleGroupID", - roleGroupItem.RoleGroupId, roleGroupItem.CreatedBy, roleGroupItem.ModifiedBy); - } - } - - private static void RefreshRecordsUserIds(IEnumerable roleItems) - { - var provider = DataProvider.Instance(); - foreach (var roleItem in roleItems) - { - provider.UpdateRecordChangers("Roles", "RoleID", - roleItem.RoleId, roleItem.CreatedBy, roleItem.ModifiedBy); - } - } - private static void RefreshRecordsUserIds(IEnumerable settingItems) { var provider = DataProvider.Instance(); @@ -449,46 +449,38 @@ private static void RefreshRecordsUserIds(IEnumerable settingItems) private struct RoleGroupItem { - public int RoleGroupId { get; } - - public int CreatedBy { get; } - - public int ModifiedBy { get; } - public RoleGroupItem(int roleGroupId, int createdBy, int modifiedBy) { this.RoleGroupId = roleGroupId; this.CreatedBy = createdBy; this.ModifiedBy = modifiedBy; } - } - - private struct RoleItem - { - public int RoleId { get; } + + public int RoleGroupId { get; } public int CreatedBy { get; } public int ModifiedBy { get; } + } + private struct RoleItem + { public RoleItem(int roleId, int createdBy, int modifiedBy) { this.RoleId = roleId; this.CreatedBy = createdBy; this.ModifiedBy = modifiedBy; } - } - - private struct SettingItem - { - public int RoleId { get; } - public string Name { get; } + public int RoleId { get; } public int CreatedBy { get; } public int ModifiedBy { get; } + } + private struct SettingItem + { public SettingItem(int roleId, string settingName, int createdBy, int modifiedBy) { this.RoleId = roleId; @@ -496,6 +488,14 @@ public SettingItem(int roleId, string settingName, int createdBy, int modifiedBy this.CreatedBy = createdBy; this.ModifiedBy = modifiedBy; } + + public int RoleId { get; } + + public string Name { get; } + + public int CreatedBy { get; } + + public int ModifiedBy { get; } } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs index cb87b814913..b7bd39f93a6 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs @@ -24,6 +24,33 @@ namespace Dnn.ExportImport.Components.Services /// public class UsersDataExportService : BasePortableService { + private static readonly Tuple[] UserRolesDatasetColumns = + { + new Tuple("PortalId", typeof(int)), + new Tuple("UserId", typeof(int)), + new Tuple("RoleId", typeof(int)), + new Tuple("ExpiryDate", typeof(DateTime)), + new Tuple("IsTrialUsed", typeof(bool)), + new Tuple("EffectiveDate", typeof(DateTime)), + new Tuple("CreatedByUserId", typeof(int)), + new Tuple("LastModifiedByUserId", typeof(int)), + new Tuple("Status", typeof(int)), + new Tuple("IsOwner", typeof(bool)), + new Tuple("IsSuperUser", typeof(bool)), + }; + + private static readonly Tuple[] UserProfileDatasetColumns = + { + new Tuple("PortalId", typeof(int)), + new Tuple("UserId", typeof(int)), + new Tuple("PropertyDefinitionId", typeof(int)), + new Tuple("PropertyValue", typeof(string)), + new Tuple("PropertyText", typeof(string)), + new Tuple("Visibility", typeof(int)), + new Tuple("ExtendedVisibility", typeof(string)), + new Tuple("IsSuperUser", typeof(bool)), + }; + public override string Category => Constants.Category_UsersData; public override string ParentCategory => Constants.Category_Users; @@ -238,6 +265,11 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } } + public override int GetImportTotal() + { + return this.Repository.GetCount(); + } + private string GetUserPhotoId(int portalId, string importFileId, ExportUser user) { int profilePictureId; @@ -280,37 +312,5 @@ private string GetUserPhotoId(int portalId, string importFileId, ExportUser user return null; } - - public override int GetImportTotal() - { - return this.Repository.GetCount(); - } - - private static readonly Tuple[] UserRolesDatasetColumns = - { - new Tuple("PortalId", typeof(int)), - new Tuple("UserId", typeof(int)), - new Tuple("RoleId", typeof(int)), - new Tuple("ExpiryDate", typeof(DateTime)), - new Tuple("IsTrialUsed", typeof(bool)), - new Tuple("EffectiveDate", typeof(DateTime)), - new Tuple("CreatedByUserId", typeof(int)), - new Tuple("LastModifiedByUserId", typeof(int)), - new Tuple("Status", typeof(int)), - new Tuple("IsOwner", typeof(bool)), - new Tuple("IsSuperUser", typeof(bool)), - }; - - private static readonly Tuple[] UserProfileDatasetColumns = - { - new Tuple("PortalId", typeof(int)), - new Tuple("UserId", typeof(int)), - new Tuple("PropertyDefinitionId", typeof(int)), - new Tuple("PropertyValue", typeof(string)), - new Tuple("PropertyText", typeof(string)), - new Tuple("Visibility", typeof(int)), - new Tuple("ExtendedVisibility", typeof(string)), - new Tuple("IsSuperUser", typeof(bool)), - }; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs index d05530d8f9c..0c04c532b5a 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs @@ -23,6 +23,45 @@ namespace Dnn.ExportImport.Components.Services /// public class UsersExportService : BasePortableService { + private static readonly Tuple[] UsersDatasetColumns = + { + new Tuple("PortalId", typeof(int)), + new Tuple("Username", typeof(string)), + new Tuple("FirstName", typeof(string)), + new Tuple("LastName", typeof(string)), + new Tuple("AffiliateId", typeof(int)), + new Tuple("IsSuperUser", typeof(bool)), + new Tuple("Email", typeof(string)), + new Tuple("DisplayName", typeof(string)), + new Tuple("UpdatePassword", typeof(bool)), + new Tuple("Authorised", typeof(bool)), + new Tuple("CreatedByUserID", typeof(int)), + new Tuple("VanityUrl", typeof(string)), + new Tuple("RefreshRoles", typeof(bool)), + new Tuple("LastIPAddress", typeof(string)), + new Tuple("PasswordResetToken", typeof(Guid)), + new Tuple("PasswordResetExpiration", typeof(DateTime)), + new Tuple("IsDeleted", typeof(bool)), + new Tuple("LastModifiedByUserID", typeof(int)), + new Tuple("ApplicationId", typeof(Guid)), + new Tuple("AspUserId", typeof(Guid)), + new Tuple("MobileAlias", typeof(string)), + new Tuple("IsAnonymous", typeof(bool)), + new Tuple("Password", typeof(string)), + new Tuple("PasswordFormat", typeof(int)), + new Tuple("PasswordSalt", typeof(string)), + new Tuple("MobilePIN", typeof(string)), + new Tuple("PasswordQuestion", typeof(string)), + new Tuple("PasswordAnswer", typeof(string)), + new Tuple("IsApproved", typeof(bool)), + new Tuple("IsLockedOut", typeof(bool)), + new Tuple("FailedPasswordAttemptCount", typeof(int)), + new Tuple("FailedPasswordAnswerAttemptCount", typeof(int)), + new Tuple("Comment", typeof(string)), + new Tuple("AuthenticationType", typeof(string)), + new Tuple("AuthenticationToken", typeof(string)), + }; + public override string Category => Constants.Category_Users; public override string ParentCategory => null; @@ -463,44 +502,5 @@ private Guid GetApplicationId() "SELECT TOP 1 ApplicationId FROM aspnet_Applications"); } } - - private static readonly Tuple[] UsersDatasetColumns = - { - new Tuple("PortalId", typeof(int)), - new Tuple("Username", typeof(string)), - new Tuple("FirstName", typeof(string)), - new Tuple("LastName", typeof(string)), - new Tuple("AffiliateId", typeof(int)), - new Tuple("IsSuperUser", typeof(bool)), - new Tuple("Email", typeof(string)), - new Tuple("DisplayName", typeof(string)), - new Tuple("UpdatePassword", typeof(bool)), - new Tuple("Authorised", typeof(bool)), - new Tuple("CreatedByUserID", typeof(int)), - new Tuple("VanityUrl", typeof(string)), - new Tuple("RefreshRoles", typeof(bool)), - new Tuple("LastIPAddress", typeof(string)), - new Tuple("PasswordResetToken", typeof(Guid)), - new Tuple("PasswordResetExpiration", typeof(DateTime)), - new Tuple("IsDeleted", typeof(bool)), - new Tuple("LastModifiedByUserID", typeof(int)), - new Tuple("ApplicationId", typeof(Guid)), - new Tuple("AspUserId", typeof(Guid)), - new Tuple("MobileAlias", typeof(string)), - new Tuple("IsAnonymous", typeof(bool)), - new Tuple("Password", typeof(string)), - new Tuple("PasswordFormat", typeof(int)), - new Tuple("PasswordSalt", typeof(string)), - new Tuple("MobilePIN", typeof(string)), - new Tuple("PasswordQuestion", typeof(string)), - new Tuple("PasswordAnswer", typeof(string)), - new Tuple("IsApproved", typeof(bool)), - new Tuple("IsLockedOut", typeof(bool)), - new Tuple("FailedPasswordAttemptCount", typeof(int)), - new Tuple("FailedPasswordAnswerAttemptCount", typeof(int)), - new Tuple("Comment", typeof(string)), - new Tuple("AuthenticationType", typeof(string)), - new Tuple("AuthenticationToken", typeof(string)), - }; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs index fd62d8db51f..44f9cb0c2f6 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs @@ -113,16 +113,6 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) } } - private static List GetTaxonomyTerms(int portalId, DateTime toDate, DateTime? fromDate) - { - return CBO.FillCollection(DataProvider.Instance().GetAllTerms(portalId, toDate, fromDate)); - } - - private static List GetTaxonomyVocabularies(int portalId, DateTime toDate, DateTime? fromDate) - { - return CBO.FillCollection(DataProvider.Instance().GetAllVocabularies(portalId, toDate, fromDate)); - } - public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (this.CheckPoint.Stage > 0) @@ -172,6 +162,16 @@ public override int GetImportTotal() return this.Repository.GetCount() + this.Repository.GetCount(); } + private static List GetTaxonomyTerms(int portalId, DateTime toDate, DateTime? fromDate) + { + return CBO.FillCollection(DataProvider.Instance().GetAllTerms(portalId, toDate, fromDate)); + } + + private static List GetTaxonomyVocabularies(int portalId, DateTime toDate, DateTime? fromDate) + { + return CBO.FillCollection(DataProvider.Instance().GetAllVocabularies(portalId, toDate, fromDate)); + } + private void ProcessVocabularies(ExportImportJob importJob, ImportDto importDto, IList otherScopeTypes, IEnumerable otherVocabularies) { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs index 7d7d9f5072c..b50003b4b17 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs @@ -82,25 +82,6 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPoint.StageData = null; this.CheckPointStageCallback(this); } - - private static List GetWorkflows(int portalId, bool includeDeletions) - { - return CBO.FillCollection( - DataProvider.Instance().GetAllWorkflows(portalId, includeDeletions)); - } - - private static List GetWorkflowStates(int workflowId) - { - return CBO.FillCollection( - DataProvider.Instance().GetAllWorkflowStates(workflowId)); - } - - private static List GetWorkflowStatePermissions( - int stateId, DateTime toDate, DateTime? fromDate) - { - return CBO.FillCollection( - DataProvider.Instance().GetAllWorkflowStatePermissions(stateId, toDate, fromDate)); - } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { @@ -279,5 +260,24 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPoint.ProcessedItems = importWorkflows.Count; this.CheckPointStageCallback(this); } + + private static List GetWorkflows(int portalId, bool includeDeletions) + { + return CBO.FillCollection( + DataProvider.Instance().GetAllWorkflows(portalId, includeDeletions)); + } + + private static List GetWorkflowStates(int workflowId) + { + return CBO.FillCollection( + DataProvider.Instance().GetAllWorkflowStates(workflowId)); + } + + private static List GetWorkflowStatePermissions( + int stateId, DateTime toDate, DateTime? fromDate) + { + return CBO.FillCollection( + DataProvider.Instance().GetAllWorkflowStatePermissions(stateId, toDate, fromDate)); + } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs b/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs index 5bacbcb39eb..c9f8195b4f9 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs @@ -35,16 +35,6 @@ public void Dispose() this.Dispose(true); } - private void Dispose(bool isDisposing) - { - var temp = Interlocked.Exchange(ref this._liteDb, null); - temp?.Dispose(); - if (isDisposing) - { - GC.SuppressFinalize(this); - } - } - public T AddSingleItem(T item) where T : class { @@ -61,6 +51,16 @@ public T UpdateSingleItem(T item) return item; } + private void Dispose(bool isDisposing) + { + var temp = Interlocked.Exchange(ref this._liteDb, null); + temp?.Dispose(); + if (isDisposing) + { + GC.SuppressFinalize(this); + } + } + public T GetSingleItem() where T : class { @@ -152,6 +152,20 @@ public IEnumerable GetAllItems( return this.InternalGetItems(null, orderKeySelector, asc, skip, max); } + public T GetItem(int id) + where T : BasicExportImportDto + { + var collection = this.DbCollection(); + return collection.FindById(id); + } + + public IEnumerable GetItems(IEnumerable idList) + where T : BasicExportImportDto + { + Expression> predicate = p => idList.Contains(p.Id); + return this.InternalGetItems(predicate); + } + private IEnumerable InternalGetItems( Expression> predicate, Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) @@ -171,20 +185,6 @@ private IEnumerable InternalGetItems( return result.AsEnumerable(); } - public T GetItem(int id) - where T : BasicExportImportDto - { - var collection = this.DbCollection(); - return collection.FindById(id); - } - - public IEnumerable GetItems(IEnumerable idList) - where T : BasicExportImportDto - { - Expression> predicate = p => idList.Contains(p.Id); - return this.InternalGetItems(predicate); - } - public IEnumerable GetRelatedItems(int referenceId) where T : BasicExportImportDto { diff --git a/DNN Platform/Modules/Groups/Components/Content.cs b/DNN Platform/Modules/Groups/Components/Content.cs index 79c01d8490c..2581b5f1cad 100644 --- a/DNN Platform/Modules/Groups/Components/Content.cs +++ b/DNN Platform/Modules/Groups/Components/Content.cs @@ -16,6 +16,29 @@ namespace DotNetNuke.Entities.Groups public class Content { + /// + /// This is used to determine the ContentTypeID (part of the Core API) based on this module's content type. If the content type doesn't exist yet for the module, it is created. + /// + /// The primary key value (ContentTypeID) from the core API's Content Types table. + internal static int GetContentTypeID(string ContentTypeName) + { + var typeController = new ContentTypeController(); + var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t; + int contentTypeId; + + if (colContentTypes.Count() > 0) + { + var contentType = colContentTypes.Single(); + contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; + } + else + { + contentTypeId = CreateContentType(ContentTypeName); + } + + return contentTypeId; + } + /// /// This should only run after the Post exists in the data store. /// @@ -106,29 +129,6 @@ internal void DeleteContentItem(int contentItemID) // cntTerms.RemoveQuestionTerms(objContent); Util.GetContentController().DeleteContentItem(objContent); } - - /// - /// This is used to determine the ContentTypeID (part of the Core API) based on this module's content type. If the content type doesn't exist yet for the module, it is created. - /// - /// The primary key value (ContentTypeID) from the core API's Content Types table. - internal static int GetContentTypeID(string ContentTypeName) - { - var typeController = new ContentTypeController(); - var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t; - int contentTypeId; - - if (colContentTypes.Count() > 0) - { - var contentType = colContentTypes.Single(); - contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; - } - else - { - contentTypeId = CreateContentType(ContentTypeName); - } - - return contentTypeId; - } /// /// Creates a Content Type (for taxonomy) in the data store. diff --git a/DNN Platform/Modules/Groups/Components/GroupViewParser.cs b/DNN Platform/Modules/Groups/Components/GroupViewParser.cs index 1543151204d..7cc312d6a42 100644 --- a/DNN Platform/Modules/Groups/Components/GroupViewParser.cs +++ b/DNN Platform/Modules/Groups/Components/GroupViewParser.cs @@ -19,20 +19,6 @@ namespace DotNetNuke.Modules.Groups.Components public class GroupViewParser { - protected INavigationManager NavigationManager { get; } - - private PortalSettings PortalSettings { get; set; } - - private RoleInfo RoleInfo { get; set; } - - private UserInfo CurrentUser { get; set; } - - public string Template { get; set; } - - public int GroupViewTabId { get; set; } - - public string GroupEditUrl { get; set; } - public GroupViewParser(PortalSettings portalSettings, RoleInfo roleInfo, UserInfo currentUser, string template, int groupViewTabId) { this.PortalSettings = portalSettings; @@ -42,6 +28,20 @@ public GroupViewParser(PortalSettings portalSettings, RoleInfo roleInfo, UserInf this.GroupViewTabId = groupViewTabId; this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public string Template { get; set; } + + public int GroupViewTabId { get; set; } + + protected INavigationManager NavigationManager { get; } + + private PortalSettings PortalSettings { get; set; } + + private RoleInfo RoleInfo { get; set; } + + private UserInfo CurrentUser { get; set; } + + public string GroupEditUrl { get; set; } public string ParseView() { diff --git a/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs b/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs index 969bccf3370..71384bd1b02 100644 --- a/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs +++ b/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs @@ -81,18 +81,18 @@ private void AddNotificationTypes() var type = new NotificationType { Name = "GroupPendingNotification", Description = "Group Pending Notification", DesktopModuleId = deskModuleId }; if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { - actions.Add(new NotificationTypeAction - { - NameResourceKey = "Approve", - DescriptionResourceKey = "ApproveGroup", - APICall = "API/SocialGroups/ModerationService/ApproveGroup", - }); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "RejectGroup", - DescriptionResourceKey = "RejectGroup", - APICall = "API/SocialGroups/ModerationService/RejectGroup", - }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "Approve", + DescriptionResourceKey = "ApproveGroup", + APICall = "API/SocialGroups/ModerationService/ApproveGroup", + }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "RejectGroup", + DescriptionResourceKey = "RejectGroup", + APICall = "API/SocialGroups/ModerationService/RejectGroup", + }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); } @@ -109,13 +109,13 @@ private void AddNotificationTypes() if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { actions.Clear(); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "RejectGroup", - DescriptionResourceKey = "RejectGroup", - ConfirmResourceKey = "DeleteItem", - APICall = "API/SocialGroups/ModerationService/RejectGroup", - }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "RejectGroup", + DescriptionResourceKey = "RejectGroup", + ConfirmResourceKey = "DeleteItem", + APICall = "API/SocialGroups/ModerationService/RejectGroup", + }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); } @@ -132,19 +132,19 @@ private void AddNotificationTypes() if (NotificationsController.Instance.GetNotificationType(type.Name) == null) { actions.Clear(); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "Approve", - DescriptionResourceKey = "ApproveGroupMember", - ConfirmResourceKey = string.Empty, - APICall = "API/SocialGroups/ModerationService/ApproveMember", - }); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "RejectMember", - DescriptionResourceKey = "RejectGroupMember", - APICall = "API/SocialGroups/ModerationService/RejectMember", - }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "Approve", + DescriptionResourceKey = "ApproveGroupMember", + ConfirmResourceKey = string.Empty, + APICall = "API/SocialGroups/ModerationService/ApproveMember", + }); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "RejectMember", + DescriptionResourceKey = "RejectGroupMember", + APICall = "API/SocialGroups/ModerationService/RejectMember", + }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); } diff --git a/DNN Platform/Modules/Groups/Components/Notifications.cs b/DNN Platform/Modules/Groups/Components/Notifications.cs index 19afa01b414..ac4dd2be9a0 100644 --- a/DNN Platform/Modules/Groups/Components/Notifications.cs +++ b/DNN Platform/Modules/Groups/Components/Notifications.cs @@ -40,15 +40,15 @@ internal virtual Notification AddGroupNotification(string notificationTypeName, body = body.Replace("Private.Text", Localization.GetString("Private.Text", Constants.SharedResourcesPath)); bool dismiss = notificationTypeName != Constants.GroupPendingNotification; - var notification = new Notification - { - NotificationTypeID = notificationType.NotificationTypeId, - Subject = subject, - Body = body, - IncludeDismissAction = dismiss, - SenderUserID = initiatingUser.UserID, - Context = string.Format("{0}:{1}:{2}", tabId, moduleId, group.RoleID), - }; + var notification = new Notification + { + NotificationTypeID = notificationType.NotificationTypeId, + Subject = subject, + Body = body, + IncludeDismissAction = dismiss, + SenderUserID = initiatingUser.UserID, + Context = string.Format("{0}:{1}:{2}", tabId, moduleId, group.RoleID), + }; NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, moderators, recipients); return notification; diff --git a/DNN Platform/Modules/Groups/Components/Utilities.cs b/DNN Platform/Modules/Groups/Components/Utilities.cs index 9270598932f..12af3904236 100644 --- a/DNN Platform/Modules/Groups/Components/Utilities.cs +++ b/DNN Platform/Modules/Groups/Components/Utilities.cs @@ -14,19 +14,6 @@ namespace DotNetNuke.Modules.Groups public class Utilities { - internal static string ParseTokenWrapper(string Template, string Token, bool Condition) - { - var pattern = "(\\[" + Token + "\\](.*?)\\[\\/" + Token + "\\])"; - var regExp = RegexUtils.GetCachedRegex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline); - var matches = regExp.Matches(Template); - foreach (Match match in matches) - { - Template = Template.Replace(match.Value, Condition ? match.Groups[2].Value : string.Empty); - } - - return Template; - } - public static string NavigateUrl(int TabId, string[] @params) { return Globals.DependencyProvider.GetRequiredService()?.NavigateURL(TabId, string.Empty, @params); @@ -41,5 +28,18 @@ public static string[] AddParams(string param, string[] currParams) currParams.CopyTo(tmpParams, intLength); return tmpParams; } + + internal static string ParseTokenWrapper(string Template, string Token, bool Condition) + { + var pattern = "(\\[" + Token + "\\](.*?)\\[\\/" + Token + "\\])"; + var regExp = RegexUtils.GetCachedRegex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline); + var matches = regExp.Matches(Template); + foreach (Match match in matches) + { + Template = Template.Replace(match.Value, Condition ? match.Groups[2].Value : string.Empty); + } + + return Template; + } } } diff --git a/DNN Platform/Modules/Groups/Create.ascx.cs b/DNN Platform/Modules/Groups/Create.ascx.cs index 1d181e94b19..27877ac071d 100644 --- a/DNN Platform/Modules/Groups/Create.ascx.cs +++ b/DNN Platform/Modules/Groups/Create.ascx.cs @@ -34,6 +34,11 @@ protected override void OnInit(EventArgs e) this.InitializeComponent(); base.OnInit(e); } + + protected void Page_Load(object sender, EventArgs e) + { + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + } private void InitializeComponent() { @@ -41,11 +46,6 @@ private void InitializeComponent() this.btnCreate.Click += this.Create_Click; this.btnCancel.Click += this.Cancel_Click; } - - protected void Page_Load(object sender, EventArgs e) - { - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - } private void Cancel_Click(object sender, EventArgs e) { diff --git a/DNN Platform/Modules/Groups/GroupEdit.ascx.cs b/DNN Platform/Modules/Groups/GroupEdit.ascx.cs index 9a4cec00c01..57b28676f93 100644 --- a/DNN Platform/Modules/Groups/GroupEdit.ascx.cs +++ b/DNN Platform/Modules/Groups/GroupEdit.ascx.cs @@ -29,13 +29,6 @@ protected override void OnInit(EventArgs e) this.InitializeComponent(); base.OnInit(e); } - - private void InitializeComponent() - { - this.Load += this.Page_Load; - this.btnSave.Click += this.Save_Click; - this.btnCancel.Click += this.Cancel_Click; - } protected void Page_Load(object sender, EventArgs e) { @@ -85,6 +78,13 @@ protected void Page_Load(object sender, EventArgs e) } } } + + private void InitializeComponent() + { + this.Load += this.Page_Load; + this.btnSave.Click += this.Save_Click; + this.btnCancel.Click += this.Cancel_Click; + } private void Cancel_Click(object sender, EventArgs e) { diff --git a/DNN Platform/Modules/Groups/GroupListControl.cs b/DNN Platform/Modules/Groups/GroupListControl.cs index 637d65c1dea..6fa218063e9 100644 --- a/DNN Platform/Modules/Groups/GroupListControl.cs +++ b/DNN Platform/Modules/Groups/GroupListControl.cs @@ -25,6 +25,8 @@ namespace DotNetNuke.Modules.Groups.Controls public class GroupListControl : WebControl { + public UserInfo currentUser; + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string ItemTemplate { get; set; } @@ -82,8 +84,6 @@ public PortalSettings PortalSettings [DefaultValue(false)] public bool DisplayCurrentUserGroups { get; set; } - public UserInfo currentUser; - public int GroupViewTabId { get; set; } protected override void OnInit(EventArgs e) @@ -92,17 +92,6 @@ protected override void OnInit(EventArgs e) this.currentUser = UserController.Instance.GetCurrentUserInfo(); } - private static bool TestPredicateGroup(IEnumerable> predicates, RoleInfo ri) - { - return predicates.All(p => p(ri)); - } - - private static object GetOrderByProperty(object obj, string property) - { - var propertyInfo = obj.GetType().GetProperty(property, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); - return propertyInfo == null ? null : propertyInfo.GetValue(obj, null); - } - protected override void Render(HtmlTextWriter output) { var whereCls = new List> @@ -256,5 +245,16 @@ protected override void Render(HtmlTextWriter output) output.Write(sb.ToString()); output.Write(""); } + + private static bool TestPredicateGroup(IEnumerable> predicates, RoleInfo ri) + { + return predicates.All(p => p(ri)); + } + + private static object GetOrderByProperty(object obj, string property) + { + var propertyInfo = obj.GetType().GetProperty(property, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); + return propertyInfo == null ? null : propertyInfo.GetValue(obj, null); + } } } diff --git a/DNN Platform/Modules/Groups/GroupsModuleBase.cs b/DNN Platform/Modules/Groups/GroupsModuleBase.cs index 21fecdb53ac..3c0391ad8a7 100644 --- a/DNN Platform/Modules/Groups/GroupsModuleBase.cs +++ b/DNN Platform/Modules/Groups/GroupsModuleBase.cs @@ -15,8 +15,6 @@ namespace DotNetNuke.Modules.Groups public class GroupsModuleBase : PortalModuleBase { - protected INavigationManager NavigationManager { get; } - public GroupsModuleBase() { this.NavigationManager = this.DependencyProvider.GetRequiredService(); @@ -51,6 +49,8 @@ public GroupMode LoadView } } + protected INavigationManager NavigationManager { get; } + public int GroupId { get diff --git a/DNN Platform/Modules/Groups/List.ascx.cs b/DNN Platform/Modules/Groups/List.ascx.cs index 110e10d5508..75a67bb5311 100644 --- a/DNN Platform/Modules/Groups/List.ascx.cs +++ b/DNN Platform/Modules/Groups/List.ascx.cs @@ -13,13 +13,13 @@ namespace DotNetNuke.Modules.Groups public partial class List : GroupsModuleBase { - public INavigationManager _navigationManager { get; } - public List() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } + public INavigationManager _navigationManager { get; } + protected void Page_Load(object sender, EventArgs e) { ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); diff --git a/DNN Platform/Modules/Groups/ModerationServiceController.cs b/DNN Platform/Modules/Groups/ModerationServiceController.cs index f2ffbccf582..32f230b2ed5 100644 --- a/DNN Platform/Modules/Groups/ModerationServiceController.cs +++ b/DNN Platform/Modules/Groups/ModerationServiceController.cs @@ -27,11 +27,11 @@ namespace DotNetNuke.Modules.Groups [DnnAuthorize] public class ModerationServiceController : DnnApiController { - protected INavigationManager NavigationManager { get; } - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModerationServiceController)); private int _tabId; private int _moduleId; + + protected INavigationManager NavigationManager { get; } private int _roleId; private int _memberId; private RoleInfo _roleInfo; @@ -41,11 +41,6 @@ public ModerationServiceController(INavigationManager navigationManager) this.NavigationManager = navigationManager; } - public class NotificationDTO - { - public int NotificationId { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage ApproveGroup(NotificationDTO postData) @@ -181,11 +176,9 @@ public HttpResponseMessage JoinGroup(RoleDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); } - public class RoleDTO + public class NotificationDTO { - public int RoleId { get; set; } - - public int GroupViewTabId { get; set; } + public int NotificationId { get; set; } } [HttpPost] @@ -322,6 +315,13 @@ public HttpResponseMessage RejectMember(NotificationDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); } + public class RoleDTO + { + public int RoleId { get; set; } + + public int GroupViewTabId { get; set; } + } + private void ParseKey(string key) { this._tabId = -1; diff --git a/DNN Platform/Modules/Groups/Setup.ascx.cs b/DNN Platform/Modules/Groups/Setup.ascx.cs index 2034257e955..e96166156c1 100644 --- a/DNN Platform/Modules/Groups/Setup.ascx.cs +++ b/DNN Platform/Modules/Groups/Setup.ascx.cs @@ -23,13 +23,6 @@ namespace DotNetNuke.Modules.Groups public partial class Setup : GroupsModuleBase { - protected void Page_Load(object sender, EventArgs e) - { - this.btnGo.Visible = this.Request.IsAuthenticated; - this.btnGo.Enabled = this.Request.IsAuthenticated; - this.btnGo.Click += this.btGo_Click; - } - public void btGo_Click(object sender, EventArgs e) { // Setup Child Page - Main View/Activity @@ -73,6 +66,13 @@ public void btGo_Click(object sender, EventArgs e) this.Response.Redirect(this.Request.RawUrl); } + protected void Page_Load(object sender, EventArgs e) + { + this.btnGo.Visible = this.Request.IsAuthenticated; + this.btnGo.Enabled = this.Request.IsAuthenticated; + this.btnGo.Click += this.btGo_Click; + } + private TabInfo CreatePage(TabInfo tab, int portalId, int parentTabId, string tabName, bool includeInMenu) { var newTab = TabController.Instance.GetTabsByPortal(portalId).WithTabNameAndParentId(tabName, parentTabId); diff --git a/DNN Platform/Modules/Groups/View.ascx.cs b/DNN Platform/Modules/Groups/View.ascx.cs index 8af7bd0a47c..00950eca756 100644 --- a/DNN Platform/Modules/Groups/View.ascx.cs +++ b/DNN Platform/Modules/Groups/View.ascx.cs @@ -55,8 +55,8 @@ private void Page_Load(object sender, EventArgs e) if (this.GroupId < 0) { if (this.TabId != this.GroupListTabId && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) - { - this.Response.Redirect(this._navigationManager.NavigateURL(this.GroupListTabId)); + { + this.Response.Redirect(this._navigationManager.NavigateURL(this.GroupListTabId)); } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs index c6b15bb52d2..3ab6195d0b8 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs @@ -48,13 +48,171 @@ public class HtmlTextController : ModuleSearchBase, IPortable, IUpgradeable public const int MAX_DESCRIPTION_LENGTH = 100; private const string PortalRootToken = "{{PortalRoot}}"; - protected INavigationManager NavigationManager { get; } - public HtmlTextController() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } + + /// ----------------------------------------------------------------------------- + /// + /// FormatHtmlText formats HtmlText content for display in the browser. + /// + /// + /// + /// The ModuleID. + /// The HtmlText Content. + /// Module Settings. + /// The Portal Settings. + /// The Page Instance. + /// + public static string FormatHtmlText(int moduleId, string content, HtmlModuleSettings settings, PortalSettings portalSettings, Page page) + { + // token replace + if (settings.ReplaceTokens) + { + var tr = new HtmlTokenReplace(page) + { + AccessingUser = UserController.Instance.GetCurrentUserInfo(), + DebugMessages = portalSettings.UserMode != PortalSettings.Mode.View, + ModuleId = moduleId, + PortalSettings = portalSettings, + }; + content = tr.ReplaceEnvironmentTokens(content); + } + + // Html decode content + content = HttpUtility.HtmlDecode(content); + + // manage relative paths + content = ManageRelativePaths(content, portalSettings.HomeDirectory, "src", portalSettings.PortalId); + content = ManageRelativePaths(content, portalSettings.HomeDirectory, "background", portalSettings.PortalId); + + return content; + } + + public static string ManageRelativePaths(string strHTML, string strUploadDirectory, string strToken, int intPortalID) + { + int P = 0; + int R = 0; + int S = 0; + int tLen = 0; + string strURL = null; + var sbBuff = new StringBuilder(string.Empty); + + if (!string.IsNullOrEmpty(strHTML)) + { + tLen = strToken.Length + 2; + string uploadDirectory = strUploadDirectory.ToLowerInvariant(); + + // find position of first occurrance: + P = strHTML.IndexOf(strToken + "=\"", StringComparison.InvariantCultureIgnoreCase); + while (P != -1) + { + sbBuff.Append(strHTML.Substring(S, P - S + tLen)); + + // keep charactes left of URL + S = P + tLen; + + // save startpos of URL + R = strHTML.IndexOf("\"", S); + + // end of URL + if (R >= 0) + { + strURL = strHTML.Substring(S, R - S).ToLowerInvariant(); + } + else + { + strURL = strHTML.Substring(S).ToLowerInvariant(); + } + + if (strHTML.Substring(P + tLen, 10).Equals("data:image", StringComparison.InvariantCultureIgnoreCase)) + { + P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); + continue; + } + + // if we are linking internally + if (!strURL.Contains("://")) + { + // remove the leading portion of the path if the URL contains the upload directory structure + string strDirectory = uploadDirectory; + if (!strDirectory.EndsWith("/")) + { + strDirectory += "/"; + } + + if (strURL.IndexOf(strDirectory) != -1) + { + S = S + strURL.IndexOf(strDirectory) + strDirectory.Length; + strURL = strURL.Substring(strURL.IndexOf(strDirectory) + strDirectory.Length); + } + + // add upload directory + if (!strURL.StartsWith("/") + && !string.IsNullOrEmpty(strURL.Trim())) // We don't write the UploadDirectory if the token/attribute has not value. Therefore we will avoid an unnecessary request + { + sbBuff.Append(uploadDirectory); + } + } + + // find position of next occurrance + P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); + } + + if (S > -1) + { + sbBuff.Append(strHTML.Substring(S)); + } + + // append characters of last URL and behind + } + + return sbBuff.ToString(); + } + + public string ReplaceWithRootToken(Match m) + { + var domain = m.Groups["domain"].Value; + + // Relative url + if (string.IsNullOrEmpty(domain)) + { + return PortalRootToken; + } + + var aliases = PortalAliasController.Instance.GetPortalAliases(); + if (!aliases.Contains(domain)) + { + // this is no not a portal url so even if it contains /portals/.. + // we do not need to replace it with a token + return m.ToString(); + } + + // full qualified portal url that needs to be tokenized + var result = domain + PortalRootToken; + var protocol = m.Groups["protocol"].Value; + return string.IsNullOrEmpty(protocol) ? result : protocol + result; + } + + /// ----------------------------------------------------------------------------- + /// + /// DeleteHtmlText deletes an HtmlTextInfo object for the Module and Item. + /// + /// + /// + /// The ID of the Module. + /// The ID of the Item. + public void DeleteHtmlText(int ModuleID, int ItemID) + { + DataProvider.Instance().DeleteHtmlText(ModuleID, ItemID); + + // refresh output cache + ModuleController.SynchronizeModule(ModuleID); + } + private static void AddHtmlNotification(string subject, string body, UserInfo user) { var notificationType = NotificationsController.Instance.GetNotificationType("HtmlNotification"); @@ -246,83 +404,6 @@ private string TokeniseLinks(string content, int portalId) return exp.Replace(content, matchEvaluator); } - public string ReplaceWithRootToken(Match m) - { - var domain = m.Groups["domain"].Value; - - // Relative url - if (string.IsNullOrEmpty(domain)) - { - return PortalRootToken; - } - - var aliases = PortalAliasController.Instance.GetPortalAliases(); - if (!aliases.Contains(domain)) - { - // this is no not a portal url so even if it contains /portals/.. - // we do not need to replace it with a token - return m.ToString(); - } - - // full qualified portal url that needs to be tokenized - var result = domain + PortalRootToken; - var protocol = m.Groups["protocol"].Value; - return string.IsNullOrEmpty(protocol) ? result : protocol + result; - } - - /// ----------------------------------------------------------------------------- - /// - /// DeleteHtmlText deletes an HtmlTextInfo object for the Module and Item. - /// - /// - /// - /// The ID of the Module. - /// The ID of the Item. - public void DeleteHtmlText(int ModuleID, int ItemID) - { - DataProvider.Instance().DeleteHtmlText(ModuleID, ItemID); - - // refresh output cache - ModuleController.SynchronizeModule(ModuleID); - } - - /// ----------------------------------------------------------------------------- - /// - /// FormatHtmlText formats HtmlText content for display in the browser. - /// - /// - /// - /// The ModuleID. - /// The HtmlText Content. - /// Module Settings. - /// The Portal Settings. - /// The Page Instance. - /// - public static string FormatHtmlText(int moduleId, string content, HtmlModuleSettings settings, PortalSettings portalSettings, Page page) - { - // token replace - if (settings.ReplaceTokens) - { - var tr = new HtmlTokenReplace(page) - { - AccessingUser = UserController.Instance.GetCurrentUserInfo(), - DebugMessages = portalSettings.UserMode != PortalSettings.Mode.View, - ModuleId = moduleId, - PortalSettings = portalSettings, - }; - content = tr.ReplaceEnvironmentTokens(content); - } - - // Html decode content - content = HttpUtility.HtmlDecode(content); - - // manage relative paths - content = ManageRelativePaths(content, portalSettings.HomeDirectory, "src", portalSettings.PortalId); - content = ManageRelativePaths(content, portalSettings.HomeDirectory, "background", portalSettings.PortalId); - - return content; - } - /// ----------------------------------------------------------------------------- /// /// GetAllHtmlText gets a collection of HtmlTextInfo objects for the Module and Workflow. @@ -459,87 +540,6 @@ public KeyValuePair GetWorkflow(int ModuleId, int TabId, int Portal return new KeyValuePair(workFlowType, workFlowId); } - public static string ManageRelativePaths(string strHTML, string strUploadDirectory, string strToken, int intPortalID) - { - int P = 0; - int R = 0; - int S = 0; - int tLen = 0; - string strURL = null; - var sbBuff = new StringBuilder(string.Empty); - - if (!string.IsNullOrEmpty(strHTML)) - { - tLen = strToken.Length + 2; - string uploadDirectory = strUploadDirectory.ToLowerInvariant(); - - // find position of first occurrance: - P = strHTML.IndexOf(strToken + "=\"", StringComparison.InvariantCultureIgnoreCase); - while (P != -1) - { - sbBuff.Append(strHTML.Substring(S, P - S + tLen)); - - // keep charactes left of URL - S = P + tLen; - - // save startpos of URL - R = strHTML.IndexOf("\"", S); - - // end of URL - if (R >= 0) - { - strURL = strHTML.Substring(S, R - S).ToLowerInvariant(); - } - else - { - strURL = strHTML.Substring(S).ToLowerInvariant(); - } - - if (strHTML.Substring(P + tLen, 10).Equals("data:image", StringComparison.InvariantCultureIgnoreCase)) - { - P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); - continue; - } - - // if we are linking internally - if (!strURL.Contains("://")) - { - // remove the leading portion of the path if the URL contains the upload directory structure - string strDirectory = uploadDirectory; - if (!strDirectory.EndsWith("/")) - { - strDirectory += "/"; - } - - if (strURL.IndexOf(strDirectory) != -1) - { - S = S + strURL.IndexOf(strDirectory) + strDirectory.Length; - strURL = strURL.Substring(strURL.IndexOf(strDirectory) + strDirectory.Length); - } - - // add upload directory - if (!strURL.StartsWith("/") - && !string.IsNullOrEmpty(strURL.Trim())) // We don't write the UploadDirectory if the token/attribute has not value. Therefore we will avoid an unnecessary request - { - sbBuff.Append(uploadDirectory); - } - } - - // find position of next occurrance - P = strHTML.IndexOf(strToken + "=\"", S + strURL.Length + 2, StringComparison.InvariantCultureIgnoreCase); - } - - if (S > -1) - { - sbBuff.Append(strHTML.Substring(S)); - } - - // append characters of last URL and behind - } - - return sbBuff.ToString(); - } - /// ----------------------------------------------------------------------------- /// /// UpdateHtmlText creates a new HtmlTextInfo object or updates an existing HtmlTextInfo object. @@ -824,26 +824,6 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modI return searchDocuments; } - private static List CollectHierarchicalTags(List terms) - { - Func, List, List> collectTagsFunc = null; - collectTagsFunc = (ts, tags) => - { - if (ts != null && ts.Count > 0) - { - foreach (var t in ts) - { - tags.Add(t.Name); - tags.AddRange(collectTagsFunc(t.ChildTerms, new List())); - } - } - - return tags; - }; - - return collectTagsFunc(terms, new List()); - } - public string UpgradeModule(string Version) { switch (Version) @@ -871,6 +851,26 @@ public string UpgradeModule(string Version) return string.Empty; } + private static List CollectHierarchicalTags(List terms) + { + Func, List, List> collectTagsFunc = null; + collectTagsFunc = (ts, tags) => + { + if (ts != null && ts.Count > 0) + { + foreach (var t in ts) + { + tags.Add(t.Name); + tags.AddRange(collectTagsFunc(t.ChildTerms, new List())); + } + } + + return tags; + }; + + return collectTagsFunc(terms, new List()); + } + private void AddNotificationTypes() { var type = new NotificationType { Name = "HtmlNotification", Description = "Html Module Notification" }; diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs b/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs index e796b750739..b662047dabc 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs @@ -68,7 +68,7 @@ public ArrayList GetWorkflowStates(int WorkflowID) /// ----------------------------------------------------------------------------- public object GetWorkflowStatesCallBack(CacheItemArgs cacheItemArgs) { - var WorkflowID = (int) cacheItemArgs.ParamList[0]; + var WorkflowID = (int)cacheItemArgs.ParamList[0]; return CBO.FillCollection(DataProvider.Instance().GetWorkflowStates(WorkflowID), typeof(WorkflowStateInfo)); } @@ -87,7 +87,7 @@ public int GetFirstWorkflowStateID(int WorkflowID) ArrayList arrWorkflowStates = this.GetWorkflowStates(WorkflowID); if (arrWorkflowStates.Count > 0) { - intStateID = ((WorkflowStateInfo) arrWorkflowStates[0]).StateID; + intStateID = ((WorkflowStateInfo)arrWorkflowStates[0]).StateID; } return intStateID; @@ -112,7 +112,7 @@ public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) // locate the current state for (intItem = 0; intItem < arrWorkflowStates.Count; intItem++) { - if (((WorkflowStateInfo) arrWorkflowStates[intItem]).StateID == StateID) + if (((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID == StateID) { intPreviousStateID = StateID; break; @@ -125,9 +125,9 @@ public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) intItem = intItem - 1; while (intItem >= 0) { - if (((WorkflowStateInfo) arrWorkflowStates[intItem]).IsActive) + if (((WorkflowStateInfo)arrWorkflowStates[intItem]).IsActive) { - intPreviousStateID = ((WorkflowStateInfo) arrWorkflowStates[intItem]).StateID; + intPreviousStateID = ((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID; break; } @@ -163,7 +163,7 @@ public int GetNextWorkflowStateID(int WorkflowID, int StateID) // locate the current state for (intItem = 0; intItem < arrWorkflowStates.Count; intItem++) { - if (((WorkflowStateInfo) arrWorkflowStates[intItem]).StateID == StateID) + if (((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID == StateID) { intNextStateID = StateID; break; @@ -176,9 +176,9 @@ public int GetNextWorkflowStateID(int WorkflowID, int StateID) intItem = intItem + 1; while (intItem < arrWorkflowStates.Count) { - if (((WorkflowStateInfo) arrWorkflowStates[intItem]).IsActive) + if (((WorkflowStateInfo)arrWorkflowStates[intItem]).IsActive) { - intNextStateID = ((WorkflowStateInfo) arrWorkflowStates[intItem]).StateID; + intNextStateID = ((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID; break; } @@ -210,7 +210,7 @@ public int GetLastWorkflowStateID(int WorkflowID) ArrayList arrWorkflowStates = this.GetWorkflowStates(WorkflowID); if (arrWorkflowStates.Count > 0) { - intStateID = ((WorkflowStateInfo) arrWorkflowStates[arrWorkflowStates.Count - 1]).StateID; + intStateID = ((WorkflowStateInfo)arrWorkflowStates[arrWorkflowStates.Count - 1]).StateID; } return intStateID; diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs index 0a8fadf87ee..dba64ca00ee 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs @@ -52,7 +52,7 @@ public WorkflowStatePermissionInfo this[int index] { get { - return (WorkflowStatePermissionInfo) this.List[index]; + return (WorkflowStatePermissionInfo)this.List[index]; } set diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs index 5bb309ccc0e..46f213952f9 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs @@ -31,6 +31,48 @@ public class WorkflowStatePermissionController public const int WorkflowStatePermissionCacheTimeOut = 20; private static readonly DataProvider provider = DataProvider.Instance(); + /// ----------------------------------------------------------------------------- + /// + /// GetWorkflowStatePermissions gets a WorkflowStatePermissionCollection. + /// + /// The ID of the State. + /// + /// ----------------------------------------------------------------------------- + public static WorkflowStatePermissionCollection GetWorkflowStatePermissions(int StateID) + { + bool bFound = false; + + // Get the WorkflowStatePermission Dictionary + Dictionary dicWorkflowStatePermissions = GetWorkflowStatePermissions(); + + // Get the Collection from the Dictionary + WorkflowStatePermissionCollection WorkflowStatePermissions = null; + bFound = dicWorkflowStatePermissions.TryGetValue(StateID, out WorkflowStatePermissions); + + if (!bFound) + { + // try the database + WorkflowStatePermissions = new WorkflowStatePermissionCollection( + CBO.FillCollection(provider.GetWorkflowStatePermissionsByStateID(StateID), typeof(WorkflowStatePermissionInfo)), + StateID); + } + + return WorkflowStatePermissions; + } + + /// ----------------------------------------------------------------------------- + /// + /// HasWorkflowStatePermission checks whether the current user has a specific WorkflowState Permission. + /// + /// The Permissions for the WorkflowState. + /// The Permission to check. + /// + /// ----------------------------------------------------------------------------- + public static bool HasWorkflowStatePermission(WorkflowStatePermissionCollection objWorkflowStatePermissions, string permissionKey) + { + return PortalSecurity.IsInRoles(objWorkflowStatePermissions.ToString(permissionKey)); + } + /// ----------------------------------------------------------------------------- /// /// GetWorkflowStatePermissions gets a Dictionary of WorkflowStatePermissionCollections by @@ -108,47 +150,5 @@ private static Dictionary FillWorkflowSt return dic; } - - /// ----------------------------------------------------------------------------- - /// - /// GetWorkflowStatePermissions gets a WorkflowStatePermissionCollection. - /// - /// The ID of the State. - /// - /// ----------------------------------------------------------------------------- - public static WorkflowStatePermissionCollection GetWorkflowStatePermissions(int StateID) - { - bool bFound = false; - - // Get the WorkflowStatePermission Dictionary - Dictionary dicWorkflowStatePermissions = GetWorkflowStatePermissions(); - - // Get the Collection from the Dictionary - WorkflowStatePermissionCollection WorkflowStatePermissions = null; - bFound = dicWorkflowStatePermissions.TryGetValue(StateID, out WorkflowStatePermissions); - - if (!bFound) - { - // try the database - WorkflowStatePermissions = new WorkflowStatePermissionCollection( - CBO.FillCollection(provider.GetWorkflowStatePermissionsByStateID(StateID), typeof(WorkflowStatePermissionInfo)), - StateID); - } - - return WorkflowStatePermissions; - } - - /// ----------------------------------------------------------------------------- - /// - /// HasWorkflowStatePermission checks whether the current user has a specific WorkflowState Permission. - /// - /// The Permissions for the WorkflowState. - /// The Permission to check. - /// - /// ----------------------------------------------------------------------------- - public static bool HasWorkflowStatePermission(WorkflowStatePermissionCollection objWorkflowStatePermissions, string permissionKey) - { - return PortalSecurity.IsInRoles(objWorkflowStatePermissions.ToString(permissionKey)); - } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs index ce140d43357..41016d4b8e7 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs @@ -95,6 +95,25 @@ public int StateID this._StateID = value; } } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + public int KeyID + { + get + { + return this.WorkflowStatePermissionID; + } + + set + { + this.WorkflowStatePermissionID = value; + } + } /// ----------------------------------------------------------------------------- /// @@ -167,24 +186,5 @@ public void Fill(IDataReader dr) this.WorkflowStatePermissionID = Null.SetNullInteger(dr["WorkflowStatePermissionID"]); this.StateID = Null.SetNullInteger(dr["StateID"]); } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Key ID. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - public int KeyID - { - get - { - return this.WorkflowStatePermissionID; - } - - set - { - this.WorkflowStatePermissionID = value; - } - } } } diff --git a/DNN Platform/Modules/HTML/EditHtml.ascx.cs b/DNN Platform/Modules/HTML/EditHtml.ascx.cs index ad7a2f82695..ed9e00d5c75 100644 --- a/DNN Platform/Modules/HTML/EditHtml.ascx.cs +++ b/DNN Platform/Modules/HTML/EditHtml.ascx.cs @@ -34,21 +34,45 @@ public partial class EditHtml : HtmlModuleBase { private readonly INavigationManager _navigationManager; + private readonly HtmlTextController _htmlTextController = new HtmlTextController(); + private readonly HtmlTextLogController _htmlTextLogController = new HtmlTextLogController(); + private readonly WorkflowStateController _workflowStateController = new WorkflowStateController(); + public EditHtml() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private readonly HtmlTextController _htmlTextController = new HtmlTextController(); - private readonly HtmlTextLogController _htmlTextLogController = new HtmlTextLogController(); - private readonly WorkflowStateController _workflowStateController = new WorkflowStateController(); - private enum WorkflowType { DirectPublish = 1, ContentStaging = 2, } + protected string CurrentView + { + get + { + if (this.phEdit.Visible) + { + return "EditView"; + } + else if (this.phPreview.Visible) + { + return "PreviewView"; + } + + if (this.phHistory.Visible) + { + return "HistoryView"; + } + else + { + return string.Empty; + } + } + } + private int WorkflowID { get @@ -107,28 +131,161 @@ private WorkflowType CurrentWorkflowType } } - protected string CurrentView + protected override void OnInit(EventArgs e) { - get + base.OnInit(e); + + this.hlCancel.NavigateUrl = this._navigationManager.NavigateURL(); + + this.cmdEdit.Click += this.OnEditClick; + this.cmdPreview.Click += this.OnPreviewClick; + this.cmdHistory.Click += this.OnHistoryClick; + this.cmdMasterContent.Click += this.OnMasterContentClick; + this.ddlRender.SelectedIndexChanged += this.OnRenderSelectedIndexChanged; + this.cmdSave.Click += this.OnSaveClick; + this.dgHistory.RowDataBound += this.OnHistoryGridItemDataBound; + this.dgVersions.RowCommand += this.OnVersionsGridItemCommand; + this.dgVersions.RowDataBound += this.OnVersionsGridItemDataBound; + this.dgVersions.PageIndexChanged += this.OnVersionsGridPageIndexChanged; + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + try { - if (this.phEdit.Visible) + var htmlContentItemID = -1; + var htmlContent = this._htmlTextController.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); + + if (htmlContent != null) { - return "EditView"; + htmlContentItemID = htmlContent.ItemID; } - else if (this.phPreview.Visible) + + if (!this.Page.IsPostBack) { - return "PreviewView"; + var workflowStates = this._workflowStateController.GetWorkflowStates(this.WorkflowID); + var maxVersions = this._htmlTextController.GetMaximumVersionHistory(this.PortalId); + var userCanEdit = this.UserInfo.IsSuperUser || PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); + + this.lblMaxVersions.Text = maxVersions.ToString(); + this.dgVersions.PageSize = Math.Min(Math.Max(maxVersions, 5), 10); // min 5, max 10 + + switch (workflowStates.Count) + { + case 1: + this.CurrentWorkflowType = WorkflowType.DirectPublish; + break; + case 2: + this.CurrentWorkflowType = WorkflowType.ContentStaging; + break; + } + + if (htmlContentItemID != -1) + { + this.DisplayContent(htmlContent); + + // DisplayPreview(htmlContent); + this.DisplayHistory(htmlContent); + } + else + { + this.DisplayInitialContent(workflowStates[0] as WorkflowStateInfo); + } + + this.divPublish.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; + this.phCurrentVersion.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; + this.phPreviewVersion.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; + + // DisplayVersions(); + this.BindRenderItems(); + this.ddlRender.SelectedValue = this.txtContent.Mode; } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } - if (this.phHistory.Visible) + protected void OnSaveClick(object sender, EventArgs e) + { + const bool redirect = true; + + try + { + // get content + var htmlContent = this.GetLatestHTMLContent(); + + var aliases = from PortalAliasInfo pa in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalSettings.PortalId) + select pa.HTTPAlias; + string content; + if (this.phEdit.Visible) { - return "HistoryView"; + content = this.txtContent.Text; } else { - return string.Empty; + content = this.hfEditor.Value; + } + + if (this.Request.QueryString["nuru"] == null) + { + content = HtmlUtils.AbsoluteToRelativeUrls(content, aliases); + } + + htmlContent.Content = content; + + var draftStateID = this._workflowStateController.GetFirstWorkflowStateID(this.WorkflowID); + var publishedStateID = this._workflowStateController.GetLastWorkflowStateID(this.WorkflowID); + + switch (this.CurrentWorkflowType) + { + case WorkflowType.DirectPublish: + this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); + + break; + case WorkflowType.ContentStaging: + if (this.chkPublish.Checked) + { + // if it's already published set it to draft + if (htmlContent.StateID == publishedStateID) + { + htmlContent.StateID = draftStateID; + } + else + { + htmlContent.StateID = publishedStateID; + + // here it's in published mode + } + } + else + { + // if it's already published set it back to draft + if (htmlContent.StateID != draftStateID) + { + htmlContent.StateID = draftStateID; + } + } + + this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); + break; } } + catch (Exception exc) + { + Exceptions.LogException(exc); + UI.Skins.Skin.AddModuleMessage(this.Page, "Error occurred: ", exc.Message, ModuleMessage.ModuleMessageType.RedError); + return; + } + + // redirect back to portal + if (redirect) + { + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } } /// @@ -411,168 +568,11 @@ private HtmlTextInfo GetLastPublishedVersion(int publishedStateID) return (from version in this._htmlTextController.GetAllHtmlText(this.ModuleId) where version.StateID == publishedStateID orderby version.Version descending select version).ToList()[0]; } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.hlCancel.NavigateUrl = this._navigationManager.NavigateURL(); - - this.cmdEdit.Click += this.OnEditClick; - this.cmdPreview.Click += this.OnPreviewClick; - this.cmdHistory.Click += this.OnHistoryClick; - this.cmdMasterContent.Click += this.OnMasterContentClick; - this.ddlRender.SelectedIndexChanged += this.OnRenderSelectedIndexChanged; - this.cmdSave.Click += this.OnSaveClick; - this.dgHistory.RowDataBound += this.OnHistoryGridItemDataBound; - this.dgVersions.RowCommand += this.OnVersionsGridItemCommand; - this.dgVersions.RowDataBound += this.OnVersionsGridItemDataBound; - this.dgVersions.PageIndexChanged += this.OnVersionsGridPageIndexChanged; - } - private void OnRenderSelectedIndexChanged(object sender, EventArgs e) { this.txtContent.ChangeMode(this.ddlRender.SelectedValue); } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - try - { - var htmlContentItemID = -1; - var htmlContent = this._htmlTextController.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); - - if (htmlContent != null) - { - htmlContentItemID = htmlContent.ItemID; - } - - if (!this.Page.IsPostBack) - { - var workflowStates = this._workflowStateController.GetWorkflowStates(this.WorkflowID); - var maxVersions = this._htmlTextController.GetMaximumVersionHistory(this.PortalId); - var userCanEdit = this.UserInfo.IsSuperUser || PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); - - this.lblMaxVersions.Text = maxVersions.ToString(); - this.dgVersions.PageSize = Math.Min(Math.Max(maxVersions, 5), 10); // min 5, max 10 - - switch (workflowStates.Count) - { - case 1: - this.CurrentWorkflowType = WorkflowType.DirectPublish; - break; - case 2: - this.CurrentWorkflowType = WorkflowType.ContentStaging; - break; - } - - if (htmlContentItemID != -1) - { - this.DisplayContent(htmlContent); - - // DisplayPreview(htmlContent); - this.DisplayHistory(htmlContent); - } - else - { - this.DisplayInitialContent(workflowStates[0] as WorkflowStateInfo); - } - - this.divPublish.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; - this.phCurrentVersion.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; - this.phPreviewVersion.Visible = this.CurrentWorkflowType != WorkflowType.DirectPublish; - - // DisplayVersions(); - this.BindRenderItems(); - this.ddlRender.SelectedValue = this.txtContent.Mode; - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnSaveClick(object sender, EventArgs e) - { - const bool redirect = true; - - try - { - // get content - var htmlContent = this.GetLatestHTMLContent(); - - var aliases = from PortalAliasInfo pa in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalSettings.PortalId) - select pa.HTTPAlias; - string content; - if (this.phEdit.Visible) - { - content = this.txtContent.Text; - } - else - { - content = this.hfEditor.Value; - } - - if (this.Request.QueryString["nuru"] == null) - { - content = HtmlUtils.AbsoluteToRelativeUrls(content, aliases); - } - - htmlContent.Content = content; - - var draftStateID = this._workflowStateController.GetFirstWorkflowStateID(this.WorkflowID); - var publishedStateID = this._workflowStateController.GetLastWorkflowStateID(this.WorkflowID); - - switch (this.CurrentWorkflowType) - { - case WorkflowType.DirectPublish: - this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); - - break; - case WorkflowType.ContentStaging: - if (this.chkPublish.Checked) - { - // if it's already published set it to draft - if (htmlContent.StateID == publishedStateID) - { - htmlContent.StateID = draftStateID; - } - else - { - htmlContent.StateID = publishedStateID; - - // here it's in published mode - } - } - else - { - // if it's already published set it back to draft - if (htmlContent.StateID != draftStateID) - { - htmlContent.StateID = draftStateID; - } - } - - this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); - break; - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - UI.Skins.Skin.AddModuleMessage(this.Page, "Error occurred: ", exc.Message, ModuleMessage.ModuleMessageType.RedError); - return; - } - - // redirect back to portal - if (redirect) - { - this.Response.Redirect(this._navigationManager.NavigateURL(), true); - } - } - protected void OnEditClick(object sender, EventArgs e) { try @@ -607,43 +607,6 @@ protected void OnPreviewClick(object sender, EventArgs e) } } - private void OnHistoryClick(object sender, EventArgs e) - { - try - { - if (this.phEdit.Visible) - { - this.hfEditor.Value = this.txtContent.Text; - } - - this.DisplayVersions(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - private void OnMasterContentClick(object sender, EventArgs e) - { - try - { - this.phMasterContent.Visible = !this.phMasterContent.Visible; - this.cmdMasterContent.Text = this.phMasterContent.Visible ? - Localization.GetString("cmdHideMasterContent", this.LocalResourceFile) : - Localization.GetString("cmdShowMasterContent", this.LocalResourceFile); - - if (this.phMasterContent.Visible) - { - this.DisplayMasterLanguageContent(); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - protected void OnHistoryGridItemDataBound(object sender, GridViewRowEventArgs e) { var item = e.Row; @@ -707,9 +670,41 @@ protected void OnVersionsGridItemCommand(object source, GridViewCommandEventArgs } } - private HtmlTextInfo GetHTMLContent(GridViewCommandEventArgs e) + private void OnHistoryClick(object sender, EventArgs e) { - return this._htmlTextController.GetHtmlText(this.ModuleId, int.Parse(e.CommandArgument.ToString())); + try + { + if (this.phEdit.Visible) + { + this.hfEditor.Value = this.txtContent.Text; + } + + this.DisplayVersions(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + private void OnMasterContentClick(object sender, EventArgs e) + { + try + { + this.phMasterContent.Visible = !this.phMasterContent.Visible; + this.cmdMasterContent.Text = this.phMasterContent.Visible ? + Localization.GetString("cmdHideMasterContent", this.LocalResourceFile) : + Localization.GetString("cmdShowMasterContent", this.LocalResourceFile); + + if (this.phMasterContent.Visible) + { + this.DisplayMasterLanguageContent(); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } } protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e) @@ -781,6 +776,11 @@ protected void OnVersionsGridPageIndexChanged(object source, EventArgs e) this.DisplayVersions(); } + private HtmlTextInfo GetHTMLContent(GridViewCommandEventArgs e) + { + return this._htmlTextController.GetHtmlText(this.ModuleId, int.Parse(e.CommandArgument.ToString())); + } + private void BindRenderItems() { if (this.txtContent.IsRichEditorAvailable) diff --git a/DNN Platform/Modules/HTML/HtmlModule.ascx.cs b/DNN Platform/Modules/HTML/HtmlModule.ascx.cs index f600b3703c9..483a1a2352a 100644 --- a/DNN Platform/Modules/HTML/HtmlModule.ascx.cs +++ b/DNN Platform/Modules/HTML/HtmlModule.ascx.cs @@ -39,6 +39,112 @@ public HtmlModule() this._navigationManager = this.DependencyProvider.GetRequiredService(); } + /// ----------------------------------------------------------------------------- + /// + /// Gets moduleActions is an interface property that returns the module actions collection for the module. + /// + /// + /// + /// ----------------------------------------------------------------------------- + public ModuleActionCollection ModuleActions + { + get + { + // add the Edit Text action + var Actions = new ModuleActionCollection(); + Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + string.Empty, + this.EditUrl(), + false, + SecurityAccessLevel.Edit, + true, + false); + + // get the content + var objHTML = new HtmlTextController(); + var objWorkflow = new WorkflowStateController(); + this.WorkflowID = objHTML.GetWorkflow(this.ModuleId, this.TabId, this.PortalId).Value; + + HtmlTextInfo objContent = objHTML.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); + if (objContent != null) + { + // if content is in the first state + if (objContent.StateID == objWorkflow.GetFirstWorkflowStateID(this.WorkflowID)) + { + // if not direct publish workflow + if (objWorkflow.GetWorkflowStates(this.WorkflowID).Count > 1) + { + // add publish action + Actions.Add( + this.GetNextActionID(), + Localization.GetString("PublishContent.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + "publish", + "grant.gif", + string.Empty, + true, + SecurityAccessLevel.Edit, + true, + false); + } + } + else + { + // if the content is not in the last state of the workflow then review is required + if (objContent.StateID != objWorkflow.GetLastWorkflowStateID(this.WorkflowID)) + { + // if the user has permissions to review the content + if (WorkflowStatePermissionController.HasWorkflowStatePermission(WorkflowStatePermissionController.GetWorkflowStatePermissions(objContent.StateID), "REVIEW")) + { + // add approve and reject actions + Actions.Add( + this.GetNextActionID(), + Localization.GetString("ApproveContent.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "grant.gif", + this.EditUrl("action", "approve", "Review"), + false, + SecurityAccessLevel.Edit, + true, + false); + Actions.Add( + this.GetNextActionID(), + Localization.GetString("RejectContent.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "deny.gif", + this.EditUrl("action", "reject", "Review"), + false, + SecurityAccessLevel.Edit, + true, + false); + } + } + } + } + + // add mywork to action menu + Actions.Add( + this.GetNextActionID(), + Localization.GetString("MyWork.Action", this.LocalResourceFile), + "MyWork.Action", + string.Empty, + "view.gif", + this.EditUrl("MyWork"), + false, + SecurityAccessLevel.Edit, + true, + false); + + return Actions; + } + } + /// ----------------------------------------------------------------------------- /// /// Page_Init runs when the control is initialized. @@ -253,111 +359,5 @@ private void ModuleAction_Click(object sender, ActionEventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets moduleActions is an interface property that returns the module actions collection for the module. - /// - /// - /// - /// ----------------------------------------------------------------------------- - public ModuleActionCollection ModuleActions - { - get - { - // add the Edit Text action - var Actions = new ModuleActionCollection(); - Actions.Add( - this.GetNextActionID(), - Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), - ModuleActionType.AddContent, - string.Empty, - string.Empty, - this.EditUrl(), - false, - SecurityAccessLevel.Edit, - true, - false); - - // get the content - var objHTML = new HtmlTextController(); - var objWorkflow = new WorkflowStateController(); - this.WorkflowID = objHTML.GetWorkflow(this.ModuleId, this.TabId, this.PortalId).Value; - - HtmlTextInfo objContent = objHTML.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); - if (objContent != null) - { - // if content is in the first state - if (objContent.StateID == objWorkflow.GetFirstWorkflowStateID(this.WorkflowID)) - { - // if not direct publish workflow - if (objWorkflow.GetWorkflowStates(this.WorkflowID).Count > 1) - { - // add publish action - Actions.Add( - this.GetNextActionID(), - Localization.GetString("PublishContent.Action", this.LocalResourceFile), - ModuleActionType.AddContent, - "publish", - "grant.gif", - string.Empty, - true, - SecurityAccessLevel.Edit, - true, - false); - } - } - else - { - // if the content is not in the last state of the workflow then review is required - if (objContent.StateID != objWorkflow.GetLastWorkflowStateID(this.WorkflowID)) - { - // if the user has permissions to review the content - if (WorkflowStatePermissionController.HasWorkflowStatePermission(WorkflowStatePermissionController.GetWorkflowStatePermissions(objContent.StateID), "REVIEW")) - { - // add approve and reject actions - Actions.Add( - this.GetNextActionID(), - Localization.GetString("ApproveContent.Action", this.LocalResourceFile), - ModuleActionType.AddContent, - string.Empty, - "grant.gif", - this.EditUrl("action", "approve", "Review"), - false, - SecurityAccessLevel.Edit, - true, - false); - Actions.Add( - this.GetNextActionID(), - Localization.GetString("RejectContent.Action", this.LocalResourceFile), - ModuleActionType.AddContent, - string.Empty, - "deny.gif", - this.EditUrl("action", "reject", "Review"), - false, - SecurityAccessLevel.Edit, - true, - false); - } - } - } - } - - // add mywork to action menu - Actions.Add( - this.GetNextActionID(), - Localization.GetString("MyWork.Action", this.LocalResourceFile), - "MyWork.Action", - string.Empty, - "view.gif", - this.EditUrl("MyWork"), - false, - SecurityAccessLevel.Edit, - true, - false); - - return Actions; - } - } } } diff --git a/DNN Platform/Modules/HTML/Settings.ascx.cs b/DNN Platform/Modules/HTML/Settings.ascx.cs index dc3a28ed1a5..7922315633c 100644 --- a/DNN Platform/Modules/HTML/Settings.ascx.cs +++ b/DNN Platform/Modules/HTML/Settings.ascx.cs @@ -29,38 +29,6 @@ public partial class Settings : ModuleSettingsBase } } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - this.cboWorkflow.SelectedIndexChanged += this.OnWorkflowSelectedIndexChanged; - } - - protected void OnWorkflowSelectedIndexChanged(object sender, EventArgs e) - { - this.DisplayWorkflowDetails(); - } - - private void DisplayWorkflowDetails() - { - if (this.cboWorkflow.SelectedValue != null) - { - var objWorkflow = new WorkflowStateController(); - var strDescription = string.Empty; - var arrStates = objWorkflow.GetWorkflowStates(int.Parse(this.cboWorkflow.SelectedValue)); - if (arrStates.Count > 0) - { - foreach (WorkflowStateInfo objState in arrStates) - { - strDescription = strDescription + " >> " + "" + objState.StateName + ""; - } - - strDescription = strDescription + "
" + ((WorkflowStateInfo)arrStates[0]).Description; - } - - this.lblDescription.Text = strDescription; - } - } - /// /// LoadSettings loads the settings from the Database and displays them. /// @@ -162,5 +130,37 @@ public override void UpdateSettings() Exceptions.ProcessModuleLoadException(this, exc); } } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.cboWorkflow.SelectedIndexChanged += this.OnWorkflowSelectedIndexChanged; + } + + protected void OnWorkflowSelectedIndexChanged(object sender, EventArgs e) + { + this.DisplayWorkflowDetails(); + } + + private void DisplayWorkflowDetails() + { + if (this.cboWorkflow.SelectedValue != null) + { + var objWorkflow = new WorkflowStateController(); + var strDescription = string.Empty; + var arrStates = objWorkflow.GetWorkflowStates(int.Parse(this.cboWorkflow.SelectedValue)); + if (arrStates.Count > 0) + { + foreach (WorkflowStateInfo objState in arrStates) + { + strDescription = strDescription + " >> " + "" + objState.StateName + ""; + } + + strDescription = strDescription + "
" + ((WorkflowStateInfo)arrStates[0]).Description; + } + + this.lblDescription.Text = strDescription; + } + } } } diff --git a/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs b/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs index 6045fd811aa..f31330f2029 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs @@ -104,41 +104,6 @@ public string UpgradeModule(string version) return "Success"; } - /// Gets the module definition identifier. - /// Name of the module. - /// Name of the module definition. - /// The Module Id for the HTML Editor Management module. - private int GetModuleDefinitionID(string moduleName, string moduleDefinitionName) - { - // get desktop module - DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, Null.NullInteger); - if (desktopModule == null) - { - return -1; - } - - // get module definition - ModuleDefinitionInfo moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByDefinitionName( - moduleDefinitionName, - desktopModule.DesktopModuleID); - if (moduleDefinition == null) - { - return -1; - } - - return moduleDefinition.ModuleDefID; - } - - private bool RadEditorProviderInstalled() - { - return PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name.Equals("DotNetNuke.RadEditorProvider")) != null; - } - - private bool TelerikAssemblyExists() - { - return File.Exists(Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll")); - } - private static void UpdateRadCfgFiles() { var folder = Path.Combine(Globals.ApplicationMapPath, @"DesktopModules\Admin\RadEditorProvider\ConfigFile"); @@ -196,6 +161,41 @@ private static void UpdateRadCfgFiles(string folder, string mask) } } + /// Gets the module definition identifier. + /// Name of the module. + /// Name of the module definition. + /// The Module Id for the HTML Editor Management module. + private int GetModuleDefinitionID(string moduleName, string moduleDefinitionName) + { + // get desktop module + DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(moduleName, Null.NullInteger); + if (desktopModule == null) + { + return -1; + } + + // get module definition + ModuleDefinitionInfo moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByDefinitionName( + moduleDefinitionName, + desktopModule.DesktopModuleID); + if (moduleDefinition == null) + { + return -1; + } + + return moduleDefinition.ModuleDefID; + } + + private bool RadEditorProviderInstalled() + { + return PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name.Equals("DotNetNuke.RadEditorProvider")) != null; + } + + private bool TelerikAssemblyExists() + { + return File.Exists(Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll")); + } + private static string UpdateWebConfigFile() { return UpdateTelerikEncryptionKey("Telerik.AsyncUpload.ConfigurationEncryptionKey"); diff --git a/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs b/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs index 0dffc3d2416..f0e57a3ffe2 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs @@ -39,6 +39,11 @@ public PlaceHolder Editor } } + public void Refresh() + { + this.Response.Redirect(this.Request.RawUrl, true); + } + /// Handles the Click event of the SaveButton control. /// The source of the event. /// The instance containing the event data. @@ -55,11 +60,6 @@ protected void ProvidersDropDownList_SelectedIndexChanged(object sender, EventAr this.EditorChanged(this, new EditorEventArgs(this.ProvidersDropDownList.SelectedValue)); } - public void Refresh() - { - this.Response.Redirect(this.Request.RawUrl, true); - } - protected override void OnInit(EventArgs e) { var currentUser = UserController.Instance.GetCurrentUserInfo(); diff --git a/DNN Platform/Modules/Journal/Components/FeatureController.cs b/DNN Platform/Modules/Journal/Components/FeatureController.cs index adc69f7bc3d..455c2a76fff 100644 --- a/DNN Platform/Modules/Journal/Components/FeatureController.cs +++ b/DNN Platform/Modules/Journal/Components/FeatureController.cs @@ -44,13 +44,13 @@ namespace DotNetNuke.Modules.Journal.Components // uncomment the interfaces to add the support. public class FeatureController : ModuleSearchBase, IModuleSearchResultController { - protected INavigationManager NavigationManager { get; } - public FeatureController() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } + /// ----------------------------------------------------------------------------- /// /// ExportModule implements the IPortable ExportModule Interface. diff --git a/DNN Platform/Modules/Journal/Components/JournalParser.cs b/DNN Platform/Modules/Journal/Components/JournalParser.cs index bde4952d8c1..21a8b951e21 100644 --- a/DNN Platform/Modules/Journal/Components/JournalParser.cs +++ b/DNN Platform/Modules/Journal/Components/JournalParser.cs @@ -26,6 +26,15 @@ namespace DotNetNuke.Modules.Journal.Components public class JournalParser { + private const string ResxPath = "~/DesktopModules/Journal/App_LocalResources/SharedResources.resx"; + private static readonly Regex CdataRegex = new Regex(@"\<\!\[CDATA\[(?[^\]]*)\]\]\>", RegexOptions.Compiled); + + private readonly string url = string.Empty; + private bool isAdmin; + private bool isUnverifiedUser; + + public int JournalId { get; set; } + protected INavigationManager NavigationManager { get; } private PortalSettings PortalSettings { get; set; } @@ -39,16 +48,9 @@ public class JournalParser private UserInfo CurrentUser { get; set; } private int OwnerPortalId { get; set; } - - public int JournalId { get; set; } - - private readonly string url = string.Empty; - private bool isAdmin; - private bool isUnverifiedUser; - private const string ResxPath = "~/DesktopModules/Journal/App_LocalResources/SharedResources.resx"; - - private static readonly Regex CdataRegex = new Regex(@"\<\!\[CDATA\[(?[^\]]*)\]\]\>", RegexOptions.Compiled); private static readonly Regex TemplateRegex = new Regex("{CanComment}(.*?){/CanComment}", RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private static readonly Regex BaseUrlRegex = new Regex("\\[BaseUrl\\]", RegexOptions.Compiled | RegexOptions.IgnoreCase); public JournalParser(PortalSettings portalSettings, int moduleId, int profileId, int socialGroupId, UserInfo userInfo) { @@ -78,8 +80,6 @@ public JournalParser(PortalSettings portalSettings, int moduleId, int profileId, !HttpContext.Current.Request.Url.IsDefaultPort && !this.url.Contains(":") ? ":" + HttpContext.Current.Request.Url.Port : string.Empty); } - private static readonly Regex BaseUrlRegex = new Regex("\\[BaseUrl\\]", RegexOptions.Compiled | RegexOptions.IgnoreCase); - public string GetList(int currentIndex, int rows) { if (this.CurrentUser.UserID > 0) @@ -312,35 +312,35 @@ internal string GetLikeListHTML(JournalItem ji, ref bool isLiked) else if (xc > 1) { sb.Append(" {resx:likethis}"); - } - } + } + } else - { - foreach (XmlNode l in xLikes) - { - int userId = Convert.ToInt32(l.Attributes["uid"].Value); - string name = l.Attributes["un"].Value; - sb.AppendFormat("{1}", userId, name); - xc += 1; - if (xc == xLikes.Count - 1) - { - sb.Append(" {resx:and} "); + { + foreach (XmlNode l in xLikes) + { + int userId = Convert.ToInt32(l.Attributes["uid"].Value); + string name = l.Attributes["un"].Value; + sb.AppendFormat("{1}", userId, name); + xc += 1; + if (xc == xLikes.Count - 1) + { + sb.Append(" {resx:and} "); + } + else if (xc < xLikes.Count - 1) + { + sb.Append(", "); + } } - else if (xc < xLikes.Count - 1) - { - sb.Append(", "); - } - } - if (xc == 1) - { - sb.Append(" {resx:likesthis}"); - } - else if (xc > 1) - { - sb.Append(" {resx:likethis}"); + if (xc == 1) + { + sb.Append(" {resx:likesthis}"); + } + else if (xc > 1) + { + sb.Append(" {resx:likethis}"); + } } - } sb.Append(""); return sb.ToString(); diff --git a/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs b/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs index 032867aa522..803f31f9245 100644 --- a/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs +++ b/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs @@ -14,13 +14,13 @@ public class ProfilePicPropertyAccess : IPropertyAccess { private readonly int _userId; - public int Size { get; set; } = 32; - public ProfilePicPropertyAccess(int userId) { this._userId = userId; } + public int Size { get; set; } = 32; + public CacheLevel Cacheability => CacheLevel.notCacheable; public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) diff --git a/DNN Platform/Modules/Journal/Components/Utilities.cs b/DNN Platform/Modules/Journal/Components/Utilities.cs index b2db6109184..98e27170a73 100644 --- a/DNN Platform/Modules/Journal/Components/Utilities.cs +++ b/DNN Platform/Modules/Journal/Components/Utilities.cs @@ -39,6 +39,43 @@ public class Utilities private static readonly Regex HtmlTextRegex = new Regex("<(.|\\n)*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + public static string LocalizeControl(string controlText) + { + string sKey = string.Empty; + string sReplace = string.Empty; + MatchCollection matches = default(MatchCollection); + matches = ResexRegex.Matches(controlText); + foreach (Match match in matches) + { + sKey = match.Value; + sReplace = GetSharedResource(sKey); + + string newValue = match.Value; + if (!string.IsNullOrEmpty(sReplace)) + { + newValue = sReplace; + } + + controlText = controlText.Replace(sKey, newValue); + } + + return controlText; + } + + public static string GetSharedResource(string key) + { + string sValue = key; + sValue = DotNetNuke.Services.Localization.Localization.GetString(key, Constants.SharedResourcesPath); + if (sValue == string.Empty) + { + return key; + } + else + { + return sValue; + } + } + internal static Bitmap GetImageFromURL(string url) { string sImgName = string.Empty; @@ -289,43 +326,6 @@ internal static string GetPageFromURL(ref string url, string username, string pa return sHTML; } - public static string LocalizeControl(string controlText) - { - string sKey = string.Empty; - string sReplace = string.Empty; - MatchCollection matches = default(MatchCollection); - matches = ResexRegex.Matches(controlText); - foreach (Match match in matches) - { - sKey = match.Value; - sReplace = GetSharedResource(sKey); - - string newValue = match.Value; - if (!string.IsNullOrEmpty(sReplace)) - { - newValue = sReplace; - } - - controlText = controlText.Replace(sKey, newValue); - } - - return controlText; - } - - public static string GetSharedResource(string key) - { - string sValue = key; - sValue = DotNetNuke.Services.Localization.Localization.GetString(key, Constants.SharedResourcesPath); - if (sValue == string.Empty) - { - return key; - } - else - { - return sValue; - } - } - public static string RemoveHTML(string sText) { if (string.IsNullOrEmpty(sText)) diff --git a/DNN Platform/Modules/Journal/FileUploadController.cs b/DNN Platform/Modules/Journal/FileUploadController.cs index ac7ca0fa1e1..793a5a0e5b7 100644 --- a/DNN Platform/Modules/Journal/FileUploadController.cs +++ b/DNN Platform/Modules/Journal/FileUploadController.cs @@ -23,6 +23,8 @@ 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" }; + [DnnAuthorize] [HttpPost] [IFrameSupportedValidateAntiForgeryToken] @@ -42,6 +44,11 @@ public HttpResponseMessage UploadFile() return this.IframeSafeJson(statuses); } + private static bool IsImageExtension(string extension) + { + return ImageExtensions.Contains(extension.ToUpper()); + } + private HttpResponseMessage IframeSafeJson(List statuses) { // return json but label it as plain text @@ -51,13 +58,6 @@ private HttpResponseMessage IframeSafeJson(List statuses) }; } - private static readonly List ImageExtensions = new List { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG", ".JPEG", ".ICO", ".SVG" }; - - private static bool IsImageExtension(string extension) - { - return ImageExtensions.Contains(extension.ToUpper()); - } - // Upload entire file private void UploadWholeFile(HttpContextBase context, ICollection statuses) { diff --git a/DNN Platform/Modules/Journal/FilesStatus.cs b/DNN Platform/Modules/Journal/FilesStatus.cs index 964080798dc..3057120dadd 100644 --- a/DNN Platform/Modules/Journal/FilesStatus.cs +++ b/DNN Platform/Modules/Journal/FilesStatus.cs @@ -6,6 +6,11 @@ namespace DotNetNuke.Modules.Journal { public class FilesStatus { + // ReSharper restore InconsistentNaming + public FilesStatus() + { + } + // ReSharper disable InconsistentNaming public bool success { get; set; } @@ -26,10 +31,5 @@ public class FilesStatus public string message { get; set; } public int file_id { get; set; } - - // ReSharper restore InconsistentNaming - public FilesStatus() - { - } } } diff --git a/DNN Platform/Modules/Journal/MyFiles.ascx.cs b/DNN Platform/Modules/Journal/MyFiles.ascx.cs index f4132793037..13c18e49624 100644 --- a/DNN Platform/Modules/Journal/MyFiles.ascx.cs +++ b/DNN Platform/Modules/Journal/MyFiles.ascx.cs @@ -19,12 +19,6 @@ protected override void OnInit(EventArgs e) this.InitializeComponent(); base.OnInit(e); } - - private void InitializeComponent() - { - this.Load += new System.EventHandler(this.Page_Load); - this.btnUp.Click += new System.EventHandler(this.btnUp_Upload); - } protected void Page_Load(object sender, EventArgs e) { @@ -67,5 +61,11 @@ protected void btnUp_Upload(object sender, EventArgs e) this.litOut.Text = message; } } + + private void InitializeComponent() + { + this.Load += new System.EventHandler(this.Page_Load); + this.btnUp.Click += new System.EventHandler(this.btnUp_Upload); + } } } diff --git a/DNN Platform/Modules/Journal/NotificationServicesController.cs b/DNN Platform/Modules/Journal/NotificationServicesController.cs index 1af65688cc0..1c9a434d04c 100644 --- a/DNN Platform/Modules/Journal/NotificationServicesController.cs +++ b/DNN Platform/Modules/Journal/NotificationServicesController.cs @@ -24,11 +24,6 @@ public class NotificationServicesController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(NotificationServicesController)); - public class NotificationDTO - { - public int NotificationId { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage ViewJournal(NotificationDTO postData) @@ -61,5 +56,10 @@ public HttpResponseMessage ViewJournal(NotificationDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } + + public class NotificationDTO + { + public int NotificationId { get; set; } + } } } diff --git a/DNN Platform/Modules/Journal/ServicesController.cs b/DNN Platform/Modules/Journal/ServicesController.cs index b4203ce3ec1..8beeb59b4c3 100644 --- a/DNN Platform/Modules/Journal/ServicesController.cs +++ b/DNN Platform/Modules/Journal/ServicesController.cs @@ -32,36 +32,77 @@ namespace DotNetNuke.Modules.Journal [SupportedModules("Journal")] public class ServicesController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ServicesController)); - private const int MentionNotificationLength = 100; private const string MentionNotificationSuffix = "..."; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ServicesController)); private const string MentionIdentityChar = "@"; private static readonly string[] AcceptedFileExtensions = { "jpg", "png", "gif", "jpe", "jpeg", "tiff", "bmp" }; - - public class CreateDTO + + [HttpPost] + [ValidateAntiForgeryToken] + [DnnAuthorize(DenyRoles = "Unverified Users")] + public HttpResponseMessage Create(CreateDTO postData) { - public string Text { get; set; } - - public int ProfileId { get; set; } - - public string JournalType { get; set; } - - public string ItemData { get; set; } - - public string SecuritySet { get; set; } - - public int GroupId { get; set; } - - public IList Mentions { get; set; } + try + { + int userId = this.UserInfo.UserID; + IDictionary mentionedUsers = new Dictionary(); + + if (postData.ProfileId == -1) + { + postData.ProfileId = userId; + } + + this.checkProfileAccess(postData.ProfileId, this.UserInfo); + + this.checkGroupAccess(postData); + + var journalItem = this.prepareJournalItem(postData, mentionedUsers); + + JournalController.Instance.SaveJournalItem(journalItem, this.ActiveModule); + + var originalSummary = journalItem.Summary; + this.SendMentionNotifications(mentionedUsers, journalItem, originalSummary); + + return this.Request.CreateResponse(HttpStatusCode.OK, journalItem); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } } - public class MentionDTO + [HttpPost] + [ValidateAntiForgeryToken] + [DnnAuthorize(DenyRoles = "Unverified Users")] + public HttpResponseMessage Delete(JournalIdDTO postData) { - public string DisplayName { get; set; } - - public int UserId { get; set; } + try + { + var jc = JournalController.Instance; + var ji = jc.GetJournalItem(this.ActiveModule.OwnerPortalID, this.UserInfo.UserID, postData.JournalId); + + if (ji == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "invalid request"); + } + + if (ji.UserId == this.UserInfo.UserID || ji.ProfileId == this.UserInfo.UserID || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) + { + jc.DeleteJournalItem(this.PortalSettings.PortalId, this.UserInfo.UserID, postData.JournalId); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + + return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "access denied"); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } } private static bool IsImageFile(string relativePath) @@ -88,34 +129,70 @@ private static bool IsAllowedLink(string url) { return !string.IsNullOrEmpty(url) && !url.Contains("//"); } + + public class CreateDTO + { + public string Text { get; set; } + + public int ProfileId { get; set; } + + public string JournalType { get; set; } + + public string ItemData { get; set; } + + public string SecuritySet { get; set; } + + public int GroupId { get; set; } + + public IList Mentions { get; set; } + } + + public class MentionDTO + { + public string DisplayName { get; set; } + + public int UserId { get; set; } + } [HttpPost] [ValidateAntiForgeryToken] [DnnAuthorize(DenyRoles = "Unverified Users")] - public HttpResponseMessage Create(CreateDTO postData) + public HttpResponseMessage SoftDelete(JournalIdDTO postData) { try { - int userId = this.UserInfo.UserID; - IDictionary mentionedUsers = new Dictionary(); + var jc = JournalController.Instance; + var ji = jc.GetJournalItem(this.ActiveModule.OwnerPortalID, this.UserInfo.UserID, postData.JournalId); - if (postData.ProfileId == -1) + if (ji == null) { - postData.ProfileId = userId; + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "invalid request"); } - this.checkProfileAccess(postData.ProfileId, this.UserInfo); - - this.checkGroupAccess(postData); - - var journalItem = this.prepareJournalItem(postData, mentionedUsers); - - JournalController.Instance.SaveJournalItem(journalItem, this.ActiveModule); + if (ji.UserId == this.UserInfo.UserID || ji.ProfileId == this.UserInfo.UserID || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) + { + jc.SoftDeleteJournalItem(this.PortalSettings.PortalId, this.UserInfo.UserID, postData.JournalId); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } - var originalSummary = journalItem.Summary; - this.SendMentionNotifications(mentionedUsers, journalItem, originalSummary); + return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "access denied"); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } - return this.Request.CreateResponse(HttpStatusCode.OK, journalItem); + [HttpPost] + [ValidateAntiForgeryToken] + [DnnAuthorize] + public HttpResponseMessage PreviewUrl(PreviewDTO postData) + { + try + { + var link = Utilities.GetLinkData(postData.Url); + return this.Request.CreateResponse(HttpStatusCode.OK, link); } catch (Exception exc) { @@ -256,99 +333,6 @@ public class JournalIdDTO public int JournalId { get; set; } } - [HttpPost] - [ValidateAntiForgeryToken] - [DnnAuthorize(DenyRoles = "Unverified Users")] - public HttpResponseMessage Delete(JournalIdDTO postData) - { - try - { - var jc = JournalController.Instance; - var ji = jc.GetJournalItem(this.ActiveModule.OwnerPortalID, this.UserInfo.UserID, postData.JournalId); - - if (ji == null) - { - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "invalid request"); - } - - if (ji.UserId == this.UserInfo.UserID || ji.ProfileId == this.UserInfo.UserID || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) - { - jc.DeleteJournalItem(this.PortalSettings.PortalId, this.UserInfo.UserID, postData.JournalId); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - - return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "access denied"); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - [HttpPost] - [ValidateAntiForgeryToken] - [DnnAuthorize(DenyRoles = "Unverified Users")] - public HttpResponseMessage SoftDelete(JournalIdDTO postData) - { - try - { - var jc = JournalController.Instance; - var ji = jc.GetJournalItem(this.ActiveModule.OwnerPortalID, this.UserInfo.UserID, postData.JournalId); - - if (ji == null) - { - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "invalid request"); - } - - if (ji.UserId == this.UserInfo.UserID || ji.ProfileId == this.UserInfo.UserID || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) - { - jc.SoftDeleteJournalItem(this.PortalSettings.PortalId, this.UserInfo.UserID, postData.JournalId); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - - return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "access denied"); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - public class PreviewDTO - { - public string Url { get; set; } - } - - [HttpPost] - [ValidateAntiForgeryToken] - [DnnAuthorize] - public HttpResponseMessage PreviewUrl(PreviewDTO postData) - { - try - { - var link = Utilities.GetLinkData(postData.Url); - return this.Request.CreateResponse(HttpStatusCode.OK, link); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - public class GetListForProfileDTO - { - public int ProfileId { get; set; } - - public int GroupId { get; set; } - - public int RowIndex { get; set; } - - public int MaxRows { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage GetListForProfile(GetListForProfileDTO postData) @@ -387,15 +371,6 @@ public HttpResponseMessage Like(JournalIdDTO postData) } } - public class CommentSaveDTO - { - public int JournalId { get; set; } - - public string Comment { get; set; } - - public IList Mentions { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] [DnnAuthorize(DenyRoles = "Unverified Users")] @@ -426,12 +401,21 @@ public HttpResponseMessage CommentSave(CommentSaveDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } + + public class PreviewDTO + { + public string Url { get; set; } + } - public class CommentDeleteDTO + public class GetListForProfileDTO { - public int JournalId { get; set; } + public int ProfileId { get; set; } - public int CommentId { get; set; } + public int GroupId { get; set; } + + public int RowIndex { get; set; } + + public int MaxRows { get; set; } } [HttpPost] @@ -469,17 +453,6 @@ public HttpResponseMessage CommentDelete(CommentDeleteDTO postData) } } - public class SuggestDTO - { - public string displayName { get; set; } - - public int userId { get; set; } - - public string avatar { get; set; } - - public string key { get; set; } - } - [HttpGet] [DnnAuthorize(DenyRoles = "Unverified Users")] public HttpResponseMessage GetSuggestions(string keyword) @@ -500,13 +473,13 @@ public HttpResponseMessage GetSuggestions(string keyword) || targetUser.DisplayName.ToLowerInvariant().Contains(keyword.Replace("-", " ").ToLowerInvariant())) && findedUsers.All(s => s.userId != targetUser.UserID)) { - findedUsers.Add(new SuggestDTO - { - displayName = targetUser.DisplayName.Replace(" ", "-"), - userId = targetUser.UserID, - avatar = targetUser.Profile.PhotoURL, - key = keyword, - }); + findedUsers.Add(new SuggestDTO + { + displayName = targetUser.DisplayName.Replace(" ", "-"), + userId = targetUser.UserID, + avatar = targetUser.Profile.PhotoURL, + key = keyword, + }); } } @@ -581,6 +554,33 @@ private void SendMentionNotifications(IDictionary mentionedUse } } + public class CommentSaveDTO + { + public int JournalId { get; set; } + + public string Comment { get; set; } + + public IList Mentions { get; set; } + } + + public class CommentDeleteDTO + { + public int JournalId { get; set; } + + public int CommentId { get; set; } + } + + public class SuggestDTO + { + public string displayName { get; set; } + + public int userId { get; set; } + + public string avatar { get; set; } + + public string key { get; set; } + } + private bool IsCurrentUserFile(IFileInfo file) { if (file == null) diff --git a/DNN Platform/Modules/Journal/View.ascx.cs b/DNN Platform/Modules/Journal/View.ascx.cs index 4043efc9583..a0e302f8116 100644 --- a/DNN Platform/Modules/Journal/View.ascx.cs +++ b/DNN Platform/Modules/Journal/View.ascx.cs @@ -39,9 +39,9 @@ namespace DotNetNuke.Modules.Journal /// ----------------------------------------------------------------------------- public partial class View : JournalModuleBase { - private readonly INavigationManager _navigationManager; public int PageSize = 20; public bool AllowPhotos = true; + private readonly INavigationManager _navigationManager; public bool AllowFiles = true; public int MaxMessageLength = 250; public bool CanRender = true; diff --git a/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs b/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs index 2e24dbd94b3..b7f34e35750 100644 --- a/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs +++ b/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs @@ -28,6 +28,53 @@ public class MemberDirectoryController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MemberDirectoryController)); + [HttpGet] + public HttpResponseMessage AdvancedSearch(int userId, int groupId, int pageIndex, int pageSize, string searchTerm1, string searchTerm2, string searchTerm3, string searchTerm4) + { + try + { + if (userId < 0) + { + userId = this.PortalSettings.UserId; + } + + var searchField1 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField1", "DisplayName"); + var searchField2 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField2", "Email"); + var searchField3 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField3", "City"); + var searchField4 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField4", "Country"); + + var propertyNames = string.Empty; + var propertyValues = string.Empty; + AddSearchTerm(ref propertyNames, ref propertyValues, searchField1, searchTerm1); + AddSearchTerm(ref propertyNames, ref propertyValues, searchField2, searchTerm2); + AddSearchTerm(ref propertyNames, ref propertyValues, searchField3, searchTerm3); + AddSearchTerm(ref propertyNames, ref propertyValues, searchField4, searchTerm4); + + var members = this.GetUsers(userId, groupId, searchTerm1, pageIndex, pageSize, propertyNames, propertyValues); + return this.Request.CreateResponse(HttpStatusCode.OK, this.GetMembers(members)); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpGet] + public HttpResponseMessage BasicSearch(int groupId, string searchTerm, int pageIndex, int pageSize) + { + try + { + var users = this.GetUsers(-1, groupId, string.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.Trim(), pageIndex, pageSize, string.Empty, string.Empty); + return this.Request.CreateResponse(HttpStatusCode.OK, this.GetMembers(users)); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + private static void AddSearchTerm(ref string propertyNames, ref string propertyValues, string name, string value) { if (!string.IsNullOrEmpty(value)) @@ -55,6 +102,17 @@ private static string GetMatchedListEntryIds(string name, string value) return $"${string.Join("$", listEntries)}$"; } + private static string GetSetting(IDictionary settings, string key, string defaultValue) + { + var setting = defaultValue; + if (settings[key] != null) + { + setting = Convert.ToString(settings[key]); + } + + return setting; + } + private bool CanViewGroupMembers(int portalId, int groupId) { var group = RoleController.Instance.GetRole(portalId, r => r.RoleID == groupId); @@ -81,17 +139,6 @@ private IList GetMembers(IEnumerable users) return users.Select(user => new Member(user, this.PortalSettings)).ToList(); } - private static string GetSetting(IDictionary settings, string key, string defaultValue) - { - var setting = defaultValue; - if (settings[key] != null) - { - setting = Convert.ToString(settings[key]); - } - - return setting; - } - private IEnumerable GetUsers(int userId, int groupId, string searchTerm, int pageIndex, int pageSize, string propertyNames, string propertyValues) { var portalId = this.PortalSettings.PortalId; @@ -191,53 +238,6 @@ private IEnumerable FilterExcludedUsers(IEnumerable users) { return users.Where(u => !u.IsSuperUser).Select(u => u).ToList(); } - - [HttpGet] - public HttpResponseMessage AdvancedSearch(int userId, int groupId, int pageIndex, int pageSize, string searchTerm1, string searchTerm2, string searchTerm3, string searchTerm4) - { - try - { - if (userId < 0) - { - userId = this.PortalSettings.UserId; - } - - var searchField1 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField1", "DisplayName"); - var searchField2 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField2", "Email"); - var searchField3 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField3", "City"); - var searchField4 = GetSetting(this.ActiveModule.TabModuleSettings, "SearchField4", "Country"); - - var propertyNames = string.Empty; - var propertyValues = string.Empty; - AddSearchTerm(ref propertyNames, ref propertyValues, searchField1, searchTerm1); - AddSearchTerm(ref propertyNames, ref propertyValues, searchField2, searchTerm2); - AddSearchTerm(ref propertyNames, ref propertyValues, searchField3, searchTerm3); - AddSearchTerm(ref propertyNames, ref propertyValues, searchField4, searchTerm4); - - var members = this.GetUsers(userId, groupId, searchTerm1, pageIndex, pageSize, propertyNames, propertyValues); - return this.Request.CreateResponse(HttpStatusCode.OK, this.GetMembers(members)); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - [HttpGet] - public HttpResponseMessage BasicSearch(int groupId, string searchTerm, int pageIndex, int pageSize) - { - try - { - var users = this.GetUsers(-1, groupId, string.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.Trim(), pageIndex, pageSize, string.Empty, string.Empty); - return this.Request.CreateResponse(HttpStatusCode.OK, this.GetMembers(users)); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } [HttpGet] public HttpResponseMessage GetMember(int userId) diff --git a/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs b/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs index e8dc8f5d053..197b2ba7426 100644 --- a/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs +++ b/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs @@ -27,6 +27,8 @@ namespace DotNetNuke.Modules.MemberDirectory [PresenterBinding(typeof(ModuleSettingsPresenter))] public partial class Settings : SettingsView { + public const int DefaultPageSize = 20; + private static string templatePath = "~/DesktopModules/MemberDirectory/Templates/"; private string _defaultSearchField1 = "DisplayName"; @@ -74,8 +76,6 @@ public static string DefaultItemTemplate } } - public const int DefaultPageSize = 20; - public static string DefaultPopUpTemplate { get @@ -171,17 +171,6 @@ protected override void OnLoad(EventArgs e) } } - private ListItemCollection GetPropertiesCollection(string profileResourceFile) - { - var result = new ListItemCollection(); - foreach (var property in this.Model.ProfileProperties) - { - result.Add(new ListItem(this.GetLocalizeName(property.PropertyName, profileResourceFile), property.PropertyName)); - } - - return result; - } - protected override void OnSettingsLoaded() { base.OnSettingsLoaded(); @@ -250,6 +239,17 @@ protected override void OnSavingSettings() base.OnSavingSettings(); } + private ListItemCollection GetPropertiesCollection(string profileResourceFile) + { + var result = new ListItemCollection(); + foreach (var property in this.Model.ProfileProperties) + { + result.Add(new ListItem(this.GetLocalizeName(property.PropertyName, profileResourceFile), property.PropertyName)); + } + + return result; + } + private string GetLocalizeName(string propertyName, string resourceFile) { var name = Localization.GetString("ProfileProperties_" + propertyName, resourceFile); diff --git a/DNN Platform/Modules/MemberDirectory/View.ascx.cs b/DNN Platform/Modules/MemberDirectory/View.ascx.cs index 75045f1ceb7..9bb03aca794 100644 --- a/DNN Platform/Modules/MemberDirectory/View.ascx.cs +++ b/DNN Platform/Modules/MemberDirectory/View.ascx.cs @@ -20,24 +20,19 @@ namespace DotNetNuke.Modules.MemberDirectory public partial class View : ProfileModuleUserControlBase { - protected override void OnInit(EventArgs e) + public override bool DisplayModule { - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); - JavaScript.RequestRegistration(CommonJs.Knockout); - - ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/MemberDirectory/Scripts/MemberDirectory.js"); - this.AddIe7StyleSheet(); - - this.searchBar.Visible = this.DisplaySearch != "None"; - this.advancedSearchBar.Visible = this.DisplaySearch == "Both"; - this.popUpPanel.Visible = this.EnablePopUp; - this.loadMore.Visible = !this.DisablePaging; - - base.OnInit(e); + get + { + return !(this.ProfileUserId == this.ModuleContext.PortalSettings.UserId && this.FilterBy == "User") && this.ModuleContext.PortalSettings.UserId > -1; + } } + public string ProfileResourceFile + { + get { return "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx"; } + } + protected string AlternateItemTemplate { get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "AlternateItemTemplate", Settings.DefaultAlternateItemTemplate); } @@ -52,6 +47,24 @@ protected string DisplaySearch { get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "DisplaySearch", "Both"); } } + + protected override void OnInit(EventArgs e) + { + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); + JavaScript.RequestRegistration(CommonJs.Knockout); + + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/MemberDirectory/Scripts/MemberDirectory.js"); + this.AddIe7StyleSheet(); + + this.searchBar.Visible = this.DisplaySearch != "None"; + this.advancedSearchBar.Visible = this.DisplaySearch == "Both"; + this.popUpPanel.Visible = this.EnablePopUp; + this.loadMore.Visible = !this.DisablePaging; + + base.OnInit(e); + } protected bool EnablePopUp { @@ -95,19 +108,6 @@ protected string PopUpTemplate get { return this.GetSetting(this.ModuleContext.Configuration.TabModuleSettings, "PopUpTemplate", Settings.DefaultPopUpTemplate); } } - public override bool DisplayModule - { - get - { - return !(this.ProfileUserId == this.ModuleContext.PortalSettings.UserId && this.FilterBy == "User") && this.ModuleContext.PortalSettings.UserId > -1; - } - } - - public string ProfileResourceFile - { - get { return "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx"; } - } - protected string ProfileUrlUserToken { get diff --git a/DNN Platform/Modules/RazorHost/AddScript.ascx.cs b/DNN Platform/Modules/RazorHost/AddScript.ascx.cs index e853b7f802f..406babb8f74 100644 --- a/DNN Platform/Modules/RazorHost/AddScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/AddScript.ascx.cs @@ -24,11 +24,6 @@ public AddScript() this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - private void DisplayExtension() - { - this.fileExtension.Text = "." + this.scriptFileType.SelectedValue.ToLowerInvariant(); - } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected override void OnInit(EventArgs e) { @@ -47,6 +42,11 @@ protected override void OnLoad(EventArgs e) this.DisplayExtension(); } + private void DisplayExtension() + { + this.fileExtension.Text = "." + this.scriptFileType.SelectedValue.ToLowerInvariant(); + } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected void cmdCancel_Click(object sender, EventArgs e) { diff --git a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs index 45ec94c7214..bd635fe9a12 100644 --- a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs +++ b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs @@ -53,7 +53,7 @@ protected string RazorScriptFile { string m_RazorScriptFile = Null.NullString; var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; - if (! string.IsNullOrEmpty(scriptFileSetting)) + if (!string.IsNullOrEmpty(scriptFileSetting)) { m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); } @@ -62,6 +62,33 @@ protected string RazorScriptFile } } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdCreate.Click += this.cmdCreate_Click; + this.scriptList.SelectedIndexChanged += this.scriptList_SelectedIndexChanged; + } + + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + if (!this.ModuleContext.PortalSettings.UserInfo.IsSuperUser) + { + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); + } + + if (!this.Page.IsPostBack) + { + this.LoadScripts(); + this.DisplayFile(); + } + } + private void Create() { // Create new Folder @@ -241,7 +268,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) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) { item.Selected = true; } @@ -258,33 +285,6 @@ private void DisplayFile() this.lblModuleControl.Text = string.Format(Localization.GetString("SourceControl", this.LocalResourceFile), this.ModuleControl); } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.cmdCancel.Click += this.cmdCancel_Click; - this.cmdCreate.Click += this.cmdCreate_Click; - this.scriptList.SelectedIndexChanged += this.scriptList_SelectedIndexChanged; - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - if (!this.ModuleContext.PortalSettings.UserInfo.IsSuperUser) - { - this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); - } - - if (!this.Page.IsPostBack) - { - this.LoadScripts(); - this.DisplayFile(); - } - } - private void cmdCancel_Click(object sender, EventArgs e) { try diff --git a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs index 2bfb070de90..7eb84b83271 100644 --- a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs @@ -35,7 +35,7 @@ protected string RazorScriptFile { string m_RazorScriptFile = Null.NullString; var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; - if (! string.IsNullOrEmpty(scriptFileSetting)) + if (!string.IsNullOrEmpty(scriptFileSetting)) { m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); } @@ -44,6 +44,30 @@ protected string RazorScriptFile } } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdSave.Click += this.cmdSave_Click; + this.cmdSaveClose.Click += this.cmdSaveClose_Click; + this.cmdAdd.Click += this.cmdAdd_Click; + this.scriptList.SelectedIndexChanged += this.scriptList_SelectedIndexChanged; + } + + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + if (!this.Page.IsPostBack) + { + this.LoadScripts(); + this.DisplayFile(); + } + } + private void LoadScripts() { string basePath = this.Server.MapPath(this.razorScriptFolder); @@ -53,7 +77,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) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) { item.Selected = true; } @@ -75,7 +99,7 @@ private void DisplayFile() this.txtSource.Text = objStreamReader.ReadToEnd(); objStreamReader.Close(); - if (! string.IsNullOrEmpty(scriptFileSetting)) + if (!string.IsNullOrEmpty(scriptFileSetting)) { this.isCurrentScript.Checked = this.scriptList.SelectedValue.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant(); } @@ -98,30 +122,6 @@ private void SaveScript() } } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.cmdCancel.Click += this.cmdCancel_Click; - this.cmdSave.Click += this.cmdSave_Click; - this.cmdSaveClose.Click += this.cmdSaveClose_Click; - this.cmdAdd.Click += this.cmdAdd_Click; - this.scriptList.SelectedIndexChanged += this.scriptList_SelectedIndexChanged; - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - if (!this.Page.IsPostBack) - { - this.LoadScripts(); - this.DisplayFile(); - } - } - private void cmdCancel_Click(object sender, EventArgs e) { try diff --git a/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs b/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs index e4453ca48e6..3054eeaec5a 100644 --- a/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs +++ b/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs @@ -15,22 +15,6 @@ namespace DotNetNuke.Modules.RazorHost public partial class RazorHost : RazorModuleBase, IActionable { private string razorScriptFileFormatString = "~/DesktopModules/RazorModules/RazorHost/Scripts/{0}"; - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override string RazorScriptFile - { - get - { - string m_RazorScriptFile = base.RazorScriptFile; - var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; - if (! string.IsNullOrEmpty(scriptFileSetting)) - { - m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); - } - - return m_RazorScriptFile; - } - } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public ModuleActionCollection ModuleActions @@ -63,5 +47,21 @@ public ModuleActionCollection ModuleActions return Actions; } } + + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + protected override string RazorScriptFile + { + get + { + string m_RazorScriptFile = base.RazorScriptFile; + var scriptFileSetting = this.ModuleContext.Settings["ScriptFile"] as string; + if (!string.IsNullOrEmpty(scriptFileSetting)) + { + m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); + } + + return m_RazorScriptFile; + } + } } } diff --git a/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs b/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs index 0d00f481e33..80235e66cf9 100644 --- a/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs +++ b/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs @@ -30,14 +30,14 @@ private static void EnsureEditScriptControlIsRegistered(int moduleDefId) return; } - var m = new ModuleControlInfo - { - ControlKey = "EditRazorScript", - ControlSrc = "DesktopModules/RazorModules/RazorHost/EditScript.ascx", - ControlTitle = "Edit Script", - ControlType = SecurityAccessLevel.Host, - ModuleDefID = moduleDefId, - }; + var m = new ModuleControlInfo + { + ControlKey = "EditRazorScript", + ControlSrc = "DesktopModules/RazorModules/RazorHost/EditScript.ascx", + ControlTitle = "Edit Script", + ControlType = SecurityAccessLevel.Host, + ModuleDefID = moduleDefId, + }; ModuleControlController.UpdateModuleControl(m); } } diff --git a/DNN Platform/Modules/RazorHost/Settings.ascx.cs b/DNN Platform/Modules/RazorHost/Settings.ascx.cs index 6a14312b5d1..81bdf8f15d7 100644 --- a/DNN Platform/Modules/RazorHost/Settings.ascx.cs +++ b/DNN Platform/Modules/RazorHost/Settings.ascx.cs @@ -24,7 +24,7 @@ public override void LoadSettings() { 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) && scriptPath.ToLowerInvariant() == scriptFileSetting.ToLowerInvariant()) { item.Selected = true; } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs index a96e389c8fe..4c55495c0eb 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs @@ -14,15 +14,15 @@ namespace DotNetNuke.Authentication.Facebook public partial class Login : OAuthLoginBase { - protected override string AuthSystemApplicationName - { - get { return "Facebook"; } - } - public override bool SupportsRegistration { get { return true; } } + + protected override string AuthSystemApplicationName + { + get { return "Facebook"; } + } protected override UserData GetCurrentUser() { diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs index 269ee736892..4c328f94fb0 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs @@ -13,15 +13,15 @@ namespace DotNetNuke.Authentication.Google public partial class Login : OAuthLoginBase { - protected override string AuthSystemApplicationName - { - get { return "Google"; } - } - public override bool SupportsRegistration { get { return true; } } + + protected override string AuthSystemApplicationName + { + get { return "Google"; } + } protected override UserData GetCurrentUser() { diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs index f4c1e35cb5f..0051d01ef6b 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs @@ -13,15 +13,15 @@ namespace DotNetNuke.Authentication.LiveConnect public partial class Login : OAuthLoginBase { - protected override string AuthSystemApplicationName - { - get { return "Live"; } - } - public override bool SupportsRegistration { get { return true; } } + + protected override string AuthSystemApplicationName + { + get { return "Live"; } + } protected override UserData GetCurrentUser() { diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs index 13bd6a969b7..9b386f7d239 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs @@ -13,15 +13,15 @@ namespace DotNetNuke.Authentication.Twitter public partial class Login : OAuthLoginBase { - protected override string AuthSystemApplicationName - { - get { return "Twitter"; } - } - public override bool SupportsRegistration { get { return true; } } + + protected override string AuthSystemApplicationName + { + get { return "Twitter"; } + } protected override UserData GetCurrentUser() { 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 2aff778fd5f..9e5a2d48509 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs @@ -25,6 +25,73 @@ public class SimpleWebFarmCachingProvider : CachingProvider private readonly int executionTimeout = 5000; // Limit timeout to 5 seconds as cache operations should be quick + 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 + if (CacheExpirationDisable) + { + return; + } + + // Notify other servers + this.NotifyOtherServers("Clear~" + type, data); + } + + public override void Remove(string key) + { + // Remove from local cache + this.RemoveInternal(key); + + // Per API implementation standards only notify others if expiration has not been disabled + if (CacheExpirationDisable) + { + return; + } + + // Notify Other Servers + this.NotifyOtherServers("Remove", key); + } + + /// + /// This method responds to an incoming request to process synchronization from an additional server. + /// + /// + /// This is internal as it should only be called from . + /// + /// The command to process, currently supported Remove and Clear~{Type}. + /// Additional detail to pass to the caching sub-system. + internal void ProcessSynchronizationRequest(string command, string detail) + { + // Handle basic removal + if (command.StartsWith("remove", StringComparison.OrdinalIgnoreCase)) + { + this.RemoveInternal(detail); + return; + } + + // A clear method will have additional type information included, split using the ~ character + if (command.StartsWith("clear~", StringComparison.InvariantCultureIgnoreCase)) + { + var commandParts = command.Split('~'); + this.ClearCacheInternal(commandParts[1], detail, true); + } + } + + private static void HandleNotificationTimeout(object state, bool timedOut) + { + if (!timedOut) + { + return; + } + + // Abort if possible + var request = (HttpWebRequest)state; + request?.Abort(); + } + private void NotifyOtherServers(string command, string detail) { // Do not send notifications to other servers if currently upgrading @@ -82,7 +149,7 @@ private void OnServerNotificationCompleteCallback(IAsyncResult asynchronousResul try { // Get the response - using (var response = (HttpWebResponse) request.EndGetResponse(asynchronousResult)) + using (var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult)) { // If status code is ok do nothing if (response.StatusCode == HttpStatusCode.OK) @@ -103,72 +170,5 @@ private void OnServerNotificationCompleteCallback(IAsyncResult asynchronousResul } } } - - private static void HandleNotificationTimeout(object state, bool timedOut) - { - if (!timedOut) - { - return; - } - - // Abort if possible - var request = (HttpWebRequest)state; - request?.Abort(); - } - - /// - /// This method responds to an incoming request to process synchronization from an additional server. - /// - /// - /// This is internal as it should only be called from . - /// - /// The command to process, currently supported Remove and Clear~{Type}. - /// Additional detail to pass to the caching sub-system. - internal void ProcessSynchronizationRequest(string command, string detail) - { - // Handle basic removal - if (command.StartsWith("remove", StringComparison.OrdinalIgnoreCase)) - { - this.RemoveInternal(detail); - return; - } - - // A clear method will have additional type information included, split using the ~ character - if (command.StartsWith("clear~", StringComparison.InvariantCultureIgnoreCase)) - { - var commandParts = command.Split('~'); - this.ClearCacheInternal(commandParts[1], detail, true); - } - } - - 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 - if (CacheExpirationDisable) - { - return; - } - - // Notify other servers - this.NotifyOtherServers("Clear~" + type, data); - } - - public override void Remove(string key) - { - // Remove from local cache - this.RemoveInternal(key); - - // Per API implementation standards only notify others if expiration has not been disabled - if (CacheExpirationDisable) - { - return; - } - - // Notify Other Servers - this.NotifyOtherServers("Remove", key); - } } } diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs index 363c15bdfbd..9cc193912cb 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs @@ -16,6 +16,11 @@ namespace DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider /// public class SimpleWebFarmSynchronizationHandler : IHttpHandler { + /// + /// Gets a value indicating whether indicates that this handler can be reused for multiple requests. + /// + public bool IsReusable => true; + public void ProcessRequest(HttpContext context) { // Validate the request for required inputs, return if no action possible @@ -48,10 +53,5 @@ public void ProcessRequest(HttpContext context) var provider = (Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider)CachingProvider.Instance(); provider.ProcessSynchronizationRequest(command, detail); } - - /// - /// Gets a value indicating whether indicates that this handler can be reused for multiple requests. - /// - public bool IsReusable => true; } } diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs index 595f272587f..404883c9bde 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs @@ -20,21 +20,20 @@ namespace DotNetNuke.Providers.AspNetClientCapabilityProvider ///
public class AspNetClientCapability : Services.ClientCapability.ClientCapability { + // set all agent identifiers are in lowercase for faster comparison + private const string WindowsPcAgent = "windows nt"; + private const string WindowsPhoneAgent = "windows phone"; + private const string AndroidAgent = "android"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AspNetClientCapability)); - private readonly IDictionary _properties; - - public override string this[string name] - { - get - { - if (this._properties != null && this._properties.ContainsKey(name)) - { - return this._properties[name]; - } + private static readonly Regex MobileCheck = + new Regex( + @"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", + RegexOptions.Compiled, TimeSpan.FromSeconds(2)); - return (this.Capabilities != null && this.Capabilities.ContainsKey(name)) ? this.Capabilities[name] : string.Empty; - } - } + private static readonly Regex TabletRegex = new Regex("ipad|xoom|sch-i800|playbook|tablet|kindle|nexus", RegexOptions.Compiled, TimeSpan.FromSeconds(2)); + + private readonly IDictionary _properties; /// /// Initializes a new instance of the class. @@ -125,6 +124,19 @@ public AspNetClientCapability(IDictionary properties) } } } + + public override string this[string name] + { + get + { + if (this._properties != null && this._properties.ContainsKey(name)) + { + return this._properties[name]; + } + + return (this.Capabilities != null && this.Capabilities.ContainsKey(name)) ? this.Capabilities[name] : string.Empty; + } + } /// /// Returns a dictionary of capability names and values as strings based on the object @@ -188,13 +200,6 @@ private static string GetStringValue(IDictionary properties, str return properties.ContainsKey(property) ? properties[property] : null; } - private static readonly Regex MobileCheck = - new Regex( - @"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", - RegexOptions.Compiled, TimeSpan.FromSeconds(2)); - - private static readonly Regex TabletRegex = new Regex("ipad|xoom|sch-i800|playbook|tablet|kindle|nexus", RegexOptions.Compiled, TimeSpan.FromSeconds(2)); - private static bool GetIfMobile(string userAgent) { return MobileCheck.IsMatch(userAgent); @@ -308,11 +313,6 @@ private static string MapAgentVersionToWinVersion(string version) return "NT " + version; } } - - // set all agent identifiers are in lowercase for faster comparison - private const string WindowsPcAgent = "windows nt"; - private const string WindowsPhoneAgent = "windows phone"; - private const string AndroidAgent = "android"; private const string IphoneAgent = "iphone"; private const string IpadAgent = "ipad"; private const string MacOsxAgent = "mac os x"; diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.cs index 6cf44ed4fee..101bc9a7f26 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapabilityProvider.cs @@ -26,6 +26,16 @@ public class AspNetClientCapabilityProvider : ClientCapabilityProvider private static Dictionary> _allClientCapabilityValues; private static IDictionary _highPiorityCapabilityValues; + + private static IDictionary _dummyProperies; + + /// + /// Gets a value indicating whether indicates whether tablet detection is supported in the available data set. + /// + public override bool SupportsTabletDetection + { + get { return false; } + } private static IQueryable AllCapabilities { @@ -104,8 +114,6 @@ private static IDictionary HighPiorityCapabilityValues }); } } - - private static IDictionary _dummyProperies; private static IDictionary DummyProperties { @@ -125,6 +133,18 @@ private static IDictionary DummyProperties }); } } + + public static HttpBrowserCapabilities GetHttpBrowserCapabilities(NameValueCollection headers, string userAgent) + { + var factory = new BrowserCapabilitiesFactory(); + var browserCaps = new HttpBrowserCapabilities(); + var hashtable = new Hashtable(180, StringComparer.OrdinalIgnoreCase); + hashtable[string.Empty] = userAgent; + browserCaps.Capabilities = hashtable; + factory.ConfigureBrowserCapabilities(headers, browserCaps); + factory.ConfigureCustomCapabilities(headers, browserCaps); + return browserCaps; + } /// /// Returns ClientCapability based on the user agent provided. @@ -173,25 +193,5 @@ public override IQueryable GetAllClientCapabilities() { return AllCapabilities; } - - /// - /// Gets a value indicating whether indicates whether tablet detection is supported in the available data set. - /// - public override bool SupportsTabletDetection - { - get { return false; } - } - - public static HttpBrowserCapabilities GetHttpBrowserCapabilities(NameValueCollection headers, string userAgent) - { - var factory = new BrowserCapabilitiesFactory(); - var browserCaps = new HttpBrowserCapabilities(); - var hashtable = new Hashtable(180, StringComparer.OrdinalIgnoreCase); - hashtable[string.Empty] = userAgent; - browserCaps.Capabilities = hashtable; - factory.ConfigureBrowserCapabilities(headers, browserCaps); - factory.ConfigureCustomCapabilities(headers, browserCaps); - return browserCaps; - } } } diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs index 1182fe64db4..3b2666fe18c 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs @@ -56,6 +56,32 @@ public string UpgradeModule(string version) return Localization.GetString("SuccessMessage", ResourceFileRelativePath); } + private static IDictionary CreateMappedCapabilities() + { + var mappingCapabilites = new Dictionary + { + { "is_wireless_device", "IsMobile" }, + { "resolution_width", "ScreenPixelsWidth" }, + { "resolution_height", "ScreenPixelsHeight" }, + }; + + if (DotNetNukeContext.Current.Application.Name != "DNNCORP.CE") + { + mappingCapabilites.Add("is_tablet", "IsTablet"); + mappingCapabilites.Add("device_os", "PlatformName"); + mappingCapabilites.Add("mobile_browser", "BrowserName"); + mappingCapabilites.Add("mobile_browser_version", "BrowserVersion"); + mappingCapabilites.Add("device_os_version", "PlatformVersion"); + mappingCapabilites.Add("brand_name", "HardwareVendor"); + mappingCapabilites.Add("cookie_support", "CookiesCapable"); + mappingCapabilites.Add("model_name", "HardwareModel"); + mappingCapabilites.Add("physical_screen_height", "ScreenMMHeight"); + mappingCapabilites.Add("physical_screen_width", "ScreenMMWidth"); + } + + return mappingCapabilites; + } + private void RemoveWurflProvider() { var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.WURFLClientCapabilityProvider"); @@ -127,31 +153,5 @@ private void UpdateRules() controller.Save(redirection); } } - - private static IDictionary CreateMappedCapabilities() - { - var mappingCapabilites = new Dictionary - { - { "is_wireless_device", "IsMobile" }, - { "resolution_width", "ScreenPixelsWidth" }, - { "resolution_height", "ScreenPixelsHeight" }, - }; - - if (DotNetNukeContext.Current.Application.Name != "DNNCORP.CE") - { - mappingCapabilites.Add("is_tablet", "IsTablet"); - mappingCapabilites.Add("device_os", "PlatformName"); - mappingCapabilites.Add("mobile_browser", "BrowserName"); - mappingCapabilites.Add("mobile_browser_version", "BrowserVersion"); - mappingCapabilites.Add("device_os_version", "PlatformVersion"); - mappingCapabilites.Add("brand_name", "HardwareVendor"); - mappingCapabilites.Add("cookie_support", "CookiesCapable"); - mappingCapabilites.Add("model_name", "HardwareModel"); - mappingCapabilites.Add("physical_screen_height", "ScreenMMHeight"); - mappingCapabilites.Add("physical_screen_width", "ScreenMMWidth"); - } - - return mappingCapabilites; - } } } diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs index 7c12cbc0e01..93d42b82374 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs @@ -51,33 +51,94 @@ protected override string ListObjectsCacheKey get { return "Azure_ListObjects_{0}"; } } - private static void CheckSettings(FolderMappingInfo folderMapping) + /// + /// Azure Storage doesn't support folders, so we create a file in order for the folder to not be deleted during future synchronizations. + /// The file has an extension not allowed by host. This way the file won't be added during synchronizations. + /// + public override void AddFolder(string folderPath, FolderMappingInfo folderMapping, string mappedPath) { - var settings = folderMapping.FolderMappingSettings; + Requires.NotNull("folderPath", folderPath); + Requires.NotNull("folderMapping", folderMapping); - if (string.IsNullOrEmpty((string)settings[Constants.AccountName]) || - string.IsNullOrEmpty((string)settings[Constants.AccountKey]) || - string.IsNullOrEmpty((string)settings[Constants.Container]) || - string.IsNullOrEmpty((string)settings[Constants.UseHttps])) - { - throw new Exception("Settings cannot be found."); - } + this.UpdateFileInternal(new MemoryStream(), folderMapping, mappedPath + Constants.PlaceHolderFileName); } - private CloudBlobContainer GetContainer(FolderMappingInfo folderMapping) + /// + /// Gets the direct Url to the file. + /// + /// + public override string GetFileUrl(IFileInfo file) { - CheckSettings(folderMapping); + Requires.NotNull("file", file); - var accountName = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountName); - var accountKey = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountKey); - var container = GetSetting(folderMapping, Constants.Container); - var useHttps = GetBooleanSetting(folderMapping, Constants.UseHttps); + var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); + var directLink = string.IsNullOrEmpty(GetSetting(folderMapping, Constants.DirectLink)) || GetSetting(folderMapping, Constants.DirectLink).ToLowerInvariant() == "true"; - var sc = new StorageCredentials(accountName, accountKey); - var csa = new CloudStorageAccount(sc, useHttps); - var blobClient = csa.CreateCloudBlobClient(); - return blobClient.GetContainerReference(container); - } + if (directLink) + { + var folder = FolderManager.Instance.GetFolder(file.FolderId); + var uri = folder.MappedPath + file.FileName; + + var container = this.GetContainer(folderMapping); + var blob = container.GetBlobReference(uri); + var absuri = blob.Uri.AbsoluteUri; + var customDomain = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.CustomDomain); + + if (!string.IsNullOrEmpty(customDomain)) + { + var customUri = new UriBuilder(customDomain).Uri; + absuri = + new UriBuilder(blob.Uri.AbsoluteUri) { Host = customUri.Host, Scheme = customUri.Scheme, Port = customUri.Port } + .Uri.AbsoluteUri; + } + + const string groupPolicyIdentifier = "DNNFileManagerPolicy"; + + var permissions = container.GetPermissions(); + + SharedAccessBlobPolicy policy; + + permissions.SharedAccessPolicies.TryGetValue(groupPolicyIdentifier, out policy); + + if (policy == null) + { + policy = new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTime.UtcNow.AddYears(100) }; + + permissions.SharedAccessPolicies.Add(groupPolicyIdentifier, policy); + } + else + { + policy.Permissions = SharedAccessBlobPermissions.Read; + policy.SharedAccessExpiryTime = DateTime.UtcNow.AddYears(100); + } + + /* + * Workaround for CONTENT-3662 + * The Azure Client Storage api has issue when used with Italian Thread.Culture or eventually other cultures + * (see this article for further information https://connect.microsoft.com/VisualStudio/feedback/details/760974/windows-azure-sdk-cloudblobcontainer-setpermissions-permissions-as-microsoft-windowsazure-storageclient-blobcontainerpermissions-error). + * This code changes the thread culture to en-US + */ + var currentCulture = Thread.CurrentThread.CurrentCulture; + if (currentCulture.Name != "en-US") + { + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); + } + + container.SetPermissions(permissions); + + var signature = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy(), groupPolicyIdentifier); + + // Reset original Thread Culture + if (currentCulture.Name != "en-US") + { + Thread.CurrentThread.CurrentCulture = currentCulture; + } + + return absuri + signature; + } + + return FileLinkClickController.Instance.GetFileLinkClick(file); + } protected override void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri) { @@ -100,6 +161,34 @@ protected override void DeleteFileInternal(FolderMappingInfo folderMapping, stri this.ClearCache(folderMapping.FolderMappingID); } + + private static void CheckSettings(FolderMappingInfo folderMapping) + { + var settings = folderMapping.FolderMappingSettings; + + if (string.IsNullOrEmpty((string)settings[Constants.AccountName]) || + string.IsNullOrEmpty((string)settings[Constants.AccountKey]) || + string.IsNullOrEmpty((string)settings[Constants.Container]) || + string.IsNullOrEmpty((string)settings[Constants.UseHttps])) + { + throw new Exception("Settings cannot be found."); + } + } + + private CloudBlobContainer GetContainer(FolderMappingInfo folderMapping) + { + CheckSettings(folderMapping); + + var accountName = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountName); + var accountKey = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountKey); + var container = GetSetting(folderMapping, Constants.Container); + var useHttps = GetBooleanSetting(folderMapping, Constants.UseHttps); + + var sc = new StorageCredentials(accountName, accountKey); + var csa = new CloudStorageAccount(sc, useHttps); + var blobClient = csa.CreateCloudBlobClient(); + return blobClient.GetContainerReference(container); + } protected override void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder) { @@ -200,95 +289,6 @@ protected override void UpdateFileInternal(Stream stream, FolderMappingInfo fold this.ClearCache(folderMapping.FolderMappingID); } - - /// - /// Azure Storage doesn't support folders, so we create a file in order for the folder to not be deleted during future synchronizations. - /// The file has an extension not allowed by host. This way the file won't be added during synchronizations. - /// - public override void AddFolder(string folderPath, FolderMappingInfo folderMapping, string mappedPath) - { - Requires.NotNull("folderPath", folderPath); - Requires.NotNull("folderMapping", folderMapping); - - this.UpdateFileInternal(new MemoryStream(), folderMapping, mappedPath + Constants.PlaceHolderFileName); - } - - /// - /// Gets the direct Url to the file. - /// - /// - public override string GetFileUrl(IFileInfo file) - { - Requires.NotNull("file", file); - - var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - var directLink = string.IsNullOrEmpty(GetSetting(folderMapping, Constants.DirectLink)) || GetSetting(folderMapping, Constants.DirectLink).ToLowerInvariant() == "true"; - - if (directLink) - { - var folder = FolderManager.Instance.GetFolder(file.FolderId); - var uri = folder.MappedPath + file.FileName; - - var container = this.GetContainer(folderMapping); - var blob = container.GetBlobReference(uri); - var absuri = blob.Uri.AbsoluteUri; - var customDomain = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.CustomDomain); - - if (!string.IsNullOrEmpty(customDomain)) - { - var customUri = new UriBuilder(customDomain).Uri; - absuri = - new UriBuilder(blob.Uri.AbsoluteUri) { Host = customUri.Host, Scheme = customUri.Scheme, Port = customUri.Port } - .Uri.AbsoluteUri; - } - - const string groupPolicyIdentifier = "DNNFileManagerPolicy"; - - var permissions = container.GetPermissions(); - - SharedAccessBlobPolicy policy; - - permissions.SharedAccessPolicies.TryGetValue(groupPolicyIdentifier, out policy); - - if (policy == null) - { - policy = new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTime.UtcNow.AddYears(100) }; - - permissions.SharedAccessPolicies.Add(groupPolicyIdentifier, policy); - } - else - { - policy.Permissions = SharedAccessBlobPermissions.Read; - policy.SharedAccessExpiryTime = DateTime.UtcNow.AddYears(100); - } - - /* - * Workaround for CONTENT-3662 - * The Azure Client Storage api has issue when used with Italian Thread.Culture or eventually other cultures - * (see this article for further information https://connect.microsoft.com/VisualStudio/feedback/details/760974/windows-azure-sdk-cloudblobcontainer-setpermissions-permissions-as-microsoft-windowsazure-storageclient-blobcontainerpermissions-error). - * This code changes the thread culture to en-US - */ - var currentCulture = Thread.CurrentThread.CurrentCulture; - if (currentCulture.Name != "en-US") - { - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); - } - - container.SetPermissions(permissions); - - var signature = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy(), groupPolicyIdentifier); - - // Reset original Thread Culture - if (currentCulture.Name != "en-US") - { - Thread.CurrentThread.CurrentCulture = currentCulture; - } - - return absuri + signature; - } - - return FileLinkClickController.Instance.GetFileLinkClick(file); - } /// /// Gets the URL of the image to display in FileManager tree. diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs index 02d157b86bd..75f28e002a9 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs @@ -123,6 +123,45 @@ public override void UpdateSettings(int folderMappingID) folderMappingController.UpdateFolderMapping(folderMapping); } + /// + /// + protected void ddlContainers_SelectedIndexChanged(object sender, EventArgs e) + { + if (this.ddlContainers.SelectedIndex != 1) + { + return; + } + + if (this.tbAccountName.Text.Trim().Length > 0 && this.tbAccountKey.Text.Trim().Length > 0) + { + this.ddlContainers.Items.Clear(); + + this.ddlContainers.Items.Add(Localization.GetString("SelectContainer", this.LocalResourceFile)); + this.ddlContainers.Items.Add(Localization.GetString("RefreshContainerList", this.LocalResourceFile)); + + this.LoadContainers(); + + if (this.ddlContainers.Items.Count == 3) + { + // If there is only one container, then select it + this.ddlContainers.SelectedValue = this.ddlContainers.Items[2].Value; + } + } + else + { + this.valContainerName.ErrorMessage = Localization.GetString("CredentialsRequired.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; + } + } + + /// + /// + protected void btnNewContainer_Click(object sender, EventArgs e) + { + this.SelectContainerPanel.Visible = false; + this.CreateContainerPanel.Visible = true; + } + private static bool AreThereFolderMappingsWithSameSettings(FolderMappingInfo folderMapping, string accountName, string container) { var folderMappingController = FolderMappingController.Instance; @@ -322,45 +361,6 @@ private void LoadContainers() this.valContainerName.IsValid = false; } } - - /// - /// - protected void ddlContainers_SelectedIndexChanged(object sender, EventArgs e) - { - if (this.ddlContainers.SelectedIndex != 1) - { - return; - } - - if (this.tbAccountName.Text.Trim().Length > 0 && this.tbAccountKey.Text.Trim().Length > 0) - { - this.ddlContainers.Items.Clear(); - - this.ddlContainers.Items.Add(Localization.GetString("SelectContainer", this.LocalResourceFile)); - this.ddlContainers.Items.Add(Localization.GetString("RefreshContainerList", this.LocalResourceFile)); - - this.LoadContainers(); - - if (this.ddlContainers.Items.Count == 3) - { - // If there is only one container, then select it - this.ddlContainers.SelectedValue = this.ddlContainers.Items[2].Value; - } - } - else - { - this.valContainerName.ErrorMessage = Localization.GetString("CredentialsRequired.ErrorMessage", this.LocalResourceFile); - this.valContainerName.IsValid = false; - } - } - - /// - /// - protected void btnNewContainer_Click(object sender, EventArgs e) - { - this.SelectContainerPanel.Visible = false; - this.CreateContainerPanel.Visible = true; - } /// /// diff --git a/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs b/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs index 5b1f9111524..947288712f6 100644 --- a/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs +++ b/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs @@ -23,6 +23,31 @@ public abstract class BaseRemoteStorageProvider : FolderProvider private readonly string _encryptionKey = Host.GUID; private readonly PortalSecurity _portalSecurity = PortalSecurity.Instance; + public override bool SupportsMappedPaths + { + get { return true; } + } + + public override bool SupportsMoveFile + { + get { return false; } + } + + protected virtual string FileNotFoundMessage + { + get { return string.Empty; } + } + + protected virtual string ObjectCacheKey + { + get { return string.Empty; } + } + + protected virtual int ObjectCacheTimeout + { + get { return 150; } + } + private IRemoteStorageItem GetStorageItemInternal(FolderMappingInfo folderMapping, string key) { var cacheKey = string.Format(this.ObjectCacheKey, folderMapping.FolderMappingID, key); @@ -41,21 +66,6 @@ private IRemoteStorageItem GetStorageItemInternal(FolderMappingInfo folderMappin return list.FirstOrDefault(i => i.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); }); } - - protected virtual string FileNotFoundMessage - { - get { return string.Empty; } - } - - protected virtual string ObjectCacheKey - { - get { return string.Empty; } - } - - protected virtual int ObjectCacheTimeout - { - get { return 150; } - } protected virtual string ListObjectsCacheKey { @@ -66,27 +76,31 @@ protected virtual int ListObjectsCacheTimeout { get { return 300; } } - - public override bool SupportsMappedPaths - { - get { return true; } - } - - public override bool SupportsMoveFile - { - get { return false; } - } public override bool SupportsMoveFolder { get { return true; } } - protected abstract void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); + /// + /// Adds a new folder. + /// + public override void AddFolder(string folderPath, FolderMappingInfo folderMapping) + { + this.AddFolder(folderPath, folderMapping, folderPath); + } - protected abstract void DeleteFileInternal(FolderMappingInfo folderMapping, string uri); + /// + /// Adds a new file to the specified folder. + /// + public override void AddFile(IFolderInfo folder, string fileName, Stream content) + { + Requires.NotNull("folder", folder); + Requires.NotNullOrEmpty("fileName", fileName); + Requires.NotNull("content", content); - protected abstract void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder); + this.UpdateFile(folder, fileName, content); + } protected static bool GetBooleanSetting(FolderMappingInfo folderMapping, string settingName) { @@ -103,15 +117,12 @@ protected static int GetIntegerSetting(FolderMappingInfo folderMapping, string s return defaultValue; } + + protected abstract void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); - protected abstract Stream GetFileStreamInternal(FolderMappingInfo folderMapping, string uri); - - protected abstract IList GetObjectList(FolderMappingInfo folderMapping); + protected abstract void DeleteFileInternal(FolderMappingInfo folderMapping, string uri); - protected virtual IList GetObjectList(FolderMappingInfo folderMapping, string path) - { - return this.GetObjectList(folderMapping); - } + protected abstract void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder); protected static string GetSetting(FolderMappingInfo folderMapping, string settingName) { @@ -121,6 +132,15 @@ protected static string GetSetting(FolderMappingInfo folderMapping, string setti return folderMapping.FolderMappingSettings[settingName]?.ToString(); } + protected abstract Stream GetFileStreamInternal(FolderMappingInfo folderMapping, string uri); + + protected abstract IList GetObjectList(FolderMappingInfo folderMapping); + + protected virtual IList GetObjectList(FolderMappingInfo folderMapping, string path) + { + return this.GetObjectList(folderMapping); + } + protected abstract void MoveFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); protected abstract void MoveFolderInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); @@ -131,26 +151,6 @@ protected virtual IRemoteStorageItem GetStorageItem(FolderMappingInfo folderMapp { return this.GetStorageItemInternal(folderMapping, key); } - - /// - /// Adds a new folder. - /// - public override void AddFolder(string folderPath, FolderMappingInfo folderMapping) - { - this.AddFolder(folderPath, folderMapping, folderPath); - } - - /// - /// Adds a new file to the specified folder. - /// - public override void AddFile(IFolderInfo folder, string fileName, Stream content) - { - Requires.NotNull("folder", folder); - Requires.NotNullOrEmpty("fileName", fileName); - Requires.NotNull("content", content); - - this.UpdateFile(folder, fileName, content); - } public virtual void ClearCache(int folderMappingId) { @@ -267,8 +267,8 @@ public override string[] GetFiles(IFolderInfo folder) // select Path.GetFileName(f)).ToArray(); var pattern = "^" + mappedPath; return (from i in list - let f = i.Key - let r = !string.IsNullOrEmpty(mappedPath) ? Regex.Replace(f, pattern, string.Empty, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) : f + let f = i.Key + let r = !string.IsNullOrEmpty(mappedPath) ? Regex.Replace(f, pattern, string.Empty, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) : f where f.StartsWith(mappedPath, true, CultureInfo.InvariantCulture) && f.Length > mappedPath.Length && r.IndexOf("/", StringComparison.Ordinal) == -1 select Path.GetFileName(f)).ToArray(); } @@ -355,16 +355,16 @@ public override IEnumerable GetSubFolders(string folderPath, FolderMappi var pattern = "^" + Regex.Escape(folderPath); - return (from o in list - let f = o.Key - let r = - !string.IsNullOrEmpty(folderPath) - ? Regex.Replace(f, pattern, string.Empty, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) - : f - where f.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase) - && f.Length > folderPath.Length - && r.IndexOf("/", StringComparison.Ordinal) > -1 - select folderPath + r.Substring(0, r.IndexOf("/", StringComparison.Ordinal)) + "/").Distinct().ToList(); + return (from o in list + let f = o.Key + let r = + !string.IsNullOrEmpty(folderPath) + ? Regex.Replace(f, pattern, string.Empty, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2)) + : f + where f.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase) + && f.Length > folderPath.Length + && r.IndexOf("/", StringComparison.Ordinal) > -1 + select folderPath + r.Substring(0, r.IndexOf("/", StringComparison.Ordinal)) + "/").Distinct().ToList(); // var mylist = (from o in list // let f = o.Key diff --git a/DNN Platform/Syndication/OPML/Opml.cs b/DNN Platform/Syndication/OPML/Opml.cs index e599bfb3d6b..29c379918bd 100644 --- a/DNN Platform/Syndication/OPML/Opml.cs +++ b/DNN Platform/Syndication/OPML/Opml.cs @@ -231,6 +231,26 @@ public OpmlOutlines Outlines } } + public static Opml LoadFromUrl(Uri uri) + { + return OpmlDownloadManager.GetOpmlFeed(uri); + } + + public static Opml LoadFromFile(string path) + { + try + { + var opmlDoc = new XmlDocument { XmlResolver = null }; + opmlDoc.Load(path); + + return LoadFromXml(opmlDoc); + } + catch + { + return new Opml(); + } + } + public void AddOutline(OpmlOutline item) { this._outlines.Add(item); @@ -345,26 +365,6 @@ public void Save(string fileName) this.opmlDoc.Save(fileName); } - public static Opml LoadFromUrl(Uri uri) - { - return OpmlDownloadManager.GetOpmlFeed(uri); - } - - public static Opml LoadFromFile(string path) - { - try - { - var opmlDoc = new XmlDocument { XmlResolver = null }; - opmlDoc.Load(path); - - return LoadFromXml(opmlDoc); - } - catch - { - return new Opml(); - } - } - public static Opml LoadFromXml(XmlDocument doc) { var _out = new Opml(); diff --git a/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs b/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs index 71a9e8e98a7..4c0ed9fb59c 100644 --- a/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs +++ b/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs @@ -17,8 +17,8 @@ namespace DotNetNuke.Services.Syndication /// internal class OpmlDownloadManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OpmlDownloadManager)); private const string OPML_Dir = "/OPML/"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OpmlDownloadManager)); private static readonly OpmlDownloadManager _theManager = new OpmlDownloadManager(); private readonly Dictionary _cache; @@ -69,6 +69,41 @@ internal Opml GetFeed(Uri uri) return opmlFeed; } + + private static string PrepareTempDir() + { + string tempDir = null; + + try + { + string d = HttpContext.Current.Server.MapPath(Settings.CacheRoot + OPML_Dir); + + if (!Directory.Exists(d)) + { + Directory.CreateDirectory(d); + } + + tempDir = d; + } + catch + { + // don't cache on disk if can't do it + } + + return tempDir; + } + + private static string GetTempFileNamePrefixFromUrl(Uri uri) + { + try + { + return string.Format("{0}_{1:x8}", uri.Host.Replace('.', '_'), uri.AbsolutePath.GetHashCode()); + } + catch + { + return "opml"; + } + } private Opml DownloadOpmlFeed(Uri uri) { @@ -200,40 +235,5 @@ private void TrySaveToDisk(XmlDocument doc, Uri uri, DateTime utcExpiry) // can't save to disk - not a problem } } - - private static string PrepareTempDir() - { - string tempDir = null; - - try - { - string d = HttpContext.Current.Server.MapPath(Settings.CacheRoot + OPML_Dir); - - if (!Directory.Exists(d)) - { - Directory.CreateDirectory(d); - } - - tempDir = d; - } - catch - { - // don't cache on disk if can't do it - } - - return tempDir; - } - - private static string GetTempFileNamePrefixFromUrl(Uri uri) - { - try - { - return string.Format("{0}_{1:x8}", uri.Host.Replace('.', '_'), uri.AbsolutePath.GetHashCode()); - } - catch - { - return "opml"; - } - } } } diff --git a/DNN Platform/Syndication/RSS/GenericRssChannel.cs b/DNN Platform/Syndication/RSS/GenericRssChannel.cs index 2f5cd29d678..099ff853d9a 100644 --- a/DNN Platform/Syndication/RSS/GenericRssChannel.cs +++ b/DNN Platform/Syndication/RSS/GenericRssChannel.cs @@ -20,6 +20,14 @@ public sealed class GenericRssChannel : RssChannelBase internal class RssDownloadManager { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RssDownloadManager)); private const string RSS_Dir = "/RSS/"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RssDownloadManager)); private static readonly RssDownloadManager _theManager = new RssDownloadManager(); private readonly Dictionary _cache; @@ -36,6 +36,28 @@ private RssDownloadManager() this._directoryOnDisk = PrepareTempDir(); } + public static RssChannelDom GetChannel(string url) + { + return _theManager.GetChannelDom(url); + } + + private static int GetTtlFromString(string ttlString, int defaultTtlMinutes) + { + if (!string.IsNullOrEmpty(ttlString)) + { + int ttlMinutes; + if (int.TryParse(ttlString, out ttlMinutes)) + { + if (ttlMinutes >= 0) + { + return ttlMinutes; + } + } + } + + return defaultTtlMinutes; + } + private RssChannelDom DownloadChannelDom(string url) { // look for disk cache first @@ -197,28 +219,6 @@ private RssChannelDom GetChannelDom(string url) return dom; } - public static RssChannelDom GetChannel(string url) - { - return _theManager.GetChannelDom(url); - } - - private static int GetTtlFromString(string ttlString, int defaultTtlMinutes) - { - if (!string.IsNullOrEmpty(ttlString)) - { - int ttlMinutes; - if (int.TryParse(ttlString, out ttlMinutes)) - { - if (ttlMinutes >= 0) - { - return ttlMinutes; - } - } - } - - return defaultTtlMinutes; - } - private static string PrepareTempDir() { string tempDir = null; diff --git a/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs b/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs index 64bd93b256c..4921676a41e 100644 --- a/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs +++ b/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs @@ -24,6 +24,18 @@ public abstract class RssHttpHandlerBase /// Triggers the Init event. /// @@ -95,6 +95,16 @@ protected virtual void OnPreRender(EventArgs ea) } } + protected virtual void PopulateChannel(string channelName, string userName) + { + } + + protected virtual void Render(XmlTextWriter writer) + { + XmlDocument doc = this._channel.SaveAsXml(); + doc.Save(writer); + } + private void InternalInit(HttpContext context) { this._context = context; @@ -105,15 +115,5 @@ private void InternalInit(HttpContext context) this.Context.Response.ContentType = "text/xml"; } - - protected virtual void PopulateChannel(string channelName, string userName) - { - } - - protected virtual void Render(XmlTextWriter writer) - { - XmlDocument doc = this._channel.SaveAsXml(); - doc.Save(writer); - } } } diff --git a/DNN Platform/Tests/App.config b/DNN Platform/Tests/App.config index 345b03ceaa4..9125c5046a1 100644 --- a/DNN Platform/Tests/App.config +++ b/DNN Platform/Tests/App.config @@ -1,400 +1,400 @@ - - - - -
- - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + +
+ + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs index 613b4b54bc8..be6f21acf2f 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs @@ -35,23 +35,6 @@ public static int CreateRoleIfNotPresent(string roleName, int portalId = 0) return -1; } - private static int CreateRole(string roleName, string roleDescription, int portalId = 0) - { - var fileContent = SqlScripts.SingleRoleCreation; - var masterScript = new StringBuilder(fileContent) - .Replace(PortalIdMarker, portalId.ToString(CultureInfo.InvariantCulture)) - .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) - .ToString(); - - var script = new StringBuilder(masterScript) - .Replace(RoleNameMarker, roleName.Replace("'", "''")) - .Replace(RoleDescriptionMarker, roleDescription.Replace("'", "''")); - - DatabaseHelper.ExecuteQuery(script.ToString()); - WebApiTestHelper.ClearHostCache(); - return GetRoleId(roleName); - } - /// /// Get RoleId for role "Registered Users". /// @@ -70,6 +53,23 @@ public static int GetAdministratorsRoleId(int portalId = 0) return GetRoleId("Administrators", portalId); } + private static int CreateRole(string roleName, string roleDescription, int portalId = 0) + { + var fileContent = SqlScripts.SingleRoleCreation; + var masterScript = new StringBuilder(fileContent) + .Replace(PortalIdMarker, portalId.ToString(CultureInfo.InvariantCulture)) + .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) + .ToString(); + + var script = new StringBuilder(masterScript) + .Replace(RoleNameMarker, roleName.Replace("'", "''")) + .Replace(RoleDescriptionMarker, roleDescription.Replace("'", "''")); + + DatabaseHelper.ExecuteQuery(script.ToString()); + WebApiTestHelper.ClearHostCache(); + return GetRoleId(roleName); + } + public static int GetRoleId(string roleName, int portalId = 0) { // The fix for DNN-4288 prevented virtual roles from getting virtual diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs index 41ec2ec1a6d..924e6b22651 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs @@ -253,16 +253,6 @@ ORDER BY ScheduleHistoryId DESC public class ScheduleHistoryInfo { - public int ScheduleId { get; } - - public int ScheduleHistoryId { get; } - - public DateTime EndDate { get; } - - public bool Succeeded { get; } - - public string LogNotes { get; } - public ScheduleHistoryInfo(IDictionary queryResult) { try @@ -299,5 +289,15 @@ internal ScheduleHistoryInfo(ScheduleHistoryInfo lastRunInfo) this.Succeeded = false; this.LogNotes = lastRunInfo.LogNotes; } + + public int ScheduleId { get; } + + public int ScheduleHistoryId { get; } + + public DateTime EndDate { get; } + + public bool Succeeded { get; } + + public string LogNotes { get; } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs index f2fcd3f544a..c795c1472a0 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs @@ -11,6 +11,8 @@ namespace DNN.Integration.Test.Framework.Controllers public static class TabController { + private static int PortalId => DnnDataHelper.PortalId; + public static int GetTabIdByTabName(string tabName) { var query = string.Format( @@ -179,7 +181,5 @@ public static void DeleteTabSetting(int tabId, string settingName) { DatabaseHelper.ExecuteStoredProcedure("DeleteTabSetting", tabId, settingName); } - - private static int PortalId => DnnDataHelper.PortalId; } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs index 4036522f616..73f972aa41e 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs @@ -14,10 +14,10 @@ namespace DNN.Integration.Test.Framework.Controllers public static class UserController { - private static readonly string UserToCopy = AppConfigHelper.HostUserName; - private const string PortalIdMarker = @"'$[portal_id]'"; private const string UserToCopyMarker = @"$[users_to_copy]"; + + private static readonly string UserToCopy = AppConfigHelper.HostUserName; private const string FirstNameMarker = @"$[first_name]"; private const string LastNameMarker = @"$[last_name]"; private const string IsSuperUserMarker = @"'$[isSuperUser]'"; @@ -75,6 +75,31 @@ public static int GetUserId(string username) return results.SelectMany(x => x.Where(y => y.Key == "UserId").Select(y => (int)y.Value)).FirstOrDefault(); } + public static void DeleteUser(int userId) + { + var fileContent = SqlScripts.UserDelete; + var script = new StringBuilder(fileContent) + .Replace(UserIdMarker, userId.ToString(CultureInfo.InvariantCulture)) + .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) + .ToString(); + + DatabaseHelper.ExecuteQuery(script); + } + + public static TimeZoneInfo GetUserPreferredTimeZone(int userId, int portalId) + { + var fileContent = SqlScripts.UserGetPreferredTimeZone; + var script = new StringBuilder(fileContent) + .Replace(UserIdMarker, userId.ToString(CultureInfo.InvariantCulture)) + .Replace(PortalIdMarker, portalId.ToString(CultureInfo.InvariantCulture)) + .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) + .ToString(); + + var timeZoneString = DatabaseHelper.ExecuteQuery(script).First()["PropertyValue"].ToString(); + + return TimeZoneInfo.FindSystemTimeZoneById(timeZoneString); + } + private static int CreateUser(CreateUserParams parms) { parms.FirstName = parms.FirstName.Replace("'", "''"); @@ -109,31 +134,6 @@ private static int CreateUser(CreateUserParams parms) return GetUserId(username); } - public static void DeleteUser(int userId) - { - var fileContent = SqlScripts.UserDelete; - var script = new StringBuilder(fileContent) - .Replace(UserIdMarker, userId.ToString(CultureInfo.InvariantCulture)) - .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) - .ToString(); - - DatabaseHelper.ExecuteQuery(script); - } - - public static TimeZoneInfo GetUserPreferredTimeZone(int userId, int portalId) - { - var fileContent = SqlScripts.UserGetPreferredTimeZone; - var script = new StringBuilder(fileContent) - .Replace(UserIdMarker, userId.ToString(CultureInfo.InvariantCulture)) - .Replace(PortalIdMarker, portalId.ToString(CultureInfo.InvariantCulture)) - .Replace("{objectQualifier}", AppConfigHelper.ObjectQualifier) - .ToString(); - - var timeZoneString = DatabaseHelper.ExecuteQuery(script).First()["PropertyValue"].ToString(); - - return TimeZoneInfo.FindSystemTimeZoneById(timeZoneString); - } - public class CreateUserParams { public string FirstName { get; set; } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs index 700d1fe83d5..01813db46c1 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs @@ -6,12 +6,6 @@ namespace DNN.Integration.Test.Framework { public class FileParameter { - public byte[] File { get; set; } - - public string FileName { get; set; } - - public string ContentType { get; set; } - public FileParameter(byte[] file) : this(file, null) { @@ -28,5 +22,11 @@ public FileParameter(byte[] file, string filename, string contenttype) this.FileName = filename; this.ContentType = contenttype; } + + public byte[] File { get; set; } + + public string FileName { get; set; } + + public string ContentType { get; set; } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs index 17882d613aa..2c4168364c2 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs @@ -20,6 +20,15 @@ public static class AppConfigHelper private static string _connectionString; private static string _loginCookieString; + public static string ConnectionString => + _connectionString ?? (_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString); + + public static string ObjectQualifier => + _objectQualifier ?? (_objectQualifier = GetAppSetting("objectQualifier")); + + public static string SiteUrl => + _siteUrl ?? (_siteUrl = GetAppSetting("siteUrl") ?? DefaultWebsiteName); + public static string GetAppSetting(string key) { return ConfigurationManager.AppSettings[key]; @@ -37,15 +46,6 @@ public static int GetAppSettingAsInt(string key, int defaultValue) return int.TryParse(GetAppSetting(key), out value) ? value : defaultValue; } - public static string ConnectionString => - _connectionString ?? (_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString); - - public static string ObjectQualifier => - _objectQualifier ?? (_objectQualifier = GetAppSetting("objectQualifier")); - - public static string SiteUrl => - _siteUrl ?? (_siteUrl = GetAppSetting("siteUrl") ?? DefaultWebsiteName); - public static string HostUserName => _hostUserName ?? (_hostUserName = GetAppSetting("hostUserName") ?? DefaultHostName); diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs index 286c864237a..4e3ef150bb3 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs @@ -17,9 +17,10 @@ public static class DatabaseHelper { private const string QualifierPrefix = "{objectQualifier}"; - private static string ReplaceQueryQualifier(string input) + private static IDictionary ValuesDictionary { - return input.Replace(QualifierPrefix, AppConfigHelper.ObjectQualifier); + // case insensitive dictionary keys + get { return new Dictionary(StringComparer.InvariantCultureIgnoreCase); } } public static bool CanConnectToDatabase() @@ -42,6 +43,11 @@ public static T ExecuteScalar(string queryString, params object[] args) return PetaPocoHelper.ExecuteScalar(AppConfigHelper.ConnectionString, CommandType.Text, qstr, args); } + private static string ReplaceQueryQualifier(string input) + { + return input.Replace(QualifierPrefix, AppConfigHelper.ObjectQualifier); + } + public static IEnumerable ExecuteQuery(string queryString) { using (var connection = new SqlConnection(AppConfigHelper.ConnectionString)) @@ -235,11 +241,5 @@ public static IDictionary GetRecordById(string tableOrViewName, return values; } - - private static IDictionary ValuesDictionary - { - // case insensitive dictionary keys - get { return new Dictionary(StringComparer.InvariantCultureIgnoreCase); } - } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs index 29f8833ee24..670ea9b8371 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs @@ -21,12 +21,6 @@ public static class WebApiTestHelper private static readonly string HostGuid = HostSettingsHelper.GetHostSettingValue("GUID"); - internal static void ClearCachedConnections() - { - _anonymousConnector = null; - CachedConnections.Clear(); - } - /// /// Returns a coonector to access the default site annonymously. /// @@ -55,6 +49,12 @@ SELECT TOP 1 m.ModuleID FROM {{objectQualifier}}TabModules tm }; } + internal static void ClearCachedConnections() + { + _anonymousConnector = null; + CachedConnections.Clear(); + } + public static IWebApiConnector PrepareNewUser(out int userId, out string username, out int fileId, int portalId = 0) { username = $"testuser{Rnd.Next(1000, 9999)}"; @@ -107,6 +107,19 @@ public static HttpWebResponse Register(string userName, string password, string return connector.PostUserForm(registerRelativeUrl, postData, excludedInputPrefixes, false); } + public static string GenerateSha256Hash(this string str) + { + return str.GenerateHash("SHA256"); + } + + /// Generate a MD5 hash of a string. + /// + /// + public static string GenerateMd5(this string str) + { + return str.GenerateHash("MD5"); + } + private static string CodifyInputName(string originalId, string sufix, bool encriptName) { var transformedId = encriptName ? CodifyString(originalId) : originalId; @@ -132,50 +145,6 @@ private static string GenerateHash(string str) } } - public static string GenerateSha256Hash(this string str) - { - return str.GenerateHash("SHA256"); - } - - /// Generate a MD5 hash of a string. - /// - /// - public static string GenerateMd5(this string str) - { - return str.GenerateHash("MD5"); - } - - private static string GenerateHash(this string str, string hashType) - { - var hasher = HashAlgorithm.Create(hashType); - if (hasher == null) - { - throw new InvalidOperationException("No hashing type found by name " + hashType); - } - - using (hasher) - { - // convert our string into byte array - var byteArray = Encoding.UTF8.GetBytes(str); - - // get the hashed values created by our SHA1CryptoServiceProvider - var hashedByteArray = hasher.ComputeHash(byteArray); - - // create a StringBuilder object - var stringBuilder = new StringBuilder(); - - // loop to each each byte - foreach (var b in hashedByteArray) - { - // append it to our StringBuilder - stringBuilder.Append(b.ToString("x2").ToLowerInvariant()); - } - - // return the hashed value - return stringBuilder.ToString(); - } - } - /// /// Creates a Registered User and performs Login for that user in as well. /// Password used is same as that for Host. Existing user is used if it's already present. @@ -233,6 +202,37 @@ public static IWebApiConnector LoginAdministrator(string firstName = Integration return connector; } + private static string GenerateHash(this string str, string hashType) + { + var hasher = HashAlgorithm.Create(hashType); + if (hasher == null) + { + throw new InvalidOperationException("No hashing type found by name " + hashType); + } + + using (hasher) + { + // convert our string into byte array + var byteArray = Encoding.UTF8.GetBytes(str); + + // get the hashed values created by our SHA1CryptoServiceProvider + var hashedByteArray = hasher.ComputeHash(byteArray); + + // create a StringBuilder object + var stringBuilder = new StringBuilder(); + + // loop to each each byte + foreach (var b in hashedByteArray) + { + // append it to our StringBuilder + stringBuilder.Append(b.ToString("x2").ToLowerInvariant()); + } + + // return the hashed value + return stringBuilder.ToString(); + } + } + /// /// Logs in Host. /// diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs index ebe5ac0ac01..35f127df5d5 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs @@ -19,7 +19,7 @@ public interface IWebApiConnector CookieContainer SessionCookies { get; } - DateTime LoggedInAtTime { get; } + DateTime LoggedInAtTime { get; } TimeSpan Timeout { get; set; } @@ -27,6 +27,8 @@ public interface IWebApiConnector string UserAgentValue { get; set; } + bool AvoidCaching { get; set; } + void Logout(); bool Login(string password); @@ -53,7 +55,5 @@ HttpResponseMessage GetContent( HttpResponseMessage GetContent( string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true); - - bool AvoidCaching { get; set; } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs index b7bd0eb6bc5..afb9b84ee85 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs @@ -14,8 +14,6 @@ namespace DNN.Integration.Test.Framework public abstract class IntegrationTestBase { - public static string ConnectionString { get; } - // public static string DatabaseName { get; } static IntegrationTestBase() { @@ -32,6 +30,17 @@ static IntegrationTestBase() // SchedulerController.DisableAppStartDelay(false); } + public static string ConnectionString { get; } + + public static void LogText(string text) + { + // Don't write anything to console when we run in TeamCity + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) + { + Console.WriteLine(text); + } + } + [TestFixtureSetUp] public virtual void TestFixtureSetUp() { @@ -47,14 +56,5 @@ private static string GetDbNameFromConnectionString(string connectionString) var builder = new System.Data.Common.DbConnectionStringBuilder { ConnectionString = connectionString }; return builder["Database"] as string; } - - public static void LogText(string text) - { - // Don't write anything to console when we run in TeamCity - if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) - { - Console.WriteLine(text); - } - } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs index b9217df6362..18eebb13c0e 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs @@ -576,21 +576,6 @@ INSERT INTO [dbo].[{objectQualifier}ModulePermission] SELECT SCOPE_IDENTITY() AS ModulePermissionId"; - public static string UserGetPreferredTimeZone = @" - DECLARE @UserId INT - DECLARE @PortalID INT - DECLARE @PropertyDefinitionId INT - - SET @UserId = '$[user_id]' - SET @PortalID = '$[portal_id]' - - SELECT TOP 1 @PropertyDefinitionId = PropertyDefinitionID - FROM [dbo].[{objectQualifier}ProfilePropertyDefinition] - WHERE PortalID = @PortalID AND PropertyName = 'PreferredTimeZone' AND PropertyCategory = 'Preferences' - - SELECT PropertyValue FROM [dbo].[{objectQualifier}UserProfile] - WHERE PropertyDefinitionID = @PropertyDefinitionId AND [UserId] = @UserId"; - public const string PortalGetTimeZone = @" DECLARE @PortalID INT SET @PortalID = '$[portal_id]' @@ -616,6 +601,21 @@ FROM dbo.{objectQualifier}DesktopModules dtm AND (dtm.FriendlyName = @friendlyName OR mdfn.FriendlyName = @friendlyName) ORDER BY dtm.FriendlyName, mdfn.FriendlyName, dtm.DesktopModuleID, mdfn.ModuleDefID, mdl.ModuleID;"; + public static string UserGetPreferredTimeZone = @" + DECLARE @UserId INT + DECLARE @PortalID INT + DECLARE @PropertyDefinitionId INT + + SET @UserId = '$[user_id]' + SET @PortalID = '$[portal_id]' + + SELECT TOP 1 @PropertyDefinitionId = PropertyDefinitionID + FROM [dbo].[{objectQualifier}ProfilePropertyDefinition] + WHERE PortalID = @PortalID AND PropertyName = 'PreferredTimeZone' AND PropertyCategory = 'Preferences' + + SELECT PropertyValue FROM [dbo].[{objectQualifier}UserProfile] + WHERE PropertyDefinitionID = @PropertyDefinitionId AND [UserId] = @UserId"; + public const string TableExist = @" IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.[{objectQualifier}$[table_name]]') AND type in (N'U')) SELECT 1 diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs index 81129723583..f4b014e6b25 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs @@ -25,6 +25,17 @@ namespace DNN.Integration.Test.Framework internal class WebApiConnector : IWebApiConnector, IDisposable { + public const string FileFilters = + "swf,jpg,jpeg,jpe,gif,bmp,png,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,xml," + + "xsl,xsd,css,zip,template,htmtemplate,ico,avi,mpg,mpeg,mp3,wmv,mov,wav"; + + public const string RqVerifTokenName = "__RequestVerificationToken"; + public const string RqVerifTokenNameNoUndescrores = "RequestVerificationToken"; + + private const string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"; + + private const string LoginPath = "/Login"; + private static readonly Dictionary CachedPages = new Dictionary(); public static WebApiConnector GetWebConnector(string siteUrl, string userName) @@ -34,12 +45,12 @@ public static WebApiConnector GetWebConnector(string siteUrl, string userName) UserName = (userName ?? string.Empty).Replace("'", string.Empty), }; } - - public const string FileFilters = - "swf,jpg,jpeg,jpe,gif,bmp,png,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,xml," + - "xsl,xsd,css,zip,template,htmtemplate,ico,avi,mpg,mpeg,mp3,wmv,mov,wav"; - - private const string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36"; + private const string LogoffPath = "/Home/ctl/Logoff"; + + // private const string LogoffPath = "/Home/ctl/Logoff.aspx"; + // private const string LogoffPath = "/Logoff.aspx"); + // private const string LogoffPath = "/Home/tabid/55/ctl/LogOff/Default.aspx"); + private const string UploadFileRequestPath = "API/internalservices/fileupload/postfile"; private string _userAgentValue; @@ -48,25 +59,15 @@ public string UserAgentValue get { return this._userAgentValue ?? (this._userAgentValue = ConfigurationManager.AppSettings["HttpUserAgent"] ?? DefaultUserAgent); } set { this._userAgentValue = value; } } - - private const string LoginPath = "/Login"; - private const string LogoffPath = "/Home/ctl/Logoff"; - - // private const string LogoffPath = "/Home/ctl/Logoff.aspx"; - // private const string LogoffPath = "/Logoff.aspx"); - // private const string LogoffPath = "/Home/tabid/55/ctl/LogOff/Default.aspx"); - private const string UploadFileRequestPath = "API/internalservices/fileupload/postfile"; private const string ActivityStreamUploadFilePath = "API/DNNCorp/ActivityStream/FileUpload/UploadFile"; + private static readonly Regex HtmlFormInuts = new Regex( + @"", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline); private int _userId; public bool AvoidCaching { get; set; } - private void ResetUserId() - { - this._userId = -1; - } - /// /// Gets the userID will be available only if the user is logged in. /// After obtaining it for the first time, it will be cached until logout. @@ -88,17 +89,20 @@ public int UserId public bool IsLoggedIn { get; private set; } - public const string RqVerifTokenName = "__RequestVerificationToken"; - public const string RqVerifTokenNameNoUndescrores = "RequestVerificationToken"; + private void ResetUserId() + { + this._userId = -1; + } + + // ============================================================================== + // Adapted from http://www.briangrinstead.com/blog/multipart-form-post-in-c# + private static readonly Encoding Encoding = Encoding.UTF8; + private CookieContainer _sessionCookiesContainer; private Cookie _cookieVerificationToken; private string _inputFieldVerificationToken; private string _currentTabId; - public TimeSpan Timeout { get; set; } - - public Uri Domain { get; } - private WebApiConnector(string siteUrl) { this.Timeout = TimeSpan.FromMinutes(1); @@ -110,21 +114,9 @@ private WebApiConnector(string siteUrl) this.AvoidCaching = false; } - public void Dispose() - { - this.Logout(); - } - - private void EnsureLoggedIn() - { - if (!this.IsLoggedIn) - { - Console.WriteLine(@"User not logged in yet"); - throw new WebApiException( - new HttpRequestException("User not logged in yet."), - new HttpResponseMessage(HttpStatusCode.Unauthorized)); - } - } + public TimeSpan Timeout { get; set; } + + public Uri Domain { get; } public CookieContainer SessionCookies { @@ -137,6 +129,11 @@ public CookieContainer SessionCookies public DateTime LoggedInAtTime { get; private set; } + public void Dispose() + { + this.Logout(); + } + public void Logout() { if (this.IsLoggedIn) @@ -178,6 +175,17 @@ public void Logout() } } + private void EnsureLoggedIn() + { + if (!this.IsLoggedIn) + { + Console.WriteLine(@"User not logged in yet"); + throw new WebApiException( + new HttpRequestException("User not logged in yet."), + new HttpResponseMessage(HttpStatusCode.Unauthorized)); + } + } + public bool Login(string password) { if (this.IsLoggedIn) @@ -219,6 +227,57 @@ public bool Login(string password) return this.IsLoggedIn; } + + public HttpResponseMessage UploadUserFile(string fileName, bool waitHttpResponse = true, int userId = -1) + { + this.EnsureLoggedIn(); + + var folder = "Users"; + if (userId > Null.NullInteger) + { + var rootFolder = PathUtils.Instance.GetUserFolderPathElement(userId, PathUtils.UserFolderElement.Root); + var subFolder = PathUtils.Instance.GetUserFolderPathElement(userId, PathUtils.UserFolderElement.SubFolder); + folder = $"Users/{rootFolder}/{subFolder}/{userId}/"; + } + + return this.UploadFile(fileName, folder, waitHttpResponse); + } + + public HttpResponseMessage ActivityStreamUploadUserFile(IDictionary headers, string fileName) + { + this.EnsureLoggedIn(); + return this.ActivityStreamUploadFile(headers, fileName); + } + + private static string GetVerificationToken(string pageData) + { + if (!string.IsNullOrEmpty(pageData)) + { + const string str1 = "= str1.Length) + { + var num1 = pageData.IndexOf("\"", startIndex1, StringComparison.Ordinal); + return pageData.Substring(startIndex1, num1 - startIndex1); + } + } + + return string.Empty; + } + + private static string GetCurrentTabId(string pageData) + { + if (!string.IsNullOrEmpty(pageData)) + { + var match = Regex.Match(pageData, "`sf_tabId`:`(\\d+)`"); + if (match.Success) + { + return match.Groups[1].Value; + } + } + + return string.Empty; + } private void VerifyLogInCookie(HttpWebResponse httpResponse) { @@ -275,62 +334,89 @@ private void ExtractVerificationCookie(string cookiesString) } } - private static string GetVerificationToken(string pageData) + public bool UploadCmsFile(string fileName, string portalFolder) { - if (!string.IsNullOrEmpty(pageData)) - { - const string str1 = "= str1.Length) - { - var num1 = pageData.IndexOf("\"", startIndex1, StringComparison.Ordinal); - return pageData.Substring(startIndex1, num1 - startIndex1); - } - } - - return string.Empty; + this.EnsureLoggedIn(); + var result = this.UploadFile(fileName, portalFolder); + return result.IsSuccessStatusCode; } - - private static string GetCurrentTabId(string pageData) + + public HttpResponseMessage PostJson( + string relativeUrl, + object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) { - if (!string.IsNullOrEmpty(pageData)) + if (!ignoreLoggedIn) + { + this.EnsureLoggedIn(); + } + + using (var client = this.CreateHttpClient("/", true)) { - var match = Regex.Match(pageData, "`sf_tabId`:`(\\d+)`"); - if (match.Success) + var rqHeaders = client.DefaultRequestHeaders; + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); + rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); + rqHeaders.UserAgent.Clear(); + rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); + + if (contentHeaders != null) { - return match.Groups[1].Value; + foreach (var hdr in contentHeaders) + { + if (rqHeaders.Contains(hdr.Key)) + { + rqHeaders.Remove(hdr.Key); + } + + rqHeaders.Add(hdr.Key, hdr.Value); + } } + + var requestUriString = CombineUrlPath(this.Domain, relativeUrl); + var result = client.PostAsJsonAsync(requestUriString, content).Result; + return !waitHttpResponse + ? result + : EnsureSuccessResponse(result, "PostJson", requestUriString); } + } - return string.Empty; - } - - public HttpResponseMessage UploadUserFile(string fileName, bool waitHttpResponse = true, int userId = -1) + public HttpResponseMessage PutJson( + string relativeUrl, + object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) { - this.EnsureLoggedIn(); - - var folder = "Users"; - if (userId > Null.NullInteger) + if (!ignoreLoggedIn) + { + this.EnsureLoggedIn(); + } + + using (var client = this.CreateHttpClient("/", true)) { - var rootFolder = PathUtils.Instance.GetUserFolderPathElement(userId, PathUtils.UserFolderElement.Root); - var subFolder = PathUtils.Instance.GetUserFolderPathElement(userId, PathUtils.UserFolderElement.SubFolder); - folder = $"Users/{rootFolder}/{subFolder}/{userId}/"; - } + var rqHeaders = client.DefaultRequestHeaders; + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); + rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); + rqHeaders.UserAgent.Clear(); + rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); - return this.UploadFile(fileName, folder, waitHttpResponse); - } + if (contentHeaders != null) + { + foreach (var hdr in contentHeaders) + { + if (rqHeaders.Contains(hdr.Key)) + { + rqHeaders.Remove(hdr.Key); + } - public HttpResponseMessage ActivityStreamUploadUserFile(IDictionary headers, string fileName) - { - this.EnsureLoggedIn(); - return this.ActivityStreamUploadFile(headers, fileName); - } + rqHeaders.Add(hdr.Key, hdr.Value); + } + } - public bool UploadCmsFile(string fileName, string portalFolder) - { - this.EnsureLoggedIn(); - var result = this.UploadFile(fileName, portalFolder); - return result.IsSuccessStatusCode; + var requestUriString = CombineUrlPath(this.Domain, relativeUrl); + var result = client.PutAsJsonAsync(requestUriString, content).Result; + return !waitHttpResponse + ? result + : EnsureSuccessResponse(result, "PutJson", requestUriString); + } } private HttpResponseMessage UploadFile(string fileName, string portalFolder, bool waitHttpResponse = true) @@ -439,169 +525,6 @@ private HttpResponseMessage ActivityStreamUploadFile( : EnsureSuccessResponse(result, "ActivityStreamUploadFile", ActivityStreamUploadFilePath); } } - - public HttpResponseMessage PostJson( - string relativeUrl, - object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) - { - if (!ignoreLoggedIn) - { - this.EnsureLoggedIn(); - } - - using (var client = this.CreateHttpClient("/", true)) - { - var rqHeaders = client.DefaultRequestHeaders; - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); - rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); - rqHeaders.UserAgent.Clear(); - rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); - - if (contentHeaders != null) - { - foreach (var hdr in contentHeaders) - { - if (rqHeaders.Contains(hdr.Key)) - { - rqHeaders.Remove(hdr.Key); - } - - rqHeaders.Add(hdr.Key, hdr.Value); - } - } - - var requestUriString = CombineUrlPath(this.Domain, relativeUrl); - var result = client.PostAsJsonAsync(requestUriString, content).Result; - return !waitHttpResponse - ? result - : EnsureSuccessResponse(result, "PostJson", requestUriString); - } - } - - public HttpResponseMessage PutJson( - string relativeUrl, - object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) - { - if (!ignoreLoggedIn) - { - this.EnsureLoggedIn(); - } - - using (var client = this.CreateHttpClient("/", true)) - { - var rqHeaders = client.DefaultRequestHeaders; - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); - rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); - rqHeaders.UserAgent.Clear(); - rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); - - if (contentHeaders != null) - { - foreach (var hdr in contentHeaders) - { - if (rqHeaders.Contains(hdr.Key)) - { - rqHeaders.Remove(hdr.Key); - } - - rqHeaders.Add(hdr.Key, hdr.Value); - } - } - - var requestUriString = CombineUrlPath(this.Domain, relativeUrl); - var result = client.PutAsJsonAsync(requestUriString, content).Result; - return !waitHttpResponse - ? result - : EnsureSuccessResponse(result, "PutJson", requestUriString); - } - } - - private HttpClient CreateHttpClient(string path, bool autoRedirect) - { - var clientHandler = new HttpClientHandler - { - AllowAutoRedirect = autoRedirect, - CookieContainer = this._sessionCookiesContainer, - }; - - var url = CombineUrlPath(this.Domain, path); - var client = new HttpClient(clientHandler) - { - BaseAddress = this.Domain, - Timeout = this.Timeout, - }; - - if (string.IsNullOrEmpty(this._inputFieldVerificationToken)) - { - client.DefaultRequestHeaders.UserAgent.ParseAdd(this.UserAgentValue); - var resultGet = client.GetAsync(url).Result; - var data = resultGet.Content.ReadAsStringAsync().Result; - this._inputFieldVerificationToken = GetVerificationToken(data); - client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); - - this._currentTabId = GetCurrentTabId(data); - client.DefaultRequestHeaders.Add("TabId", this._currentTabId); - } - else - { - client.DefaultRequestHeaders.Add("TabId", this._currentTabId); - client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); - } - - return client; - } - - private string[] GetPageInputFields(HttpClient client, string path) - { - CachedWebPage cachedPage = null; - var url = CombineUrlPath(this.Domain, path); - if (!this.IsLoggedIn || this.AvoidCaching || - (!CachedPages.TryGetValue(url, out cachedPage) || - cachedPage.FetchDateTime < DateTime.Now.AddMinutes(-19.5))) - { - try - { - var requestVerificationToken = string.Empty; - client.DefaultRequestHeaders.UserAgent.ParseAdd(this.UserAgentValue); - var resultGet = client.GetAsync(url).Result; - var data = resultGet.Content.ReadAsStringAsync().Result; - const string str1 = "= 0) - { - startIndex1 += str1.Length; - var num1 = data.IndexOf("\"", startIndex1, StringComparison.Ordinal); - requestVerificationToken = data.Substring(startIndex1, num1 - startIndex1); - client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, requestVerificationToken); - } - else - { - Console.WriteLine(@"Cannot find '{0}' in the page input fields. Data: {1}", RqVerifTokenName, resultGet); - } - - var inputFields = HtmlFormInuts.Matches(data).Cast().Select(match => match.Groups[0].Value).ToArray(); - cachedPage = new CachedWebPage(requestVerificationToken, inputFields); - CachedPages[url] = cachedPage; - return inputFields; - } - catch (Exception ex) - { - Console.WriteLine(@"Error accessing this path {0}.{1}{2}", path, Environment.NewLine, ex); - } - } - else - { - client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, cachedPage.VerificationToken); - } - - return cachedPage != null ? cachedPage.InputFields : new string[0]; - } - - private static readonly Regex HtmlFormInuts = new Regex( - @"", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline); public HttpWebResponse PostUserForm(string relativeUrl, IDictionary formFields, List excludedInputPrefixes, bool checkUserLoggedIn = true, bool followRedirect = false) @@ -733,66 +656,126 @@ where key.StartsWith(prefix) return null; } - // ============================================================================== - // Adapted from http://www.briangrinstead.com/blog/multipart-form-post-in-c# - private static readonly Encoding Encoding = Encoding.UTF8; - public HttpWebResponse MultipartFormDataPost(string relativeUrl, IDictionary postParameters, IDictionary headers = null, bool followRedirect = false) { var url = CombineUrlPath(this.Domain, relativeUrl); return this.MultipartFormDataPost(url, this.UserAgentValue, postParameters, headers, followRedirect); } - private HttpWebResponse MultipartFormDataPost( - string postUrl, string userAgent, IDictionary postParameters, IDictionary headers = null, bool followRedirect = false) + private HttpClient CreateHttpClient(string path, bool autoRedirect) { - var formDataBoundary = string.Format("----WebKitFormBoundary{0:X16}", DateTime.Now.Ticks); - var contentType = "multipart/form-data; boundary=" + formDataBoundary; - var formData = GetMultipartFormData(postParameters, formDataBoundary); - return this.PostForm(postUrl, userAgent, contentType, headers, formData, followRedirect); - } + var clientHandler = new HttpClientHandler + { + AllowAutoRedirect = autoRedirect, + CookieContainer = this._sessionCookiesContainer, + }; - private HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, IDictionary headers, byte[] formData, bool followRedirect) - { - var request = WebRequest.Create(postUrl) as HttpWebRequest; + var url = CombineUrlPath(this.Domain, path); + var client = new HttpClient(clientHandler) + { + BaseAddress = this.Domain, + Timeout = this.Timeout, + }; - if (request == null) + if (string.IsNullOrEmpty(this._inputFieldVerificationToken)) { - throw new NullReferenceException("request is not a http request"); + client.DefaultRequestHeaders.UserAgent.ParseAdd(this.UserAgentValue); + var resultGet = client.GetAsync(url).Result; + var data = resultGet.Content.ReadAsStringAsync().Result; + this._inputFieldVerificationToken = GetVerificationToken(data); + client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); + + this._currentTabId = GetCurrentTabId(data); + client.DefaultRequestHeaders.Add("TabId", this._currentTabId); + } + else + { + client.DefaultRequestHeaders.Add("TabId", this._currentTabId); + client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); } - // Set up the request properties. - request.Method = "POST"; - request.ContentType = contentType; - request.UserAgent = userAgent; - request.CookieContainer = this._sessionCookiesContainer; - request.ContentLength = formData.Length; - request.Headers.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); - if (headers != null) + return client; + } + + private string[] GetPageInputFields(HttpClient client, string path) + { + CachedWebPage cachedPage = null; + var url = CombineUrlPath(this.Domain, path); + if (!this.IsLoggedIn || this.AvoidCaching || + (!CachedPages.TryGetValue(url, out cachedPage) || + cachedPage.FetchDateTime < DateTime.Now.AddMinutes(-19.5))) { - foreach (var h in headers) + try { - request.Headers.Add(h.Key, h.Value); + var requestVerificationToken = string.Empty; + client.DefaultRequestHeaders.UserAgent.ParseAdd(this.UserAgentValue); + var resultGet = client.GetAsync(url).Result; + var data = resultGet.Content.ReadAsStringAsync().Result; + const string str1 = "= 0) + { + startIndex1 += str1.Length; + var num1 = data.IndexOf("\"", startIndex1, StringComparison.Ordinal); + requestVerificationToken = data.Substring(startIndex1, num1 - startIndex1); + client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, requestVerificationToken); + } + else + { + Console.WriteLine(@"Cannot find '{0}' in the page input fields. Data: {1}", RqVerifTokenName, resultGet); + } + + var inputFields = HtmlFormInuts.Matches(data).Cast().Select(match => match.Groups[0].Value).ToArray(); + cachedPage = new CachedWebPage(requestVerificationToken, inputFields); + CachedPages[url] = cachedPage; + return inputFields; } + catch (Exception ex) + { + Console.WriteLine(@"Error accessing this path {0}.{1}{2}", path, Environment.NewLine, ex); + } + } + else + { + client.DefaultRequestHeaders.Add(RqVerifTokenNameNoUndescrores, cachedPage.VerificationToken); } - request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; - request.KeepAlive = true; - request.ReadWriteTimeout = 90; - request.AllowAutoRedirect = followRedirect; - request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); + return cachedPage != null ? cachedPage.InputFields : new string[0]; + } - // You could add authentication here as well if needed: - // request.PreAuthenticate = true; - // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; - // request.Headers.Add("Authorization", "Basic " + - // Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password"))); + public HttpResponseMessage GetContent( + string relativeUrl, object parameters, Dictionary contentHeaders = null, + bool waitHttpResponse = true, bool autoRedirect = true) + { + var url = relativeUrl + "?" + QueryStringFromObject(parameters); + return this.GetContent(url, contentHeaders, waitHttpResponse, autoRedirect); + } - // Send the form data to the request. - using (var requestStream = request.GetRequestStream()) + public HttpResponseMessage GetContent( + string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true) + { + using (var client = this.CreateHttpClient("/", autoRedirect)) { - requestStream.Write(formData, 0, formData.Length); - return request.GetResponse() as HttpWebResponse; + var rqHeaders = client.DefaultRequestHeaders; + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); + rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); + rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); + + if (contentHeaders != null) + { + foreach (var hdr in contentHeaders) + { + rqHeaders.Add(hdr.Key, hdr.Value); + } + } + + var requestUriString = CombineUrlPath(this.Domain, relativeUrl); + var uri = new Uri(requestUriString); + var result = client.GetAsync(uri.AbsoluteUri).Result; + return !waitHttpResponse + ? result + : EnsureSuccessResponse(result, "GetContent", uri.AbsoluteUri); } } @@ -886,51 +869,68 @@ private static string CombineUrlPath(Uri domain, string path) return new Uri(url + path).AbsoluteUri; } - private static string QueryStringFromObject(object query) + private HttpWebResponse MultipartFormDataPost( + string postUrl, string userAgent, IDictionary postParameters, IDictionary headers = null, bool followRedirect = false) { - var properties = from p in query.GetType().GetProperties() - where p.GetValue(query, null) != null - select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(query, null).ToString()); - - return string.Join("&", properties.ToArray()); + var formDataBoundary = string.Format("----WebKitFormBoundary{0:X16}", DateTime.Now.Ticks); + var contentType = "multipart/form-data; boundary=" + formDataBoundary; + var formData = GetMultipartFormData(postParameters, formDataBoundary); + return this.PostForm(postUrl, userAgent, contentType, headers, formData, followRedirect); } - public HttpResponseMessage GetContent( - string relativeUrl, object parameters, Dictionary contentHeaders = null, - bool waitHttpResponse = true, bool autoRedirect = true) + private HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, IDictionary headers, byte[] formData, bool followRedirect) { - var url = relativeUrl + "?" + QueryStringFromObject(parameters); - return this.GetContent(url, contentHeaders, waitHttpResponse, autoRedirect); - } + var request = WebRequest.Create(postUrl) as HttpWebRequest; - public HttpResponseMessage GetContent( - string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true) - { - using (var client = this.CreateHttpClient("/", autoRedirect)) + if (request == null) { - var rqHeaders = client.DefaultRequestHeaders; - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - rqHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html", 0.5d)); - rqHeaders.Add("X-Requested-With", "XMLHttpRequest"); - rqHeaders.UserAgent.ParseAdd(this.UserAgentValue); + throw new NullReferenceException("request is not a http request"); + } - if (contentHeaders != null) + // Set up the request properties. + request.Method = "POST"; + request.ContentType = contentType; + request.UserAgent = userAgent; + request.CookieContainer = this._sessionCookiesContainer; + request.ContentLength = formData.Length; + request.Headers.Add(RqVerifTokenNameNoUndescrores, this._inputFieldVerificationToken); + if (headers != null) + { + foreach (var h in headers) { - foreach (var hdr in contentHeaders) - { - rqHeaders.Add(hdr.Key, hdr.Value); - } + request.Headers.Add(h.Key, h.Value); } + } - var requestUriString = CombineUrlPath(this.Domain, relativeUrl); - var uri = new Uri(requestUriString); - var result = client.GetAsync(uri.AbsoluteUri).Result; - return !waitHttpResponse - ? result - : EnsureSuccessResponse(result, "GetContent", uri.AbsoluteUri); + request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; + request.KeepAlive = true; + request.ReadWriteTimeout = 90; + request.AllowAutoRedirect = followRedirect; + request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); + + // You could add authentication here as well if needed: + // request.PreAuthenticate = true; + // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; + // request.Headers.Add("Authorization", "Basic " + + // Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password"))); + + // Send the form data to the request. + using (var requestStream = request.GetRequestStream()) + { + requestStream.Write(formData, 0, formData.Length); + return request.GetResponse() as HttpWebResponse; } } + private static string QueryStringFromObject(object query) + { + var properties = from p in query.GetType().GetProperties() + where p.GetValue(query, null) != null + select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(query, null).ToString()); + + return string.Join("&", properties.ToArray()); + } + private static HttpResponseMessage EnsureSuccessResponse(HttpResponseMessage result, string source, string url) { var body = string.Empty; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs index 00e42ca5976..a731448dfd2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs @@ -17,8 +17,8 @@ namespace DotNetNuke.Tests.AspNetClientCapabilityProvider [TestFixture] public class AspNetClientCapabilityProviderTest { - private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; private const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; + private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; [SetUp] public void Setup() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs index d4e36d1a332..a39bc7abf0e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs @@ -17,10 +17,10 @@ namespace DotNetNuke.Tests.AspNetClientCapabilityProviderTest [TestFixture] public class AspNetClientCapabilityTest { - private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; public const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; - public const string wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; + + private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; public const string msIE8UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; Creative AutoUpdate v1.40.02)"; public const string msIE9UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs index cfc73720487..62f40288699 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs @@ -44,50 +44,6 @@ public void TearDown() MockComponentProvider.ResetContainer(); } - private static Mock DataServiceFactory() - { - var dataService = new Mock(); - - dataService.Setup(ds => - ds.SynchronizeMetaData( - It.IsAny(), - It.IsAny>>(), - It.IsAny>>())) - .Callback>, IEnumerable>>( - (ci, added, deleted) => - { - deleted.ToList().ForEach( - item => dataService.Object.DeleteMetaData(ci, item.Key, item.Value)); - - added.ToList().ForEach( - item => dataService.Object.AddMetaData(ci, item.Key, item.Value)); - }); - - // Register controller types that are dependent on our IDataService. - var contentController = new ContentController(dataService.Object); - - ComponentFactory.RegisterComponentInstance(new FileController(contentController)); - ComponentFactory.RegisterComponentInstance(contentController); - ComponentFactory.RegisterComponentInstance(MockHelper.CreateMockFileManager().Object); - - return dataService; - } - - private static Mock DataServiceFactoryWithLocalMetaData(ref Dictionary metadata) - { - var dataService = DataServiceFactory(); - - var closure = metadata; - - dataService.Setup(ds => ds.GetMetaData(It.IsAny())).Returns(() => MockHelper.CreateMetaDataReaderFromDictionary(closure)); - dataService.Setup(ds => ds.AddMetaData(It.IsAny(), It.IsAny(), It.IsAny())). - Callback((ci, name, value) => closure[name] = value); - dataService.Setup(ds => ds.DeleteMetaData(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((ci, key, val) => closure.Remove(key)); - - return dataService; - } - [Test] public void Test_Add_File_To_Content_Item_Without_Metadata() { @@ -148,6 +104,50 @@ public void Test_Load_Attachments_From_DataService() Assert.AreEqual(contentItem.Files[1].FileId, 1); Assert.AreEqual(contentItem.Files[2].FileId, 2); } + + private static Mock DataServiceFactory() + { + var dataService = new Mock(); + + dataService.Setup(ds => + ds.SynchronizeMetaData( + It.IsAny(), + It.IsAny>>(), + It.IsAny>>())) + .Callback>, IEnumerable>>( + (ci, added, deleted) => + { + deleted.ToList().ForEach( + item => dataService.Object.DeleteMetaData(ci, item.Key, item.Value)); + + added.ToList().ForEach( + item => dataService.Object.AddMetaData(ci, item.Key, item.Value)); + }); + + // Register controller types that are dependent on our IDataService. + var contentController = new ContentController(dataService.Object); + + ComponentFactory.RegisterComponentInstance(new FileController(contentController)); + ComponentFactory.RegisterComponentInstance(contentController); + ComponentFactory.RegisterComponentInstance(MockHelper.CreateMockFileManager().Object); + + return dataService; + } + + private static Mock DataServiceFactoryWithLocalMetaData(ref Dictionary metadata) + { + var dataService = DataServiceFactory(); + + var closure = metadata; + + dataService.Setup(ds => ds.GetMetaData(It.IsAny())).Returns(() => MockHelper.CreateMetaDataReaderFromDictionary(closure)); + dataService.Setup(ds => ds.AddMetaData(It.IsAny(), It.IsAny(), It.IsAny())). + Callback((ci, name, value) => closure[name] = value); + dataService.Setup(ds => ds.DeleteMetaData(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((ci, key, val) => closure.Remove(key)); + + return dataService; + } [Test] public void Test_Add_Attachments_With_FileController() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs index e2258019e83..41c34cfeecb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs @@ -48,6 +48,16 @@ internal static IQueryable TestVocabularies return vocabularies.AsQueryable(); } } + + internal static IDataReader CreateEmptyContentItemReader() + { + return CreateContentItemTable().CreateDataReader(); + } + + internal static IDataReader CreateEmptyContentTypeReader() + { + return CreateContentTypeTable().CreateDataReader(); + } private static void AddBaseEntityColumns(DataTable table) { @@ -205,16 +215,6 @@ private static Mock RegisterMockController(Mock mock) return getMock; } - - internal static IDataReader CreateEmptyContentItemReader() - { - return CreateContentItemTable().CreateDataReader(); - } - - internal static IDataReader CreateEmptyContentTypeReader() - { - return CreateContentTypeTable().CreateDataReader(); - } internal static IDataReader CreateEmptyScopeTypeReader() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/app.config b/DNN Platform/Tests/DotNetNuke.Tests.Content/app.config index 9a323d5bf20..d3f880af864 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/app.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/app.config @@ -1,27 +1,27 @@ - - - - -
- - - - - - - - - - - - - - - - - - - - - + + + + +
+ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs index 1394fc8c2e3..b0797887759 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs @@ -13,8 +13,6 @@ namespace DotNetNuke.Tests.Core.Collections public abstract class LockStrategyTests { - internal abstract ILockStrategy GetLockStrategy(); - [Test] public void DoubleDisposeAllowed() { @@ -41,6 +39,8 @@ public virtual void DoubleReadLockThrows() } } } + + internal abstract ILockStrategy GetLockStrategy(); [Test] [ExpectedException(typeof(LockRecursionException))] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs index a15e34050ad..2f581fee789 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs @@ -13,13 +13,13 @@ namespace DotNetNuke.Tests.Core.Collections [TestFixture] public class PageSelectorTests { + private IEnumerable list; + [SetUp] public void SetUp() { this.list = Util.CreateIntegerList(Constants.PAGE_TotalCount); } - - private IEnumerable list; [Test] [TestCase(0)] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs index 644b20c51c7..38264958a19 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs @@ -10,11 +10,6 @@ namespace DotNetNuke.Tests.Core.Collections [TestFixture] public class ReaderWriterLockStrategyTests : LockStrategyTests { - internal override ILockStrategy GetLockStrategy() - { - return new ReaderWriterLockStrategy(); - } - [Test] // no ExpectedException attribute public override void DoubleReadLockThrows() { @@ -26,5 +21,10 @@ public override void DoubleWriteLockThrows() { base.DoubleWriteLockThrows(); } + + internal override ILockStrategy GetLockStrategy() + { + return new ReaderWriterLockStrategy(); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs index c11385cee58..74fa0cf825d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs @@ -20,9 +20,9 @@ namespace DotNetNuke.Tests.Core.Common [TestFixture] public class NavigationManagerTests { - private INavigationManager _navigationManager; private const int TabID = 100; private const int PortalID = 7; + private INavigationManager _navigationManager; private const string DefaultURLPattern = "/Default.aspx?tabid={0}"; private const string DefaultSuperTabPattern = "&portalid={0}"; private const string ControlKeyPattern = "&ctl={0}"; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs index 50670980fcb..e8d0ba1acf1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs @@ -18,6 +18,14 @@ namespace DotNetNuke.Tests.Core.ComponentModel [TestFixture] public class ComponentFactoryTests { + public static IContainer CreateMockContainer() + { + var mockContainer = new Mock(); + IContainer container = mockContainer.Object; + ComponentFactory.Container = container; + return container; + } + [TearDown] public void TearDown() { @@ -69,13 +77,5 @@ public void DNNPRO_13443_ComponentFactory_DuplicatedInsert() var retreivedComponent = ComponentFactory.GetComponent(); Assert.AreEqual(testComp1, retreivedComponent); } - - public static IContainer CreateMockContainer() - { - var mockContainer = new Mock(); - IContainer container = mockContainer.Object; - ComponentFactory.Container = container; - return container; - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs index 7924bf395b0..73d4bdbaeab 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs @@ -61,11 +61,6 @@ public void TearDown() { MockComponentProvider.ResetContainer(); } - - private string GetValue(string key) - { - return this._hostSettingsTable.Rows.Find(key)["SettingValue"].ToString(); - } [Test] public void HostController_GetSettings_GetList() @@ -109,6 +104,11 @@ public void HostController_GetSettingsDictionary_GetList() // Assert CollectionAssert.AreEquivalent(expectedDic.Values, settingsDic.Values); } + + private string GetValue(string key) + { + return this._hostSettingsTable.Rows.Find(key)["SettingValue"].ToString(); + } [Test] public void HostController_Update_ExistingValue() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionBuilder.cs index 5723baa169f..18efe757c04 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionBuilder.cs @@ -85,19 +85,19 @@ internal SubscriptionBuilder WithTabId(int tabId) internal Subscription Build() { - return new Subscription - { - SubscriptionTypeId = this.subscriptionTypeId, - SubscriptionId = this.subscriptionId, - CreatedOnDate = DateTime.UtcNow, - ModuleId = this.moduleId, - ObjectKey = this.objectKey, - Description = this.description, - PortalId = this.portalId, - TabId = this.tabId, - UserId = this.userId, - ObjectData = this.objectData, - }; + return new Subscription + { + SubscriptionTypeId = this.subscriptionTypeId, + SubscriptionId = this.subscriptionId, + CreatedOnDate = DateTime.UtcNow, + ModuleId = this.moduleId, + ObjectKey = this.objectKey, + Description = this.description, + PortalId = this.portalId, + TabId = this.tabId, + UserId = this.userId, + ObjectData = this.objectData, + }; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionTypeBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionTypeBuilder.cs index f6605035cde..94ff287619a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionTypeBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Builders/SubscriptionTypeBuilder.cs @@ -36,13 +36,13 @@ internal SubscriptionTypeBuilder WithSubscriptionName(string subscriptionName) internal SubscriptionType Build() { - return new SubscriptionType - { - SubscriptionTypeId = this.subscriptionTypeId, - SubscriptionName = this.subscriptionName, - DesktopModuleId = this.desktopModuleId, - FriendlyName = this.friendlyName, - }; + return new SubscriptionType + { + SubscriptionTypeId = this.subscriptionTypeId, + SubscriptionName = this.subscriptionName, + DesktopModuleId = this.desktopModuleId, + FriendlyName = this.friendlyName, + }; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs index 44b5e87e982..9851c0f78d9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs @@ -112,6 +112,23 @@ public void TearDown() ComponentFactory.Container = null; PortalController.ClearInstance(); } + + [Test] + public void MessagingController_Constructor_Throws_On_Null_DataService() + { + // Arrange + + // Act, Assert + Assert.Throws(() => new MessagingController(null)); + } + + [Test] + public void AttachmentsAllowed_Returns_True_When_MessagingAllowAttachments_Setting_Is_YES() + { + this._mockMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("YES"); + var result = this._mockInternalMessagingController.Object.AttachmentsAllowed(Constants.CONTENT_ValidPortalId); + Assert.IsTrue(result); + } private void SetupDataProvider() { @@ -143,10 +160,10 @@ private void SetupUsers() private void SetupPortalSettings() { - var portalSettings = new PortalSettings - { - AdministratorRoleName = Constants.RoleName_Administrators, - }; + var portalSettings = new PortalSettings + { + AdministratorRoleName = Constants.RoleName_Administrators, + }; this._portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); } @@ -189,23 +206,6 @@ private void SetupFileControllers() this._fileManager.Setup(f => f.GetFile(It.IsAny())).Returns(new FileInfo()); this._folderPermissionController.Setup(f => f.CanViewFolder(It.IsAny())).Returns(true); } - - [Test] - public void MessagingController_Constructor_Throws_On_Null_DataService() - { - // Arrange - - // Act, Assert - Assert.Throws(() => new MessagingController(null)); - } - - [Test] - public void AttachmentsAllowed_Returns_True_When_MessagingAllowAttachments_Setting_Is_YES() - { - this._mockMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("YES"); - var result = this._mockInternalMessagingController.Object.AttachmentsAllowed(Constants.CONTENT_ValidPortalId); - Assert.IsTrue(result); - } [Test] public void IncludeAttachments_Returns_True_When_MessagingIncludeAttachments_Setting_Is_YES() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs index a2a01d46ede..c463bfc183d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs @@ -76,12 +76,6 @@ public void SetUp() this.SetupDataTables(); } - private void SetupDataProvider() - { - // Standard DataProvider Path for Logging - this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - } - [TearDown] public void TearDown() { @@ -98,6 +92,12 @@ public void CreateNotificationType_Throws_On_Null_NotificationType() this._notificationsController.CreateNotificationType(null); } + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + } + [Test] [TestCase("")] [TestCase(null)] @@ -327,17 +327,17 @@ public void SetNotificationTypeActions_Throws_On_Null_Or_Empty_APICall(string ap [Test] public void SetNotificationTypeActions_Calls_DataService_AddNotificationTypeAction_For_Each_Of_Two_Actions() { - this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); - -// _mockDataService -// .Setup(ds => ds.AddNotificationTypeAction( -// Constants.Messaging_NotificationTypeId, -// Constants.Messaging_NotificationTypeActionNameResourceKey, -// Constants.Messaging_NotificationTypeActionDescriptionResourceKey, -// Constants.Messaging_NotificationTypeActionConfirmResourceKey, -// Constants.Messaging_NotificationTypeActionAPICall, -// Constants.UserID_User12)) -// .Verifiable(); + this._mockNotificationsController.Setup(nc => nc.GetCurrentUserId()).Returns(Constants.UserID_User12); + + // _mockDataService + // .Setup(ds => ds.AddNotificationTypeAction( + // Constants.Messaging_NotificationTypeId, + // Constants.Messaging_NotificationTypeActionNameResourceKey, + // Constants.Messaging_NotificationTypeActionDescriptionResourceKey, + // Constants.Messaging_NotificationTypeActionConfirmResourceKey, + // Constants.Messaging_NotificationTypeActionAPICall, + // Constants.UserID_User12)) + // .Verifiable(); this._mockNotificationsController.Setup(nc => nc.GetNotificationTypeAction(It.IsAny())); this._mockNotificationsController.Object.SetNotificationTypeActions( @@ -680,12 +680,12 @@ public void SendNotification_Throws_On_Large_To_List() [Test] public void SendNotification_Calls_DataService_On_Valid_Notification() { - var adminUser = new UserInfo - { - UserID = Constants.UserID_Admin, - DisplayName = Constants.UserDisplayName_Admin, - PortalID = Constants.PORTAL_Zero, - }; + var adminUser = new UserInfo + { + UserID = Constants.UserID_Admin, + DisplayName = Constants.UserDisplayName_Admin, + PortalID = Constants.PORTAL_Zero, + }; this._mockInternalMessagingController.Setup(mc => mc.RecipientLimit(adminUser.PortalID)).Returns(10); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); @@ -1090,17 +1090,17 @@ public void DeleteAllNotificationRecipients_Does_Not_Call_DeleteNotificationReci private static Notification CreateUnsavedNotification() { - return new Notification - { - NotificationTypeID = Constants.Messaging_NotificationTypeId, - Subject = Constants.Messaging_NotificationSubject, - Body = Constants.Messaging_NotificationBody, - To = Constants.UserDisplayName_User12, - From = Constants.UserDisplayName_Admin, - SenderUserID = Constants.UserID_Admin, - Context = Constants.Messaging_NotificationContext, - SendToast = false, - }; + return new Notification + { + NotificationTypeID = Constants.Messaging_NotificationTypeId, + Subject = Constants.Messaging_NotificationSubject, + Body = Constants.Messaging_NotificationBody, + To = Constants.UserDisplayName_User12, + From = Constants.UserDisplayName_Admin, + SenderUserID = Constants.UserID_Admin, + Context = Constants.Messaging_NotificationContext, + SendToast = false, + }; } private static Notification CreateValidNotification() @@ -1142,13 +1142,13 @@ private static NotificationTypeAction CreateValidNotificationTypeAction() private static NotificationTypeAction CreateNewNotificationTypeAction() { - return new NotificationTypeAction - { - APICall = Constants.Messaging_NotificationTypeActionAPICall, - ConfirmResourceKey = Constants.Messaging_NotificationTypeActionConfirmResourceKey, - DescriptionResourceKey = Constants.Messaging_NotificationTypeActionDescriptionResourceKey, - NameResourceKey = Constants.Messaging_NotificationTypeActionNameResourceKey, - }; + return new NotificationTypeAction + { + APICall = Constants.Messaging_NotificationTypeActionAPICall, + ConfirmResourceKey = Constants.Messaging_NotificationTypeActionConfirmResourceKey, + DescriptionResourceKey = Constants.Messaging_NotificationTypeActionDescriptionResourceKey, + NameResourceKey = Constants.Messaging_NotificationTypeActionNameResourceKey, + }; } private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs index eccdf729f21..96e2ce0974e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs @@ -20,12 +20,12 @@ namespace DotNetNuke.Tests.Core.Controllers.Messaging [TestFixture] public class SubscriptionTypeControllerTests { + private const string SubscriptionTypesCacheKey = "DNN_" + DataCache.SubscriptionTypesCacheKey; + private SubscriptionTypeController subscriptionTypeController; private Mock mockDataService; private Mock mockCacheProvider; - private const string SubscriptionTypesCacheKey = "DNN_" + DataCache.SubscriptionTypesCacheKey; - [SetUp] public void SetUp() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs index 81b08bfcffd..6f554a11169 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs @@ -16,14 +16,22 @@ namespace DotNetNuke.Tests.Core.Controllers.Portal [TestFixture] public class PortalControllerTests { - private Mock _mockPortalTemplateIO; private const string HostMapPath = @"C:\path"; - private const string DefaultName = "Default"; - private static readonly string DefaultPath = MakePath(DefaultName); - private static readonly string DefaultDePath = MakePath(DefaultName, "de-DE"); + + private Mock _mockPortalTemplateIO; private const string DefaultDeName = "Rückstellungs-Web site"; private const string DefaultDeDescription = "A new german description"; + private static readonly string DefaultPath = MakePath(DefaultName); + private static readonly string DefaultDePath = MakePath(DefaultName, "de-DE"); + private const string StaticName = "Static"; + + private const string StaticDescription = "An description from a template file"; + private const string AlternateName = "Alternate"; + + private const string AlternateDeName = "Alternate in German"; + private const string ResourceName = "Resource"; + private static readonly Dictionary DefaultExpectationsDe = new Dictionary { { "Name", DefaultDeName }, @@ -41,11 +49,8 @@ public class PortalControllerTests { "LanguageFilePath", DefaultUsPath }, { "CultureCode", "en-US" }, }; - - private const string StaticName = "Static"; private static readonly string CultureCode = Thread.CurrentThread.CurrentCulture.Name; private static readonly string StaticPath = MakePath(StaticName); - private const string StaticDescription = "An description from a template file"; private static readonly Dictionary StaticExpectations = new Dictionary { { "Name", StaticName }, @@ -53,11 +58,8 @@ public class PortalControllerTests { "Description", StaticDescription }, { "CultureCode", CultureCode }, }; - - private const string AlternateName = "Alternate"; private static readonly string AlternatePath = MakePath(AlternateName); private static readonly string AlternateDePath = MakePath(AlternateName, "de-DE"); - private const string AlternateDeName = "Alternate in German"; private static readonly Dictionary AlternateExpectationsDe = new Dictionary { { "Name", AlternateDeName }, @@ -65,8 +67,6 @@ public class PortalControllerTests { "LanguageFilePath", AlternateDePath }, { "CultureCode", "de-DE" }, }; - - private const string ResourceName = "Resource"; private static readonly string ResourcePath = MakePath(ResourceName); private static readonly string ResourceFilePath = ResourcePath + ".resources"; private static readonly Dictionary ResourceExpectations = new Dictionary @@ -251,28 +251,6 @@ public void GetPortalTemplateCanReturnAStaticTemplate() AssertTemplateInfo(StaticExpectations, template); } - private TextReader CreateLanguageFileReader(string name) - { - return this.CreateLanguageFileReader(name, null); - } - - private TextReader CreateLanguageFileReader(string name, string description) - { - if (description != null) - { - description = string.Format("{0}", description); - } - - var xml = string.Format("{0}{1}", name, description); - return new StringReader(xml); - } - - private TextReader CreateTemplateFileReader(string description) - { - var xml = string.Format("{0}", description); - return new StringReader(xml); - } - private static void AssertTemplateInfo(Dictionary expectations, PortalController.PortalTemplateInfo templateInfo) { AssertTemplateField(expectations, "Name", templateInfo.Name); @@ -297,9 +275,26 @@ private static void AssertTemplateField(Dictionary expectations, } } - private IEnumerable ToEnumerable(params T[] input) + private TextReader CreateLanguageFileReader(string name) { - return input; + return this.CreateLanguageFileReader(name, null); + } + + private TextReader CreateLanguageFileReader(string name, string description) + { + if (description != null) + { + description = string.Format("{0}", description); + } + + var xml = string.Format("{0}{1}", name, description); + return new StringReader(xml); + } + + private TextReader CreateTemplateFileReader(string description) + { + var xml = string.Format("{0}", description); + return new StringReader(xml); } private static string MakePath(string name) @@ -312,5 +307,10 @@ private static string MakePath(string name, string culture) { return string.Format(@"{0}.{1}.resx", MakePath(name), culture); } + + private IEnumerable ToEnumerable(params T[] input) + { + return input; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs index 7c707f83daf..2828e16f7af 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs @@ -483,12 +483,12 @@ private static string GetDescription(int i) private static PortalGroupInfo CreateValidPortalGroup() { - var portalGroup = new PortalGroupInfo - { - PortalGroupName = Constants.PORTALGROUP_ValidName, - PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, - MasterPortalId = Constants.PORTAL_ValidPortalId, - }; + var portalGroup = new PortalGroupInfo + { + PortalGroupName = Constants.PORTALGROUP_ValidName, + PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, + MasterPortalId = Constants.PORTAL_ValidPortalId, + }; return portalGroup; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs index 8cec4a57280..288665d2fb4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs @@ -21,8 +21,8 @@ public override bool HasViewPermission(SearchResult searchResult) // Returns the URL to the first instance of the module the user has access to view public override string GetDocUrl(SearchResult searchResult) - { - return "http://www.google.com"; + { + return "http://www.google.com"; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs index 0e9c18e33a6..bb227586b68 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs @@ -28,6 +28,10 @@ namespace DotNetNuke.Tests.Core.Controllers.Search [TestFixture] public class InternalSearchControllerTests { + private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; + private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; + private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; + public enum SearchTypeIds { ModuleSearchTypeId = 1, @@ -37,10 +41,6 @@ public enum SearchTypeIds OtherSearchTypeId, UnknownSearchTypeId, } - - private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; - private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; - private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; @@ -126,6 +126,24 @@ public void TearDown() this._luceneController = null; } + [Test] + public void SearchController_Add_Throws_On_Null_SearchDocument() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this._internalSearchController.AddSearchDocument(null)); + } + + [Test] + public void SearchController_Add_Throws_On_Null_Or_Empty_UniqueuKey() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this._internalSearchController.AddSearchDocument(new SearchDocument())); + } + private void CreateNewLuceneControllerInstance() { this.DeleteIndexFolder(); @@ -347,24 +365,6 @@ private void DeleteIndexFolder() Console.WriteLine(ex); } } - - [Test] - public void SearchController_Add_Throws_On_Null_SearchDocument() - { - // Arrange - - // Act, Assert - Assert.Throws(() => this._internalSearchController.AddSearchDocument(null)); - } - - [Test] - public void SearchController_Add_Throws_On_Null_Or_Empty_UniqueuKey() - { - // Arrange - - // Act, Assert - Assert.Throws(() => this._internalSearchController.AddSearchDocument(new SearchDocument())); - } [Test] public void SearchController_Add_Throws_On_Null_OrEmpty_Title() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs index fb1aee2834f..0e8ea3fd40f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs @@ -32,9 +32,9 @@ namespace DotNetNuke.Tests.Core.Controllers.Search [TestFixture] public class LuceneControllerTests { - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private const string SearchIndexFolder = @"App_Data\LuceneTests"; private const string WriteLockFile = "write.lock"; + private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private const string Line1 = "the quick brown fox jumps over the lazy dog"; private const string Line2 = "the quick gold fox jumped over the lazy black dog"; private const string Line3 = "the quick fox jumps over the black dog"; @@ -49,6 +49,10 @@ public class LuceneControllerTests private const string ValidCustomAnalyzer = "Lucene.Net.Analysis.Cn.ChineseAnalyzer, Lucene.Net.Contrib.Analyzers"; private const int DefaultSearchRetryTimes = 5; + // Arrange + private const int TotalTestDocs2Create = 5; + private const string ContentFieldName = "content"; + private Mock _mockHostController; private LuceneControllerImpl _luceneController; private Mock _cachingProvider; @@ -90,6 +94,23 @@ public void TearDown() SearchHelper.ClearInstance(); } + [Test] + public void LuceneController_SearchFolderIsAsExpected() + { + var inf1 = new DirectoryInfo(SearchIndexFolder); + var inf2 = new DirectoryInfo(this._luceneController.IndexFolder); + Assert.AreEqual(inf1.FullName, inf2.FullName); + } + + [Test] + public void LuceneController_Add_Throws_On_Null_Document() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this._luceneController.Add(null)); + } + private void CreateNewLuceneControllerInstance() { if (this._luceneController != null) @@ -142,33 +163,16 @@ private void AddStandardDocs() } private void AddLinesAsSearchDocs(IEnumerable lines) - { - foreach (var line in lines) - { - var field = new Field(Constants.ContentTag, line, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); - var doc = new Document(); - doc.Add(field); - this._luceneController.Add(doc); - } - - this._luceneController.Commit(); - } - - [Test] - public void LuceneController_SearchFolderIsAsExpected() - { - var inf1 = new DirectoryInfo(SearchIndexFolder); - var inf2 = new DirectoryInfo(this._luceneController.IndexFolder); - Assert.AreEqual(inf1.FullName, inf2.FullName); - } - - [Test] - public void LuceneController_Add_Throws_On_Null_Document() { - // Arrange + foreach (var line in lines) + { + var field = new Field(Constants.ContentTag, line, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); + var doc = new Document(); + doc.Add(field); + this._luceneController.Add(doc); + } - // Act, Assert - Assert.Throws(() => this._luceneController.Add(null)); + this._luceneController.Commit(); } public void LuceneController_Add_Throws_On_Null_Query() @@ -323,10 +327,10 @@ public void LuceneController_Search_Request_For_NonExisting_PageNumbers_Returns_ var hits = this._luceneController.Search(this.CreateSearchContext( new LuceneQuery { - Query = new TermQuery(new Term(Constants.ContentTag, "fox")), - PageIndex = 5, - PageSize = 10, - })); + Query = new TermQuery(new Term(Constants.ContentTag, "fox")), + PageIndex = 5, + PageSize = 10, + })); // Assert Assert.AreEqual(4, hits.TotalHits); @@ -340,9 +344,11 @@ public void LuceneController_Search_Request_For_PagIndex2_PageSize1_Returns_2nd_ this.AddStandardDocs(); var query = new LuceneQuery - { - Query = new TermQuery(new Term(Constants.ContentTag, "quick")), PageIndex = 2, PageSize = 1, - }; + { + Query = new TermQuery(new Term(Constants.ContentTag, "quick")), + PageIndex = 2, + PageSize = 1, + }; var hits = this._luceneController.Search(this.CreateSearchContext(query)); @@ -692,9 +698,26 @@ public void LuceneController_LockFileCanBeObtainedByOnlySingleController() Assert.Throws(() => secondController.Add(doc1)); } - // Arrange - private const int TotalTestDocs2Create = 5; - private const string ContentFieldName = "content"; + [Test] + public void LuceneController_DocumentMaxAndCountAreCorrect() + { + this.AddTestDocs(); + + Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); + Assert.AreEqual(TotalTestDocs2Create, this._luceneController.SearchbleDocsCount()); + } + + [Test] + public void LuceneController_TestDeleteBeforeOptimize() + { + // Arrange + this.AddTestDocs(); + var delCount = this.DeleteTestDocs(); + + Assert.IsTrue(this._luceneController.HasDeletions()); + Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); + Assert.AreEqual(TotalTestDocs2Create - delCount, this._luceneController.SearchbleDocsCount()); + } private int AddTestDocs() { @@ -728,27 +751,6 @@ private int DeleteTestDocs() return delCount; } - [Test] - public void LuceneController_DocumentMaxAndCountAreCorrect() - { - this.AddTestDocs(); - - Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); - Assert.AreEqual(TotalTestDocs2Create, this._luceneController.SearchbleDocsCount()); - } - - [Test] - public void LuceneController_TestDeleteBeforeOptimize() - { - // Arrange - this.AddTestDocs(); - var delCount = this.DeleteTestDocs(); - - Assert.IsTrue(this._luceneController.HasDeletions()); - Assert.AreEqual(TotalTestDocs2Create, this._luceneController.MaxDocsCount()); - Assert.AreEqual(TotalTestDocs2Create - delCount, this._luceneController.SearchbleDocsCount()); - } - [Test] public void LuceneController_TestDeleteAfterOptimize() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs index a1c783070b0..366b311530f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs @@ -33,6 +33,10 @@ namespace DotNetNuke.Tests.Core.Controllers.Search [TestFixture] public class SearchControllerTests { + private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; + private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; + private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; + public enum SearchTypeIds { ModuleSearchTypeId = 1, @@ -42,10 +46,6 @@ public enum SearchTypeIds OtherSearchTypeId, UnknownSearchTypeId, } - - private const int ModuleSearchTypeId = (int)SearchTypeIds.ModuleSearchTypeId; - private const int TabSearchTypeId = (int)SearchTypeIds.TabSearchTypeId; - private const int DocumentSearchTypeId = (int)SearchTypeIds.DocumentSearchTypeId; private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; @@ -120,8 +120,8 @@ public enum SearchTypeIds private const int CustomBoost = 80; private const string SearchIndexFolder = @"App_Data\SearchTests"; - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private const int DefaultSearchRetryTimes = 5; + private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private Mock _mockHostController; private Mock _mockCachingProvider; private Mock _mockDataProvider; @@ -170,6 +170,86 @@ public void TearDown() this._luceneController = null; } + [Test] + public void SearchController_Search_Throws_On_Null_Query() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this._searchController.SiteSearch(null)); + } + + [Test] + public void SearchController_Search_Throws_On_Empty_TypeId_Collection() + { + // Arrange + + // Act, Assert + Assert.Throws(() => this._searchController.SiteSearch(new SearchQuery { KeyWords = "word" })); + } + + /// + /// Executes function proc on a separate thread respecting the given timeout value. + /// + /// + /// The function to execute. + /// The timeout duration. + /// R. + /// From: http://stackoverflow.com/questions/9460661/implementing-regex-timeout-in-net-4. + private static R ExecuteWithTimeout(Func proc, TimeSpan timeout) + { + var r = default(R); // init default return value + Exception ex = null; // records inter-thread exception + + // define a thread to wrap 'proc' + var t = new Thread(() => + { + try + { + r = proc(); + } + catch (Exception e) + { + // this can get set to ThreadAbortException + ex = e; + + Console.WriteLine("Exception hit"); + } + }); + + t.Start(); // start running 'proc' thread wrapper + + // from docs: "The Start method does not return until the new thread has started running." + if (t.Join(timeout) == false) + { + t.Abort(); // die evil thread! + + // Abort raises the ThreadAbortException + int i = 0; + while ((t.Join(1) == false) && (i < 20)) + { + // 20 ms wait possible here + i++; + } + + if (i >= 20) + { + // we didn't abort, might want to log this or take some other action + // this can happen if you are doing something indefinitely hinky in a + // finally block (cause the finally be will executed before the Abort + // completes. + Console.WriteLine("Abort didn't work as expected"); + } + } + + if (ex != null) + { + throw ex; // oops + } + + return r; // ah! + } + private void CreateNewLuceneControllerInstance(bool reCreate = false) { InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); @@ -466,8 +546,8 @@ private int AddSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) } private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) - { - var doc1 = new SearchDocument + { + var doc1 = new SearchDocument { Title = "Title", UniqueKey = "key1", @@ -476,8 +556,8 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue50 } }, - }; - var doc2 = new SearchDocument + }; + var doc2 = new SearchDocument { Title = "Title", UniqueKey = "key2", @@ -485,8 +565,8 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue100 } }, - }; - var doc3 = new SearchDocument + }; + var doc3 = new SearchDocument { Title = "Title", UniqueKey = "key3", @@ -494,8 +574,8 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue200 } }, - }; - var doc4 = new SearchDocument + }; + var doc4 = new SearchDocument { Title = "Title", UniqueKey = "key4", @@ -503,8 +583,8 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue500 } }, - }; - var doc5 = new SearchDocument + }; + var doc5 = new SearchDocument { Title = "Title", UniqueKey = "key5", @@ -512,13 +592,13 @@ private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) ModifiedTimeUtc = DateTime.UtcNow, PortalId = PortalId12, NumericKeys = new Dictionary() { { NumericKey1, NumericValue1000 } }, - }; - - var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; - - this._internalSearchController.AddSearchDocuments(docs); - - return docs.Count; + }; + + var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; + + this._internalSearchController.AddSearchDocuments(docs); + + return docs.Count; } private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) @@ -577,18 +657,18 @@ private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) return docs.Count; } - private int AddDocuments(IList titles, string body, int searchTypeId = OtherSearchTypeId) + private int AddDocuments(IList titles, string body, int searchTypeId = OtherSearchTypeId) { var count = 0; - foreach (var doc in titles.Select(title => new SearchDocument - { - Title = title, - UniqueKey = Guid.NewGuid().ToString(), - Body = body, - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - })) + foreach (var doc in titles.Select(title => new SearchDocument + { + Title = title, + UniqueKey = Guid.NewGuid().ToString(), + Body = body, + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + })) { this._internalSearchController.AddSearchDocument(doc); count++; @@ -656,86 +736,6 @@ private string StipEllipses(string text) return text.Replace("...", string.Empty).Trim(); } - /// - /// Executes function proc on a separate thread respecting the given timeout value. - /// - /// - /// The function to execute. - /// The timeout duration. - /// R. - /// From: http://stackoverflow.com/questions/9460661/implementing-regex-timeout-in-net-4. - private static R ExecuteWithTimeout(Func proc, TimeSpan timeout) - { - var r = default(R); // init default return value - Exception ex = null; // records inter-thread exception - - // define a thread to wrap 'proc' - var t = new Thread(() => - { - try - { - r = proc(); - } - catch (Exception e) - { - // this can get set to ThreadAbortException - ex = e; - - Console.WriteLine("Exception hit"); - } - }); - - t.Start(); // start running 'proc' thread wrapper - - // from docs: "The Start method does not return until the new thread has started running." - if (t.Join(timeout) == false) - { - t.Abort(); // die evil thread! - - // Abort raises the ThreadAbortException - int i = 0; - while ((t.Join(1) == false) && (i < 20)) - { - // 20 ms wait possible here - i++; - } - - if (i >= 20) - { - // we didn't abort, might want to log this or take some other action - // this can happen if you are doing something indefinitely hinky in a - // finally block (cause the finally be will executed before the Abort - // completes. - Console.WriteLine("Abort didn't work as expected"); - } - } - - if (ex != null) - { - throw ex; // oops - } - - return r; // ah! - } - - [Test] - public void SearchController_Search_Throws_On_Null_Query() - { - // Arrange - - // Act, Assert - Assert.Throws(() => this._searchController.SiteSearch(null)); - } - - [Test] - public void SearchController_Search_Throws_On_Empty_TypeId_Collection() - { - // Arrange - - // Act, Assert - Assert.Throws(() => this._searchController.SiteSearch(new SearchQuery { KeyWords = "word" })); - } - [Test] public void SearchController_AddSearchDcoumet_Regex_Does_Not_Sleep_On_Bad_Text_During_Alt_Text_Parsing() { @@ -934,30 +934,6 @@ public void SearchController_SecurityTrimmedTest_ReturnsNoResultsWhenHavingNoPer Assert.AreEqual(0, result.Results.Count); } - /// - /// Sets up some data for testing security trimming. - /// In the tests below, the users will have access to the follwoing documents - /// { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29, ..., etc. } - /// The tests check that pagination qith various page sizes returns the proper groupings. - /// - private void SetupSecurityTrimmingDocs(int totalDocs, int searchType = DocumentSearchTypeId) - { - var docModifyTime = DateTime.UtcNow - TimeSpan.FromSeconds(totalDocs); - for (var i = 0; i < totalDocs; i++) - { - this._internalSearchController.AddSearchDocument(new SearchDocument - { - AuthorUserId = i, - Title = "Fox and Dog", - Body = Line1, - Tags = new[] { Tag0, Tag1 }, - SearchTypeId = searchType, - UniqueKey = Guid.NewGuid().ToString(), - ModifiedTimeUtc = docModifyTime.AddSeconds(i), - }); - } - } - [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1A() { @@ -1010,6 +986,30 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1B Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17 }, ids); } + /// + /// Sets up some data for testing security trimming. + /// In the tests below, the users will have access to the follwoing documents + /// { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29, ..., etc. } + /// The tests check that pagination qith various page sizes returns the proper groupings. + /// + private void SetupSecurityTrimmingDocs(int totalDocs, int searchType = DocumentSearchTypeId) + { + var docModifyTime = DateTime.UtcNow - TimeSpan.FromSeconds(totalDocs); + for (var i = 0; i < totalDocs; i++) + { + this._internalSearchController.AddSearchDocument(new SearchDocument + { + AuthorUserId = i, + Title = "Fox and Dog", + Body = Line1, + Tags = new[] { Tag0, Tag1 }, + SearchTypeId = searchType, + UniqueKey = Guid.NewGuid().ToString(), + ModifiedTimeUtc = docModifyTime.AddSeconds(i), + }); + } + } + [Test] public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1C() { @@ -1664,8 +1664,8 @@ public void SearchController_GetResult_Throws_When_CustomNumericField_Is_Specifi SortField = SortFields.CustomNumericField, }; - this._searchController.SiteSearch(query); - } + this._searchController.SiteSearch(query); + } [Test] [ExpectedException(typeof(ArgumentException))] @@ -1716,11 +1716,11 @@ public void SearchController_GetResult_Sorty_By_Date_Returns_Latest_Docs_First() var added = this.AddStandardSearchDocs(); // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.LastModified, - }; + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.LastModified, + }; var search = this._searchController.SiteSearch(query); // Assert @@ -1829,8 +1829,8 @@ public void SearchController_GetResult_Sorty_By_Title_Ascending_Returns_Alphabet foreach (var title in titles.OrderBy(s => s)) { Assert.AreEqual(title, search.Results[count++].Title); - } - } + } + } [Test] public void SearchController_GetResult_Sorty_By_Title_Descending_Returns_Alphabetic_Descending() @@ -1990,12 +1990,12 @@ public void SearchController_GetResult_Sorty_By_Relevance_Returns_TopHit_Docs_Fi var added = this.AddStandardSearchDocs(); // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.Relevance, - KeyWords = "brown OR fox", - }; + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.Relevance, + KeyWords = "brown OR fox", + }; var search = this._searchController.SiteSearch(query); // Assert @@ -2123,12 +2123,12 @@ public void SearchController_GetResult_By_Locale_Returns_Specific_And_Neutral_Lo this.AddStandardSearchDocs(); // Act - var query = new SearchQuery - { - SearchTypeIds = new List { ModuleSearchTypeId }, - SortField = SortFields.LastModified, - CultureCode = CultureItIt, - }; + var query = new SearchQuery + { + SearchTypeIds = new List { ModuleSearchTypeId }, + SortField = SortFields.LastModified, + CultureCode = CultureItIt, + }; var search = this._searchController.SiteSearch(query); // Assert @@ -2472,38 +2472,6 @@ public void SearchController_Full_FileNameTest_With_WildCard() Assert.AreEqual(1, result.TotalHits); Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); } - - private void AddFoldersAndFiles() - { - var allFiles = new Dictionary - { - { "Awesome-Cycles-Logo.png", "Images/" }, - { "Banner1.jpg", "Images/" }, - { "Banner2.jpg", "Images/" }, - { "bike-powered.png", "Images/DNN/" }, - { "Spacer.gif", "Images/DNN/" }, - { "monday.png", "My { { "folderName", file.Value.ToLowerInvariant() } }, - }; - this._internalSearchController.AddSearchDocument(doc); - } - - this._internalSearchController.Commit(); - } [Test] public void SearchController_Scope_By_FolderName() @@ -2542,6 +2510,38 @@ public void SearchController_Scope_By_FolderName_With_Spaces() Assert.AreEqual(2, result3.TotalHits); } + private void AddFoldersAndFiles() + { + var allFiles = new Dictionary + { + { "Awesome-Cycles-Logo.png", "Images/" }, + { "Banner1.jpg", "Images/" }, + { "Banner2.jpg", "Images/" }, + { "bike-powered.png", "Images/DNN/" }, + { "Spacer.gif", "Images/DNN/" }, + { "monday.png", "My { { "folderName", file.Value.ToLowerInvariant() } }, + }; + this._internalSearchController.AddSearchDocument(doc); + } + + this._internalSearchController.Commit(); + } + [Test] public void SearchController_EmailTest_With_WildCard() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs index 4816389a028..35e21b0e764 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs @@ -48,6 +48,33 @@ public void SetUp() DataCache.ClearCache(); } + [Test] + public void SearchHelper_GetSynonyms_Two_Terms_Returns_Correct_Results() + { + // Arrange + + // Act + var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermDNN).ToArray(); + + // Assert + Assert.AreEqual(1, synonyms.Count()); + Assert.AreEqual(TermDotNetNuke.ToLowerInvariant(), synonyms[0]); + } + + [Test] + public void SearchHelper_GetSynonyms_Three_Terms_Returns_Correct_Results() + { + // Arrange + + // Act + var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermHop).ToArray(); + + // Assert + Assert.AreEqual(2, synonyms.Count()); + Assert.AreEqual(TermJump.ToLowerInvariant(), synonyms[0]); + Assert.AreEqual(TermLeap.ToLowerInvariant(), synonyms[1]); + } + private void SetupDataProvider() { // Standard DataProvider Path for Logging @@ -124,33 +151,6 @@ private IDataReader GetPortalCallBack(int portalId, string culture) return table.CreateDataReader(); } - [Test] - public void SearchHelper_GetSynonyms_Two_Terms_Returns_Correct_Results() - { - // Arrange - - // Act - var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermDNN).ToArray(); - - // Assert - Assert.AreEqual(1, synonyms.Count()); - Assert.AreEqual(TermDotNetNuke.ToLowerInvariant(), synonyms[0]); - } - - [Test] - public void SearchHelper_GetSynonyms_Three_Terms_Returns_Correct_Results() - { - // Arrange - - // Act - var synonyms = this._searchHelper.GetSynonyms(PortalId0, CultureEnUs, TermHop).ToArray(); - - // Assert - Assert.AreEqual(2, synonyms.Count()); - Assert.AreEqual(TermJump.ToLowerInvariant(), synonyms[0]); - Assert.AreEqual(TermLeap.ToLowerInvariant(), synonyms[1]); - } - [Test] public void SearchHelper_Rephrase_NoWildCardButExact_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 e4257d68ed0..4e314d843a5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs @@ -113,10 +113,10 @@ public void RelationshipController_DeleteRelationshipType_Calls_DataService() // Arrange var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); var relationshipController = this.CreateRelationshipController(mockDataService); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; // Act relationshipController.DeleteRelationshipType(relationshipType); @@ -133,11 +133,11 @@ public void RelationshipController_DeleteRelationshipType_Calls_EventLogControll mockEventLogController.Setup(c => c.AddLog(It.IsAny(), It.IsAny(), It.IsAny())); this.CreateLocalizationProvider(); var relationshipController = this.CreateRelationshipController(mockEventLogController); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - Name = Constants.SOCIAL_RelationshipTypeName, - }; + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + Name = Constants.SOCIAL_RelationshipTypeName, + }; // Act relationshipController.DeleteRelationshipType(relationshipType); @@ -153,10 +153,10 @@ public void RelationshipController_DeleteRelationshipType_Calls_DataCache_Remove // Arrange var relationshipController = this.CreateRelationshipController(); var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; // Act relationshipController.DeleteRelationshipType(relationshipType); @@ -240,10 +240,10 @@ public void RelationshipController_SaveRelationshipType_Calls_DataService() // Arrange var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); var relationshipController = this.CreateRelationshipController(mockDataService); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; // Act relationshipController.SaveRelationshipType(relationshipType); @@ -261,11 +261,11 @@ public void RelationshipController_SaveRelationshipType_Calls_EventLogController this.CreateLocalizationProvider(); var relationshipController = this.CreateRelationshipController(mockEventLogController); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - Name = Constants.SOCIAL_RelationshipTypeName, - }; + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + Name = Constants.SOCIAL_RelationshipTypeName, + }; // Act relationshipController.SaveRelationshipType(relationshipType); @@ -281,10 +281,10 @@ public void RelationshipController_SaveRelationshipType_Calls_DataCache_RemoveCa // Arrange var relationshipController = this.CreateRelationshipController(); var cacheKey = CachingProvider.GetCacheKey(DataCache.RelationshipTypesCacheKey); - var relationshipType = new RelationshipType() - { - RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, - }; + var relationshipType = new RelationshipType() + { + RelationshipTypeId = Constants.SOCIAL_FollowerRelationshipTypeID, + }; // Act relationshipController.SaveRelationshipType(relationshipType); @@ -310,10 +310,10 @@ public void RelationshipController_DeleteRelationship_Calls_DataService() // Arrange var mockDataService = new Mock(); var relationshipController = this.CreateRelationshipController(mockDataService); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - }; + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + }; // Act relationshipController.DeleteRelationship(relationship); @@ -331,11 +331,11 @@ public void RelationshipController_DeleteRelationship_Calls_EventLogController_A this.CreateLocalizationProvider(); var relationshipController = this.CreateRelationshipController(mockEventLogController); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - Name = Constants.SOCIAL_RelationshipName, - }; + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + Name = Constants.SOCIAL_RelationshipName, + }; // Act relationshipController.DeleteRelationship(relationship); @@ -352,12 +352,12 @@ public void RelationshipController_DeleteRelationship_Calls_DataCache_RemoveCach var portalId = 1; var relationshipController = this.CreateRelationshipController(); var cacheKey = CachingProvider.GetCacheKey(string.Format(DataCache.RelationshipByPortalIDCacheKey, portalId)); - var relationship = new Relationship() - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - PortalId = portalId, - UserId = -1, - }; + var relationship = new Relationship() + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + PortalId = portalId, + UserId = -1, + }; // Act relationshipController.DeleteRelationship(relationship); @@ -542,10 +542,10 @@ public void RelationshipController_SaveRelationship_Calls_DataService() // Arrange var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); var relationshipController = this.CreateRelationshipController(mockDataService); - var relationship = new Relationship - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - }; + var relationship = new Relationship + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + }; // Act relationshipController.SaveRelationship(relationship); @@ -563,11 +563,11 @@ public void RelationshipController_SaveRelationship_Calls_EventLogController_Add this.CreateLocalizationProvider(); var relationshipController = this.CreateRelationshipController(mockEventLogController); - var relationship = new Relationship - { - RelationshipId = Constants.SOCIAL_FollowerRelationshipID, - Name = Constants.SOCIAL_RelationshipName, - }; + var relationship = new Relationship + { + RelationshipId = Constants.SOCIAL_FollowerRelationshipID, + Name = Constants.SOCIAL_RelationshipName, + }; // Act relationshipController.SaveRelationship(relationship); @@ -612,10 +612,10 @@ public void RelationshipController_DeleteUserRelationship_Calls_DataService() // Arrange var mockDataService = this.CreateMockDataServiceWithRelationshipTypes(); var relationshipController = this.CreateRelationshipController(mockDataService); - var userRelationship = new UserRelationship() - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - }; + var userRelationship = new UserRelationship() + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + }; // Act relationshipController.DeleteUserRelationship(userRelationship); @@ -633,12 +633,12 @@ public void RelationshipController_DeleteUserRelationship_Calls_EventLogControll this.CreateLocalizationProvider(); var relationshipController = this.CreateRelationshipController(mockEventLogController); - var userRelationship = new UserRelationship - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - UserId = Constants.USER_ElevenId, - RelatedUserId = Constants.USER_TenId, - }; + var userRelationship = new UserRelationship + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + UserId = Constants.USER_ElevenId, + RelatedUserId = Constants.USER_TenId, + }; // Act relationshipController.DeleteUserRelationship(userRelationship); @@ -743,10 +743,10 @@ public void RelationshipController_SaveUserRelationship_Calls_DataService() // Arrange var mockDataService = new Mock(); var relationshipController = this.CreateRelationshipController(mockDataService); - var userRelationship = new UserRelationship() - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - }; + var userRelationship = new UserRelationship() + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + }; // Act relationshipController.SaveUserRelationship(userRelationship); @@ -767,12 +767,12 @@ public void RelationshipController_SaveUserRelationship_Calls_EventLogController this.CreateLocalizationProvider(); var relationshipController = new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); - var userRelationship = new UserRelationship - { - UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, - UserId = Constants.USER_ElevenId, - RelatedUserId = Constants.USER_TenId, - }; + var userRelationship = new UserRelationship + { + UserRelationshipId = Constants.SOCIAL_UserRelationshipIDUser10User11, + UserId = Constants.USER_ElevenId, + RelatedUserId = Constants.USER_TenId, + }; // Act relationshipController.SaveUserRelationship(userRelationship); @@ -799,10 +799,10 @@ public void RelationshipController_DeleteUserRelationshipPreference_Calls_DataSe // Arrange var mockDataService = new Mock(); var relationshipController = this.CreateRelationshipController(mockDataService); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - }; + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + }; // Act relationshipController.DeleteUserRelationshipPreference(preference); @@ -820,12 +820,12 @@ public void RelationshipController_DeleteUserRelationshipPreference_Calls_EventL this.CreateLocalizationProvider(); var relationshipController = this.CreateRelationshipController(mockEventLogController); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID, - }; + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; // Act relationshipController.DeleteUserRelationshipPreference(preference); @@ -884,12 +884,12 @@ public void RelationshipController_SaveUserRelationshipPreference_Calls_DataServ // Arrange var mockDataService = new Mock(); var relationshipController = this.CreateRelationshipController(mockDataService); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID, - }; + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; // Act relationshipController.SaveUserRelationshipPreference(preference); @@ -910,12 +910,12 @@ public void RelationshipController_SaveUserRelationshipPreference_Calls_EventLog this.CreateLocalizationProvider(); var relationshipController = new RelationshipControllerImpl(mockDataService.Object, mockEventLogController.Object); - var preference = new UserRelationshipPreference() - { - PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, - UserId = Constants.USER_ElevenId, - RelationshipId = Constants.SOCIAL_FriendRelationshipID, - }; + var preference = new UserRelationshipPreference() + { + PreferenceId = Constants.SOCIAL_PrefereceIDForUser11, + UserId = Constants.USER_ElevenId, + RelationshipId = Constants.SOCIAL_FriendRelationshipID, + }; // Act relationshipController.SaveUserRelationshipPreference(preference); @@ -1128,6 +1128,25 @@ public void RelationshipController_RemoveUserRelationship_Calls_DataService_On_V // Assert mockDataService.Verify(ds => ds.DeleteUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11)); } + + private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) + { + var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId }; + return mockPortalInfo; + } + + private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int masterPortalId) + { + var mockPortalGroupInfo = new PortalGroupInfo + { + PortalGroupId = portalGroupId, + MasterPortalId = masterPortalId, + PortalGroupName = Constants.PORTALGROUP_ValidName, + PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, + }; + + return mockPortalGroupInfo; + } private Mock CreateMockDataServiceWithRelationshipTypes() { @@ -1244,24 +1263,5 @@ private void SetupDataTables() this.dtUserRelationshipPreferences.Columns.Add("LastModifiedOnDate", typeof(DateTime)); this.dtUserRelationshipPreferences.PrimaryKey = new[] { pkPreferenceID }; } - - private static PortalInfo CreatePortalInfo(int portalId, int portalGroupId) - { - var mockPortalInfo = new PortalInfo { PortalID = portalId, PortalGroupID = portalGroupId }; - return mockPortalInfo; - } - - private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int masterPortalId) - { - var mockPortalGroupInfo = new PortalGroupInfo - { - PortalGroupId = portalGroupId, - MasterPortalId = masterPortalId, - PortalGroupName = Constants.PORTALGROUP_ValidName, - PortalGroupDescription = Constants.PORTALGROUP_ValidDescription, - }; - - return mockPortalGroupInfo; - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/BaseSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/BaseSettingsTests.cs index a9f8798396e..6ea0a60a62d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/BaseSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/BaseSettingsTests.cs @@ -20,6 +20,12 @@ namespace DotNetNuke.Tests.Core.Entities.Modules.Settings public abstract class BaseSettingsTests { + public readonly object[] SettingsCases = + { + new object[] { "AbcdeF#2@kfdfdfds", 9, 1.45, false, new DateTime(2015, 11, 30, 13, 45, 16), TimeSpan.Zero, TestingEnum.Value1, default(ComplexType), }, + new object[] { "Bsskk41233[]#%&", -5, -13456.456, true, DateTime.Today.AddDays(-1), new TimeSpan(1, 5, 6, 7), TestingEnum.Value2, new ComplexType(8, -10), }, + }; + protected const string SettingNamePrefix = "UnitTestSetting_"; protected const int ModuleId = 1234; protected const int TabModuleId = 653; @@ -33,6 +39,14 @@ public abstract class BaseSettingsTests protected Mock MockModuleController; protected Mock MockPortalController; + public enum TestingEnum + { + Value1, + Value2, + } + + protected static ModuleInfo GetModuleInfo => new ModuleInfo { ModuleID = ModuleId, TabModuleID = TabModuleId, TabID = TabId, PortalID = PortalId, }; + [TestFixtureSetUp] public virtual void TestFixtureSetUp() { @@ -73,20 +87,6 @@ public virtual void TearDown() ModuleController.ClearInstance(); } - public enum TestingEnum - { - Value1, - Value2, - } - - public readonly object[] SettingsCases = - { - new object[] { "AbcdeF#2@kfdfdfds", 9, 1.45, false, new DateTime(2015, 11, 30, 13, 45, 16), TimeSpan.Zero, TestingEnum.Value1, default(ComplexType), }, - new object[] { "Bsskk41233[]#%&", -5, -13456.456, true, DateTime.Today.AddDays(-1), new TimeSpan(1, 5, 6, 7), TestingEnum.Value2, new ComplexType(8, -10), }, - }; - - protected static ModuleInfo GetModuleInfo => new ModuleInfo { ModuleID = ModuleId, TabModuleID = TabModuleId, TabID = TabId, PortalID = PortalId, }; - protected static string CacheKey(ModuleInfo moduleInfo) => $"SettingsModule{moduleInfo.TabModuleID}"; protected static string ModuleSettingsCacheKey(ModuleInfo moduleInfo) => $"ModuleSettings{moduleInfo.TabID}"; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs index d009e5c8cdd..7bebab06a2a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/ModuleSettingsTests.cs @@ -17,6 +17,30 @@ namespace DotNetNuke.Tests.Core.Entities.Modules.Settings [TestFixture] public class ModuleSettingsTests : BaseSettingsTests { + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + public class ModulesSettings { [ModuleSetting(Prefix = SettingNamePrefix)] @@ -48,30 +72,6 @@ public class ModulesSettingsRepository : SettingsRepository { } - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - [Test] [TestCaseSource(nameof(SettingsCases))] [SetCulture("en-US")] @@ -112,33 +112,15 @@ public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_tr_TR(stri this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } - private void SaveSettings_CallsUpdateModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, - bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + [Test] + public void SaveSettings_UpdatesCache() { // Arrange var moduleInfo = GetModuleInfo; - var settings = new ModulesSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DoubleProperty = doubleValue, - BooleanProperty = booleanValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - EnumProperty = enumValue, - ComplexProperty = complexValue, - }; + var settings = new ModulesSettings(); this.MockModuleSettings(moduleInfo, new Hashtable()); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "StringProperty", stringValue)); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); - + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); var settingsRepository = new ModulesSettingsRepository(); // Act @@ -149,34 +131,52 @@ private void SaveSettings_CallsUpdateModuleSetting_WithRightParameters(string st } [Test] - public void SaveSettings_UpdatesCache() + public void GetSettings_CallsGetCachedObject() { // Arrange var moduleInfo = GetModuleInfo; - var settings = new ModulesSettings(); - this.MockModuleSettings(moduleInfo, new Hashtable()); - this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new ModulesSettings()); var settingsRepository = new ModulesSettingsRepository(); // Act - settingsRepository.SaveSettings(moduleInfo, settings); + settingsRepository.GetSettings(moduleInfo); // Assert this.MockRepository.VerifyAll(); } - [Test] - public void GetSettings_CallsGetCachedObject() + private void SaveSettings_CallsUpdateModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, + bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { // Arrange var moduleInfo = GetModuleInfo; + var settings = new ModulesSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; + + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "StringProperty", stringValue)); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); - this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new ModulesSettings()); var settingsRepository = new ModulesSettingsRepository(); // Act - settingsRepository.GetSettings(moduleInfo); + settingsRepository.SaveSettings(moduleInfo, settings); // Assert this.MockRepository.VerifyAll(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs index 5d535612997..37a8486b546 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/NullableSettingsTests.cs @@ -16,25 +16,13 @@ namespace DotNetNuke.Tests.Core.Entities.Modules.Settings [TestFixture] public class NullableSettingsTests : BaseSettingsTests { - public class MyNullableSettings + public readonly object[] NullableCases = { - [ModuleSetting] - public string StringProperty { get; set; } = "Default Value"; - - [PortalSetting] - public int? IntegerProperty { get; set; } = 500; - - [ModuleSetting] - public DateTime? DateTimeProperty { get; set; } = DateTime.MaxValue; - - [TabModuleSetting] - public TimeSpan? TimeSpanProperty { get; set; } = TimeSpan.FromHours(12); - } - - public class MyNullableSettingsRepository : SettingsRepository - { - } - + new object[] { null, null, null, null, }, + new object[] { string.Empty, -1, DateTime.UtcNow, TimeSpan.FromMilliseconds(3215648), }, + new object[] { "lorem ipsum", 456, DateTime.Now, DateTime.Today - DateTime.Now, }, + }; + [Test] [TestCaseSource(nameof(NullableCases))] [SetCulture("ar-JO")] @@ -58,6 +46,25 @@ public void SaveSettings_CallsUpdateSetting_WithRightParameters_zh_CN(string str { this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } + + public class MyNullableSettings + { + [ModuleSetting] + public string StringProperty { get; set; } = "Default Value"; + + [PortalSetting] + public int? IntegerProperty { get; set; } = 500; + + [ModuleSetting] + public DateTime? DateTimeProperty { get; set; } = DateTime.MaxValue; + + [TabModuleSetting] + public TimeSpan? TimeSpanProperty { get; set; } = TimeSpan.FromHours(12); + } + + public class MyNullableSettingsRepository : SettingsRepository + { + } [Test] [TestCaseSource(nameof(NullableCases))] @@ -99,29 +106,16 @@ public void SaveSettings_CallsUpdateSetting_WithRightParameters_tr_TR(string str this.SaveSettings_CallsUpdateSetting_WithRightParameters(stringValue, integerValue, datetimeValue, timeSpanValue); } - private void SaveSettings_CallsUpdateSetting_WithRightParameters(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) + [Test] + public void SaveSettings_UpdatesCache() { // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyNullableSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - }; + var settings = new MyNullableSettings(); this.MockModuleSettings(moduleInfo, new Hashtable()); this.MockTabModuleSettings(moduleInfo, new Hashtable()); - var expectedStringValue = stringValue ?? string.Empty; - this.MockModuleController.Setup(pc => pc.UpdateModuleSetting(ModuleId, "StringProperty", expectedStringValue)); - var integerString = integerValue?.ToString() ?? string.Empty; - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, "IntegerProperty", integerString, true, Null.NullString, false)); - var dateTimeString = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty; - this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, "DateTimeProperty", dateTimeString)); - var timeSpanString = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty; - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, "TimeSpanProperty", timeSpanString)); - + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); var settingsRepository = new MyNullableSettingsRepository(); // Act @@ -132,35 +126,48 @@ private void SaveSettings_CallsUpdateSetting_WithRightParameters(string stringVa } [Test] - public void SaveSettings_UpdatesCache() + public void GetSettings_CallsGetCachedObject() { // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyNullableSettings(); - this.MockModuleSettings(moduleInfo, new Hashtable()); - this.MockTabModuleSettings(moduleInfo, new Hashtable()); - this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyNullableSettings()); var settingsRepository = new MyNullableSettingsRepository(); // Act - settingsRepository.SaveSettings(moduleInfo, settings); + settingsRepository.GetSettings(moduleInfo); // Assert this.MockRepository.VerifyAll(); } - [Test] - public void GetSettings_CallsGetCachedObject() + private void SaveSettings_CallsUpdateSetting_WithRightParameters(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { // Arrange var moduleInfo = GetModuleInfo; + var settings = new MyNullableSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + }; + + this.MockModuleSettings(moduleInfo, new Hashtable()); + this.MockTabModuleSettings(moduleInfo, new Hashtable()); + var expectedStringValue = stringValue ?? string.Empty; + this.MockModuleController.Setup(pc => pc.UpdateModuleSetting(ModuleId, "StringProperty", expectedStringValue)); + var integerString = integerValue?.ToString() ?? string.Empty; + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, "IntegerProperty", integerString, true, Null.NullString, false)); + var dateTimeString = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty; + this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, "DateTimeProperty", dateTimeString)); + var timeSpanString = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty; + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, "TimeSpanProperty", timeSpanString)); - this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyNullableSettings()); var settingsRepository = new MyNullableSettingsRepository(); // Act - settingsRepository.GetSettings(moduleInfo); + settingsRepository.SaveSettings(moduleInfo, settings); // Assert this.MockRepository.VerifyAll(); @@ -255,12 +262,5 @@ private void GetSettings_GetsValues_FromCorrectSettings(string stringValue, int? Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one"); this.MockRepository.VerifyAll(); } - - public readonly object[] NullableCases = - { - new object[] { null, null, null, null, }, - new object[] { string.Empty, -1, DateTime.UtcNow, TimeSpan.FromMilliseconds(3215648), }, - new object[] { "lorem ipsum", 456, DateTime.Now, DateTime.Today - DateTime.Now, }, - }; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs index be2c22bec1b..997a80aeb93 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/PortalSettingsTests.cs @@ -17,6 +17,30 @@ namespace DotNetNuke.Tests.Core.Entities.Modules.Settings [TestFixture] public class PortalSettingsTests : BaseSettingsTests { + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + public class MyPortalSettings { [PortalSetting(Prefix = SettingNamePrefix)] @@ -48,30 +72,6 @@ public class MyPortalSettingsRepository : SettingsRepository { } - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ar-JO")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("ca-ES")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - - [Test] - [TestCaseSource(nameof(SettingsCases))] - [SetCulture("zh-CN")] - public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) - { - this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); - } - [Test] [TestCaseSource(nameof(SettingsCases))] [SetCulture("en-US")] @@ -112,32 +112,14 @@ public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_tr_TR(stri this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } - private void SaveSettings_CallsUpdatePortalSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, - bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + [Test] + public void SaveSettings_UpdatesCache() { // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyPortalSettings - { - StringProperty = stringValue, - IntegerProperty = integerValue, - DoubleProperty = doubleValue, - BooleanProperty = booleanValue, - DateTimeProperty = datetimeValue, - TimeSpanProperty = timeSpanValue, - EnumProperty = enumValue, - ComplexProperty = complexValue, - }; - - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "StringProperty", stringValue, true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "IntegerProperty", integerValue.ToString(), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString(), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "EnumProperty", enumValue.ToString(), true, Null.NullString, false)); - this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}", true, Null.NullString, false)); + var settings = new MyPortalSettings(); + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); var settingsRepository = new MyPortalSettingsRepository(); // Act @@ -148,33 +130,51 @@ private void SaveSettings_CallsUpdatePortalSetting_WithRightParameters(string st } [Test] - public void SaveSettings_UpdatesCache() + public void GetSettings_CallsGetCachedObject() { // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyPortalSettings(); - this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyPortalSettings()); var settingsRepository = new MyPortalSettingsRepository(); // Act - settingsRepository.SaveSettings(moduleInfo, settings); + settingsRepository.GetSettings(moduleInfo); // Assert this.MockRepository.VerifyAll(); } - [Test] - public void GetSettings_CallsGetCachedObject() + private void SaveSettings_CallsUpdatePortalSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, + bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { // Arrange var moduleInfo = GetModuleInfo; + var settings = new MyPortalSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; + + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "StringProperty", stringValue, true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "IntegerProperty", integerValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "EnumProperty", enumValue.ToString(), true, Null.NullString, false)); + this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}", true, Null.NullString, false)); - this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyPortalSettings()); var settingsRepository = new MyPortalSettingsRepository(); // Act - settingsRepository.GetSettings(moduleInfo); + settingsRepository.SaveSettings(moduleInfo, settings); // Assert this.MockRepository.VerifyAll(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs index 9d6389196f1..37a4d45709d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Modules/Settings/TabModuleSettingsTests.cs @@ -17,6 +17,30 @@ namespace DotNetNuke.Tests.Core.Entities.Modules.Settings [TestFixture] public class TabModuleSettingsTests : BaseSettingsTests { + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ar-JO")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ar_JO(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("ca-ES")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_ca_ES(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + + [Test] + [TestCaseSource(nameof(SettingsCases))] + [SetCulture("zh-CN")] + public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_zh_CN(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) + { + this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); + } + public class MyTabModuleSettings { [TabModuleSetting(Prefix = SettingNamePrefix)] @@ -48,30 +72,6 @@ public class MyTabModuleSettingsRepository : SettingsRepository mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "StringProperty", stringValue)); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); - this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); - + this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); var settingsRepository = new MyTabModuleSettingsRepository(); // Act @@ -148,35 +131,52 @@ private void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(string } [Test] - public void SaveSettings_UpdatesCache() + public void GetSettings_CallsGetCachedObject() { // Arrange var moduleInfo = GetModuleInfo; - var settings = new MyTabModuleSettings(); this.MockTabModuleSettings(moduleInfo, new Hashtable()); - this.MockCache.Setup(c => c.Insert(CacheKey(moduleInfo), settings)); + this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyTabModuleSettings()); var settingsRepository = new MyTabModuleSettingsRepository(); // Act - settingsRepository.SaveSettings(moduleInfo, settings); + settingsRepository.GetSettings(moduleInfo); // Assert this.MockRepository.VerifyAll(); } - [Test] - public void GetSettings_CallsGetCachedObject() + private void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { // Arrange var moduleInfo = GetModuleInfo; + var settings = new MyTabModuleSettings + { + StringProperty = stringValue, + IntegerProperty = integerValue, + DoubleProperty = doubleValue, + BooleanProperty = booleanValue, + DateTimeProperty = datetimeValue, + TimeSpanProperty = timeSpanValue, + EnumProperty = enumValue, + ComplexProperty = complexValue, + }; this.MockTabModuleSettings(moduleInfo, new Hashtable()); - this.MockCache.Setup(c => c.GetItem("DNN_" + CacheKey(moduleInfo))).Returns(new MyTabModuleSettings()); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "StringProperty", stringValue)); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "IntegerProperty", integerValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DoubleProperty", doubleValue.ToString(CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "BooleanProperty", booleanValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "DateTimeProperty", datetimeValue.ToString("o", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "TimeSpanProperty", timeSpanValue.ToString("c", CultureInfo.InvariantCulture))); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "EnumProperty", enumValue.ToString())); + this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, SettingNamePrefix + "ComplexProperty", $"{complexValue.X} | {complexValue.Y}")); + var settingsRepository = new MyTabModuleSettingsRepository(); // Act - settingsRepository.GetSettings(moduleInfo); + settingsRepository.SaveSettings(moduleInfo, settings); // Assert this.MockRepository.VerifyAll(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTestFactory.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTestFactory.cs index e864df2d057..6b365064301 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTestFactory.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTestFactory.cs @@ -29,22 +29,6 @@ internal static string FilePath } } - internal static Dictionary GetHostSettings() - { - var settings = new Dictionary(); - - // Read Test Settings - Util.ReadStream(FilePath, "HostSettings", (line, header) => - { - string[] fields = line.Split(','); - string key = fields[0].Trim(); - string value = fields[1].Trim(); - - settings.Add(key, value); - }); - return settings; - } - internal static IEnumerable LoadPortalSettings_Loads_Default_Value { get @@ -106,5 +90,21 @@ internal static IEnumerable LoadPortalSettings_Loads_Setting_Value return testData; } } + + internal static Dictionary GetHostSettings() + { + var settings = new Dictionary(); + + // Read Test Settings + Util.ReadStream(FilePath, "HostSettings", (line, header) => + { + string[] fields = line.Split(','); + string key = fields[0].Trim(); + string value = fields[1].Trim(); + + settings.Add(key, value); + }); + return settings; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs index 58e377fe0a5..e0893017f4e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs @@ -154,17 +154,17 @@ public void Constructor_Calls_PortalController_GetPortal_When_Passed_PortalAlias [Test] public void Constructor_Calls_PortalSettingsController_LoadPortal_When_Passed_Portal() - { - // Arrange - var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); - - var portal = this.CreatePortal(ValidPortalId); - - // Act - var settings = new PortalSettings(ValidTabId, portal); - - // Assert - mockPortalSettingsController.Verify(c => c.LoadPortal(portal, settings)); + { + // Arrange + var mockPortalSettingsController = MockComponentProvider.CreateNew("PortalSettingsController"); + + var portal = this.CreatePortal(ValidPortalId); + + // Act + var settings = new PortalSettings(ValidTabId, portal); + + // Assert + mockPortalSettingsController.Verify(c => c.LoadPortal(portal, settings)); } [Test] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/JavaScriptLibraries/JavaScriptTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/JavaScriptLibraries/JavaScriptTests.cs index 867cb3a176a..63a2d0ca75b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/JavaScriptLibraries/JavaScriptTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Framework/JavaScriptLibraries/JavaScriptTests.cs @@ -230,16 +230,16 @@ public void FallbackToHighestVersionLibraryWhenDifferentMinorVersion() int higherVersionJavaScriptLibraryId = this.libraryIdCounter++; this.SetupJavaScriptLibraryController( new JavaScriptLibrary - { - JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(2, 1, 0), - }, new JavaScriptLibrary - { - JavaScriptLibraryID = higherVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(3, 3, 3), - }); + { + JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(2, 1, 0), + }, new JavaScriptLibrary + { + JavaScriptLibraryID = higherVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(3, 3, 3), + }); // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 2), SpecificVersion.LatestMinor); @@ -257,16 +257,16 @@ public void FallbackToHighestVersionLibraryWhenDifferentMinorVersionWithMismatch int higherVersionJavaScriptLibraryId = this.libraryIdCounter++; this.SetupJavaScriptLibraryController( new JavaScriptLibrary - { - JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, - LibraryName = "test", - Version = new Version(2, 1, 0), - }, new JavaScriptLibrary - { - JavaScriptLibraryID = higherVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(3, 3, 3), - }); + { + JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, + LibraryName = "test", + Version = new Version(2, 1, 0), + }, new JavaScriptLibrary + { + JavaScriptLibraryID = higherVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(3, 3, 3), + }); // Act JavaScript.RequestRegistration("test", new Version(2, 2, 2), SpecificVersion.LatestMinor); @@ -322,16 +322,16 @@ public void FallbackToHighestVersionLibraryWhenDifferentMajorVersion() int higherVersionJavaScriptLibraryId = this.libraryIdCounter++; this.SetupJavaScriptLibraryController( new JavaScriptLibrary - { - JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(1, 2, 2), - }, new JavaScriptLibrary - { - JavaScriptLibraryID = higherVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(3, 3, 3), - }); + { + JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(1, 2, 2), + }, new JavaScriptLibrary + { + JavaScriptLibraryID = higherVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(3, 3, 3), + }); // Act JavaScript.RequestRegistration("Test", new Version(2, 2, 2), SpecificVersion.LatestMajor); @@ -349,16 +349,16 @@ public void FallbackToHighestVersionLibraryWhenDifferentMajorVersionWithMismatch int higherVersionJavaScriptLibraryId = this.libraryIdCounter++; this.SetupJavaScriptLibraryController( new JavaScriptLibrary - { - JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, - LibraryName = "test", - Version = new Version(1, 2, 2), - }, new JavaScriptLibrary - { - JavaScriptLibraryID = higherVersionJavaScriptLibraryId, - LibraryName = "Test", - Version = new Version(3, 3, 3), - }); + { + JavaScriptLibraryID = lowerVersionJavaScriptLibraryId, + LibraryName = "test", + Version = new Version(1, 2, 2), + }, new JavaScriptLibrary + { + JavaScriptLibraryID = higherVersionJavaScriptLibraryId, + LibraryName = "Test", + Version = new Version(3, 3, 3), + }); // Act JavaScript.RequestRegistration("test", new Version(2, 2, 2), SpecificVersion.LatestMajor); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs index fac02cc6665..04e935e69b3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs @@ -65,17 +65,17 @@ internal FileInfoBuilder WithEnablePublishPeriod(bool enablePublishPeriod) internal FileInfo Build() { - return new FileInfo - { - FileId = this.fileId, - PortalId = this.portalId, - StartDate = this.startDate, - EnablePublishPeriod = this.enablePublishPeriod, - EndDate = this.endDate, - ContentItemID = this.contentItemId, - FolderMappingID = this.folderMappingID, - FolderId = this.folderId, - }; + return new FileInfo + { + FileId = this.fileId, + PortalId = this.portalId, + StartDate = this.startDate, + EnablePublishPeriod = this.enablePublishPeriod, + EndDate = this.endDate, + ContentItemID = this.contentItemId, + FolderMappingID = this.folderMappingID, + FolderId = this.folderId, + }; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs index f542016abc8..e0585b69ce0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs @@ -209,14 +209,6 @@ public void AddFile_Checks_Space_For_Stream_Length() this._portalController.Verify(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, fileContent.Length)); } - private class UnSeekableStream : MemoryStream - { - public override bool CanSeek - { - get { return false; } - } - } - [Test] [ExpectedException(typeof(InvalidFileExtensionException))] public void AddFile_Throws_When_Extension_Is_Invalid() @@ -264,48 +256,12 @@ public void AddFile_No_Error_When_File_Content_Is_Valid() } } - private void PrepareFileSecurityCheck() + private class UnSeekableStream : MemoryStream { - this._mockData.Setup(p => p.GetListEntriesByListName("FileSecurityChecker", string.Empty, Null.NullInteger)).Returns(() => + public override bool CanSeek { - var dataTable = new DataTable(); - dataTable.Columns.Add("EntryID", typeof(int)); - dataTable.Columns.Add("ListName", typeof(string)); - dataTable.Columns.Add("Value", typeof(string)); - dataTable.Columns.Add("Text", typeof(string)); - dataTable.Columns.Add("Level", typeof(int)); - dataTable.Columns.Add("SortOrder", typeof(int)); - dataTable.Columns.Add("DefinitionID", typeof(int)); - dataTable.Columns.Add("ParentID", typeof(int)); - dataTable.Columns.Add("Description", typeof(string)); - dataTable.Columns.Add("PortalID", typeof(int)); - dataTable.Columns.Add("SystemList", typeof(bool)); - dataTable.Columns.Add("ParentKey", typeof(string)); - dataTable.Columns.Add("Parent", typeof(string)); - dataTable.Columns.Add("ParentList", typeof(string)); - dataTable.Columns.Add("MaxSortOrder", typeof(int)); - dataTable.Columns.Add("EntryCount", typeof(int)); - dataTable.Columns.Add("HasChildren", typeof(int)); - dataTable.Columns.Add("CreatedByUserID", typeof(int)); - dataTable.Columns.Add("CreatedOnDate", typeof(DateTime)); - dataTable.Columns.Add("LastModifiedByUserID", typeof(int)); - dataTable.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - - dataTable.Rows.Add(1, "FileSecurityChecker", "svg", - "DotNetNuke.Services.FileSystem.Internal.SecurityCheckers.SvgFileChecker, DotNetNuke", - 0, 0, -1, -0, string.Empty, -1, 1, string.Empty, string.Empty, string.Empty, 0, 1, 0, -1, DateTime.Now, -1, DateTime.Now); - - return dataTable.CreateDataReader(); - }); - this._hostController.Setup(c => c.GetString("PerformanceSetting")).Returns("NoCaching"); - this._globals.Setup(g => g.HostMapPath).Returns(AppDomain.CurrentDomain.BaseDirectory); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + get { return false; } + } } [Test] @@ -376,6 +332,50 @@ public void CopyFile_Throws_On_Null_File() this._fileManager.CopyFile(null, this._folderInfo.Object); } + private void PrepareFileSecurityCheck() + { + this._mockData.Setup(p => p.GetListEntriesByListName("FileSecurityChecker", string.Empty, Null.NullInteger)).Returns(() => + { + var dataTable = new DataTable(); + dataTable.Columns.Add("EntryID", typeof(int)); + dataTable.Columns.Add("ListName", typeof(string)); + dataTable.Columns.Add("Value", typeof(string)); + dataTable.Columns.Add("Text", typeof(string)); + dataTable.Columns.Add("Level", typeof(int)); + dataTable.Columns.Add("SortOrder", typeof(int)); + dataTable.Columns.Add("DefinitionID", typeof(int)); + dataTable.Columns.Add("ParentID", typeof(int)); + dataTable.Columns.Add("Description", typeof(string)); + dataTable.Columns.Add("PortalID", typeof(int)); + dataTable.Columns.Add("SystemList", typeof(bool)); + dataTable.Columns.Add("ParentKey", typeof(string)); + dataTable.Columns.Add("Parent", typeof(string)); + dataTable.Columns.Add("ParentList", typeof(string)); + dataTable.Columns.Add("MaxSortOrder", typeof(int)); + dataTable.Columns.Add("EntryCount", typeof(int)); + dataTable.Columns.Add("HasChildren", typeof(int)); + dataTable.Columns.Add("CreatedByUserID", typeof(int)); + dataTable.Columns.Add("CreatedOnDate", typeof(DateTime)); + dataTable.Columns.Add("LastModifiedByUserID", typeof(int)); + dataTable.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + + dataTable.Rows.Add(1, "FileSecurityChecker", "svg", + "DotNetNuke.Services.FileSystem.Internal.SecurityCheckers.SvgFileChecker, DotNetNuke", + 0, 0, -1, -0, string.Empty, -1, 1, string.Empty, string.Empty, string.Empty, 0, 1, 0, -1, DateTime.Now, -1, DateTime.Now); + + return dataTable.CreateDataReader(); + }); + this._hostController.Setup(c => c.GetString("PerformanceSetting")).Returns("NoCaching"); + this._globals.Setup(g => g.HostMapPath).Returns(AppDomain.CurrentDomain.BaseDirectory); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void CopyFile_Throws_On_Null_DestinationFolder() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs index 6065260737f..61a22a0ce6d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs @@ -82,6 +82,23 @@ public void Setup() LocaleController.RegisterInstance(this._localeControllerMock.Object); } + [TearDown] + public void TearDown() + { + MockComponentProvider.ResetContainer(); + TestableGlobals.ClearInstance(); + PortalController.ClearInstance(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void AddFile_Throws_On_Null_Folder() + { + var stream = new Mock(); + + this._sfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); + } + private Dictionary GetPortalSettingsDictionaryMock() { var portalSettingsDictionary = new Dictionary(); @@ -101,23 +118,6 @@ private PortalSettings GetPortalSettingsMock() return portalSettingsMock.Object; } - [TearDown] - public void TearDown() - { - MockComponentProvider.ResetContainer(); - TestableGlobals.ClearInstance(); - PortalController.ClearInstance(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void AddFile_Throws_On_Null_Folder() - { - var stream = new Mock(); - - this._sfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); - } - [Test] [TestCase(null)] [TestCase("")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs index 98c256c3c13..cd8dd5ba728 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs @@ -308,6 +308,14 @@ private static PortalSettings SetupPortalSettings() return portalSettings; } + private static void AddModulePermission(ModulePermissionCollection permissions, string key, int roleId) + { + var permissionController = new PermissionController(); + var permission = (PermissionInfo)permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", key)[0]; + var modulePermission = new ModulePermissionInfo { PermissionID = permission.PermissionID, RoleID = roleId, AllowAccess = true }; + permissions.Add(modulePermission); + } + private void CreateUser(bool isSuperUser, IEnumerable Roles) { var user = new UserInfo { IsSuperUser = isSuperUser, UserID = UserId }; @@ -325,13 +333,5 @@ private void CreateUser(bool isSuperUser, IEnumerable Roles) HttpContextSource.RegisterInstance(httpContextBase); HttpContext.Current.Items["UserInfo"] = user; } - - private static void AddModulePermission(ModulePermissionCollection permissions, string key, int roleId) - { - var permissionController = new PermissionController(); - var permission = (PermissionInfo)permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", key)[0]; - var modulePermission = new ModulePermissionInfo { PermissionID = permission.PermissionID, RoleID = roleId, AllowAccess = true }; - permissions.Add(modulePermission); - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs index 8782237f30d..8c55d236b50 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs @@ -86,11 +86,6 @@ internal class SleepMonitor { private readonly List _periods = new List(); - public void GoToSleep(int delay) - { - this._periods.Add(delay); - } - public IList SleepPeriod { get @@ -98,6 +93,11 @@ public IList SleepPeriod return this._periods.AsReadOnly(); } } + + public void GoToSleep(int delay) + { + this._periods.Add(delay); + } } internal class ActionMonitor diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs index 91be8adfd44..ba7a2a015b0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs @@ -115,15 +115,6 @@ public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Post_Va var request = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); Assert.AreEqual(true, request.IsValid); } - - private void SetReadonly(NameValueCollection collection, bool readOnly) - { - var readOnlyProperty = collection.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance); - if (readOnlyProperty != null) - { - readOnlyProperty.SetValue(collection, readOnly, null); - } - } /// /// method for converting a System.DateTime value to a UNIX Timestamp. @@ -137,5 +128,14 @@ private static DateTime ConvertToTimestamp(long value) DateTime epoc = new DateTime(1970, 1, 1, 0, 0, 0, 0); return epoc.AddSeconds((double)value); } + + private void SetReadonly(NameValueCollection collection, bool readOnly) + { + var readOnlyProperty = collection.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance); + if (readOnlyProperty != null) + { + readOnlyProperty.SetValue(collection, readOnly, null); + } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs index 7b85314c081..03fd64ba6e6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs @@ -35,6 +35,9 @@ namespace DotNetNuke.Tests.Core.Services.Mobile [TestFixture] public class RedirectionControllerTests { + public const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; + public const string wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; + private Mock _dataProvider; private RedirectionController _redirectionController; private Mock _clientCapabilityProvider; @@ -42,9 +45,6 @@ public class RedirectionControllerTests private DataTable _dtRedirections; private DataTable _dtRules; - - public const string iphoneUserAgent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; - public const string wp7UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0) Asus;Galaxy6"; public const string msIE8UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; Creative AutoUpdate v1.40.02)"; public const string msIE9UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; public const string msIE10UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; @@ -133,15 +133,6 @@ public void TearDown() ComponentFactory.Container = null; } - - private void SetupContianer() - { - var navigationManagerMock = new Mock(); - navigationManagerMock.Setup(x => x.NavigateURL(It.IsAny())).Returns(x => this.NavigateUrl(x)); - var containerMock = new Mock(); - containerMock.Setup(x => x.GetService(typeof(INavigationManager))).Returns(navigationManagerMock.Object); - Globals.DependencyProvider = containerMock.Object; - } [Test] public void RedirectionController_Save_Valid_Redirection() @@ -180,6 +171,15 @@ public void RedirectionController_Save_ValidRedirection_With_Rules() Assert.AreEqual(2, getRe.MatchRules.Count); } + private void SetupContianer() + { + var navigationManagerMock = new Mock(); + navigationManagerMock.Setup(x => x.NavigateURL(It.IsAny())).Returns(x => this.NavigateUrl(x)); + var containerMock = new Mock(); + containerMock.Setup(x => x.GetService(typeof(INavigationManager))).Returns(navigationManagerMock.Object); + Globals.DependencyProvider = containerMock.Object; + } + [Test] public void RedirectionController_GetRedirectionsByPortal_With_Valid_PortalID() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs index b3cd997527b..dba880e0079 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs @@ -143,39 +143,39 @@ public void DateTimePropertyAcccess_GetProperty_Returns_Correct_String_For_Cultu [TestCase("now", "de", "mmm yyyy")] [TestCase("system", "en", "dd/mm/yy")] [TestCase("utc", "it", "mmm dd, yyyy")] - public void DateTimePropertyAcccess_GetProperty_Returns_Correct_String_Given_Format_And_Culture(string propertyName, string cultureName, string format) - { - // Arrange - var dtPropertyAccess = new DateTimePropertyAccess(); - var accessingUser = new UserInfo { Profile = new UserProfile { PreferredTimeZone = TimeZoneInfo.Local } }; - var culture = new CultureInfo(cultureName); + public void DateTimePropertyAcccess_GetProperty_Returns_Correct_String_Given_Format_And_Culture(string propertyName, string cultureName, string format) + { + // Arrange + var dtPropertyAccess = new DateTimePropertyAccess(); + var accessingUser = new UserInfo { Profile = new UserProfile { PreferredTimeZone = TimeZoneInfo.Local } }; + var culture = new CultureInfo(cultureName); - string expected = string.Empty; - - switch (propertyName) - { - case "current": - expected = DateTime.Now.ToString(format, culture); - break; - case "now": - expected = DateTime.Now.ToString(format, culture); - break; - case "system": - expected = DateTime.Now.ToString(format, culture); - break; - case "utc": - expected = DateTime.Now.ToUniversalTime().ToString(format, culture); - break; - } + string expected = string.Empty; - // Act - bool propertyNotFound = false; - string propertyValue = dtPropertyAccess.GetProperty(propertyName, format, culture, - accessingUser, Scope.DefaultSettings, ref propertyNotFound); - - // Assert - Assert.AreEqual(expected, propertyValue); - } + switch (propertyName) + { + case "current": + expected = DateTime.Now.ToString(format, culture); + break; + case "now": + expected = DateTime.Now.ToString(format, culture); + break; + case "system": + expected = DateTime.Now.ToString(format, culture); + break; + case "utc": + expected = DateTime.Now.ToUniversalTime().ToString(format, culture); + break; + } + + // Act + bool propertyNotFound = false; + string propertyValue = dtPropertyAccess.GetProperty(propertyName, format, culture, + accessingUser, Scope.DefaultSettings, ref propertyNotFound); + + // Assert + Assert.AreEqual(expected, propertyValue); + } [Test] [TestCase("current", "Tokyo Standard Time")] @@ -185,11 +185,11 @@ public void DateTimePropertyAcccess_GetProperty_Adjusts_For_TimeZone(string prop // Arrange var dtPropertyAccess = new DateTimePropertyAccess(); var userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); - var timeZoneProfileProperty = new ProfilePropertyDefinition(Constants.PORTAL_Zero) - { - PropertyName = "PreferredTimeZone", - PropertyValue = timeZoneId, - }; + var timeZoneProfileProperty = new ProfilePropertyDefinition(Constants.PORTAL_Zero) + { + PropertyName = "PreferredTimeZone", + PropertyValue = timeZoneId, + }; var userProfile = new UserProfile(); userProfile.ProfileProperties.Add(timeZoneProfileProperty); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs index b7663ec3021..1c5a635c4fa 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs @@ -17,6 +17,9 @@ namespace DotNetNuke.Tests.Data [TestFixture] public class PetaPocoDataContextTests { + private const string connectionStringName = "PetaPoco"; + private const string tablePrefix = "dnn_"; + // ReSharper disable InconsistentNaming [SetUp] public void SetUp() @@ -28,9 +31,6 @@ public void TearDown() { } - private const string connectionStringName = "PetaPoco"; - private const string tablePrefix = "dnn_"; - [Test] public void PetaPocoDataContext_Constructors_Throw_On_Null_ConnectionString() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs index 0f069640e30..dfa1ce753ae 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs @@ -20,6 +20,8 @@ namespace DotNetNuke.Tests.Data [TestFixture] public class PetaPocoIntegrationTests { + private const string ConnectionStringName = "PetaPoco"; + private Dictionary _mappers; // ReSharper disable InconsistentNaming @@ -58,8 +60,6 @@ public void TearDown() { DataUtil.DeleteDatabase(Constants.PETAPOCO_DatabaseName); } - - private const string ConnectionStringName = "PetaPoco"; [Test] public void PetaPoco_Add_Inserts_Item() @@ -67,11 +67,11 @@ public void PetaPoco_Add_Inserts_Item() // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName, - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; using (var dataContext = new PetaPocoDataContext(ConnectionStringName)) { @@ -94,11 +94,11 @@ public void PetaPoco_Add_Inserts_Item_Using_FluentMapper() // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName, - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; using (var dataContext = new PetaPocoDataContext(ConnectionStringName, string.Empty, this._mappers)) { @@ -121,12 +121,12 @@ public void PetaPoco_Delete_Deletes_Item() // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - ID = Constants.PETAPOCO_DeleteDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_DeleteDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; using (var dataContext = new PetaPocoDataContext(ConnectionStringName)) { @@ -149,12 +149,12 @@ public void PetaPoco_Delete_Deletes_Item_Using_FluentMapper() // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - ID = Constants.PETAPOCO_DeleteDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_DeleteDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; using (var dataContext = new PetaPocoDataContext(ConnectionStringName, string.Empty, this._mappers)) { @@ -306,12 +306,12 @@ public void PetaPoco_Update_Updates_Item() // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - ID = Constants.PETAPOCO_UpdateDogId, - Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_UpdateDogId, + Age = Constants.PETAPOCO_UpdateDogAge, + Name = Constants.PETAPOCO_UpdateDogName, + }; // Act using (var dataContext = new PetaPocoDataContext(ConnectionStringName)) @@ -343,12 +343,12 @@ public void PetaPoco_Update_Updates_Item_Using_FluentMapper() // Arrange DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); - var dog = new Dog - { - ID = Constants.PETAPOCO_UpdateDogId, - Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_UpdateDogId, + Age = Constants.PETAPOCO_UpdateDogAge, + Name = Constants.PETAPOCO_UpdateDogName, + }; // Act using (var dataContext = new PetaPocoDataContext(ConnectionStringName, string.Empty, this._mappers)) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs index 0847bb1d9c5..08ba316ec55 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs @@ -271,11 +271,11 @@ public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase() DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName, - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; // Act repository.Insert(dog); @@ -297,11 +297,11 @@ public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ID() DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName, - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; // Act repository.Insert(dog); @@ -323,11 +323,11 @@ public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_Colum DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - Age = Constants.PETAPOCO_InsertDogAge, - Name = Constants.PETAPOCO_InsertDogName, - }; + var dog = new Dog + { + Age = Constants.PETAPOCO_InsertDogAge, + Name = Constants.PETAPOCO_InsertDogName, + }; // Act repository.Insert(dog); @@ -382,12 +382,12 @@ public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase() DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_DeleteDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_DeleteDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; // Act repository.Delete(dog); @@ -409,12 +409,12 @@ public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_DeleteDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_DeleteDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; // Act repository.Delete(dog); @@ -470,12 +470,12 @@ public void PetaPocoRepository_Delete_Does_Nothing_With_Invalid_ID() DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_InvalidDogId, - Age = Constants.PETAPOCO_DeleteDogAge, - Name = Constants.PETAPOCO_DeleteDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_InvalidDogId, + Age = Constants.PETAPOCO_DeleteDogAge, + Name = Constants.PETAPOCO_DeleteDogName, + }; // Act repository.Delete(dog); @@ -700,12 +700,12 @@ public void PetaPocoRepository_Update_Updates_Item_In_DataBase() DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_UpdateDogId, - Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_UpdateDogId, + Age = Constants.PETAPOCO_UpdateDogAge, + Name = Constants.PETAPOCO_UpdateDogName, + }; // Act repository.Update(dog); @@ -727,12 +727,12 @@ public void PetaPocoRepository_Update_Updates_Item_With_Correct_ID() DataUtil.SetUpDatabase(Constants.PETAPOCO_RecordCount); var repository = new PetaPocoRepository(db, mapper); - var dog = new Dog - { - ID = Constants.PETAPOCO_UpdateDogId, - Age = Constants.PETAPOCO_UpdateDogAge, - Name = Constants.PETAPOCO_UpdateDogName, - }; + var dog = new Dog + { + ID = Constants.PETAPOCO_UpdateDogId, + Age = Constants.PETAPOCO_UpdateDogAge, + Name = Constants.PETAPOCO_UpdateDogName, + }; // Act repository.Update(dog); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs index 129004c0d69..bf81f1d1c99 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs @@ -63,6 +63,6 @@ public class PageSettings public IList modules { get; set; } - public bool isSecure { get; set; } + public bool isSecure { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs index 472d99b9c16..9eca5061a46 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs @@ -27,7 +27,22 @@ public abstract class WebApiExecuter { public Func Login; + protected Func Anonymous; + + protected List Responses = new List(); + private LoginAsUser _loginAs; + private IWebApiConnector _connector; + + protected WebApiExecuter() + { + this.LoginAs = LoginAsUser.RegisteredUser; + this.Login = WebApiTestHelper.LoginRegisteredUser; + this.Anonymous = WebApiTestHelper.GetAnnonymousConnector; + + this.UserFirstName = Constants.RuFirstName; + this.UserLastName = Constants.RuLastName; + } public LoginAsUser LoginAs { @@ -47,19 +62,6 @@ public LoginAsUser LoginAs public string UserLastName { get; set; } - protected Func Anonymous; - private IWebApiConnector _connector; - - protected WebApiExecuter() - { - this.LoginAs = LoginAsUser.RegisteredUser; - this.Login = WebApiTestHelper.LoginRegisteredUser; - this.Anonymous = WebApiTestHelper.GetAnnonymousConnector; - - this.UserFirstName = Constants.RuFirstName; - this.UserLastName = Constants.RuLastName; - } - public IWebApiConnector Connector { get @@ -122,8 +124,6 @@ public int UserId } } - protected List Responses = new List(); - public HttpResponseMessage GetLastResponseMessage() { return this.Responses.Last(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs index 1b39aa56db4..f54cd85a395 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs @@ -16,6 +16,8 @@ namespace DotNetNuke.Tests.Integration.Modules.Journal [TestFixture] public class PostJournalTests : IntegrationTestBase { + private static readonly Random rnd = new Random(); + private readonly string _hostName; private readonly string _hostPass; @@ -424,8 +426,6 @@ public void Journal_Should_Only_Able_See_By_Himself_When_Set_Security_To_Private response = hostConnector.GetContent($"/Activity-Feed/userId/{userId}").Content.ReadAsStringAsync().Result; Assert.AreEqual(response.IndexOf(journalText), -1); } - - private static readonly Random rnd = new Random(); private IWebApiConnector PrepareNewUser(out int userId, out string username, out int fileId) { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs index f43dd8ec9cb..1f36c87f6aa 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs @@ -18,8 +18,31 @@ namespace DotNetNuke.Tests.Integration.Services.Installer [TestFixture] public class XmlMergeTests : DnnUnitTest { - private readonly Assembly _assembly = typeof(XmlMergeTests).Assembly; private const bool OutputXml = true; + private readonly Assembly _assembly = typeof(XmlMergeTests).Assembly; + + [SetUp] + public void SetUp() + { + AppDomain.CurrentDomain.SetData("APPBASE", this.WebsitePhysicalAppPath); + + LoggerSource.SetTestableInstance(new TestLogSource()); + } + + // ReSharper disable PossibleNullReferenceException + [Test] + public void SimpleUpdate() + { + XmlDocument targetDoc = this.ExecuteMerge(); + + // children are in correct location + XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); + Assert.AreEqual(2, nodes.Count); + + // children only inserted once + nodes = targetDoc.SelectNodes("//child"); + Assert.AreEqual(2, nodes.Count); + } /// /// Merges the Merge and Target files based on the name of the calling method. @@ -96,11 +119,11 @@ private XmlMerge GetXmlMerge(string fileName) } private void WriteToDebug(XmlDocument targetDoc) - { -// ReSharper disable ConditionIsAlwaysTrueOrFalse - if (OutputXml) + { + // ReSharper disable ConditionIsAlwaysTrueOrFalse + if (OutputXml) -// ReSharper restore ConditionIsAlwaysTrueOrFalse + // ReSharper restore ConditionIsAlwaysTrueOrFalse { using (var writer = new StreamWriter(new MemoryStream())) { @@ -114,29 +137,6 @@ private void WriteToDebug(XmlDocument targetDoc) } } - [SetUp] - public void SetUp() - { - AppDomain.CurrentDomain.SetData("APPBASE", this.WebsitePhysicalAppPath); - - LoggerSource.SetTestableInstance(new TestLogSource()); - } - -// ReSharper disable PossibleNullReferenceException - [Test] - public void SimpleUpdate() - { - XmlDocument targetDoc = this.ExecuteMerge(); - - // children are in correct location - XmlNodeList nodes = targetDoc.SelectNodes("/configuration/updateme/children/child"); - Assert.AreEqual(2, nodes.Count); - - // children only inserted once - nodes = targetDoc.SelectNodes("//child"); - Assert.AreEqual(2, nodes.Count); - } - [Test] public void SimpleUpdateInLocation() { @@ -491,9 +491,9 @@ public void ShouldPreserveEmptyNamespaceOnSave() var dependentAssembly = nodesWithoutNamespace[0]; var bindingRedirect = dependentAssembly.SelectSingleNode("bindingRedirect", ns); Assert.AreEqual("4.1.0.0", bindingRedirect.Attributes["newVersion"].Value); - } - -// ReSharper restore PossibleNullReferenceException + } + + // ReSharper restore PossibleNullReferenceException } internal class TestLogSource : ILoggerSource @@ -511,6 +511,21 @@ public ILog GetLogger(Type type) internal class TestLogger : ILog { + public bool IsDebugEnabled + { + get { return false; } + } + + public bool IsErrorEnabled + { + get { return false; } + } + + public bool IsFatalEnabled + { + get { return false; } + } + public void Debug(object message, Exception exception) { } @@ -575,21 +590,6 @@ public void InfoFormat(string format, params object[] args) { } - public bool IsDebugEnabled - { - get { return false; } - } - - public bool IsErrorEnabled - { - get { return false; } - } - - public bool IsFatalEnabled - { - get { return false; } - } - public bool IsInfoEnabled { get { return false; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs index 138b4b72bf9..4867dc352c7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs @@ -16,13 +16,13 @@ namespace DotNetNuke.Tests.Integration.Tests.DotNetNukeWeb [TestFixture] public class DotNetNukeWebTests : IntegrationTestBase { + private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; + private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; + private readonly HttpClient _httpClient; private readonly TimeSpan _timeout = TimeSpan.FromSeconds(30); - private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; - private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; - public DotNetNukeWebTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs index d6b5900b1cf..ee2364f81ec 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs @@ -96,7 +96,7 @@ private void PrepareSecondLanguage() private bool LanguageEnabled(int portalId, string secondLanguage) { - var portalLanguages = CBO.FillDictionary("CultureCode", DataProvider.Instance().GetLanguagesByPortal(portalId)); + var portalLanguages = CBO.FillDictionary("CultureCode", DataProvider.Instance().GetLanguagesByPortal(portalId)); if (!portalLanguages.ContainsKey(secondLanguage)) { var connector = WebApiTestHelper.LoginHost(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Jwt/JwtAuthTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Jwt/JwtAuthTest.cs index 4f3de1e47bf..f1c7476e0d0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Jwt/JwtAuthTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Jwt/JwtAuthTest.cs @@ -21,11 +21,18 @@ namespace DotNetNuke.Tests.Integration.Tests.Jwt [TestFixture] public class JwtAuthTest : IntegrationTestBase { + public const string ExtendTokenQuery = "/API/JwtAuth/mobile/extendtoken"; + + private const string LoginQuery = "/API/JwtAuth/mobile/login"; + private const string LogoutQuery = "/API/JwtAuth/mobile/logout"; + private const string TestGetQuery = "/API/JwtAuth/mobile/testget"; + private const string TestPostQuery = "/API/JwtAuth/mobile/testpost"; + private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; + private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; + private static readonly Encoding TextEncoder = Encoding.UTF8; private readonly string _hostName; private readonly string _hostPass; private readonly HttpClient _httpClient; - - private static readonly Encoding TextEncoder = Encoding.UTF8; #if DEBUG // for degugging and setting breakpoints private readonly TimeSpan _timeout = TimeSpan.FromSeconds(300); @@ -33,14 +40,6 @@ public class JwtAuthTest : IntegrationTestBase private readonly TimeSpan _timeout = TimeSpan.FromSeconds(30); #endif - private const string LoginQuery = "/API/JwtAuth/mobile/login"; - private const string LogoutQuery = "/API/JwtAuth/mobile/logout"; - public const string ExtendTokenQuery = "/API/JwtAuth/mobile/extendtoken"; - private const string TestGetQuery = "/API/JwtAuth/mobile/testget"; - private const string TestPostQuery = "/API/JwtAuth/mobile/testpost"; - private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; - private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; - public JwtAuthTest() { var url = ConfigurationManager.AppSettings["siteUrl"]; @@ -397,6 +396,18 @@ WHERE TabId IN (SELECT TabId FROM {objectQualifier}Tabs WHERE TabName='Activity LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.Unauthorized, result.StatusCode); } + + private static string DecodeBase64(string b64Str) + { + // fix Base64 string padding + var mod = b64Str.Length % 4; + if (mod != 0) + { + b64Str += new string('=', 4 - mod); + } + + return TextEncoder.GetString(Convert.FromBase64String(b64Str)); + } // template to help in copy/paste of new test methods /* @@ -451,18 +462,6 @@ private void SetMonikerHeader(string monikerValue) { this._httpClient.DefaultRequestHeaders.Add("X-DNN-MONIKER", monikerValue); } - - private static string DecodeBase64(string b64Str) - { - // fix Base64 string padding - var mod = b64Str.Length % 4; - if (mod != 0) - { - b64Str += new string('=', 4 - mod); - } - - return TextEncoder.GetString(Convert.FromBase64String(b64Str)); - } [JsonObject] public class LoginResultData diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs index ca18d472745..e0a5f425c9d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs @@ -41,12 +41,6 @@ public void Using_Logged_Out_Cookie_Should_Be_Unauthorized() Assert.IsFalse(result2.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.Unauthorized, result2.StatusCode); } - - private HttpResponseMessage SendDirectGetRequest(Uri domain, string path, TimeSpan timeout, CookieContainer cookies) - { - var client = CreateHttpClient(domain, timeout, cookies); - return client.GetAsync(path).Result; - } private static HttpClient CreateHttpClient(Uri domain, TimeSpan timeout, CookieContainer cookies) { @@ -64,5 +58,11 @@ private static HttpClient CreateHttpClient(Uri domain, TimeSpan timeout, CookieC return client; } + + private HttpResponseMessage SendDirectGetRequest(Uri domain, string path, TimeSpan timeout, CookieContainer cookies) + { + var client = CreateHttpClient(domain, timeout, cookies); + return client.GetAsync(path).Result; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs index e98e839ef8a..7934ca4ef15 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs @@ -25,15 +25,6 @@ public static string ErrorMessage } } - public class TestClass - { - [Required(ErrorMessage = "Dude, you forgot to enter a {0}")] - public object Foo { get; set; } - - [StringLength(5, ErrorMessageResourceName = "ErrorMessage", ErrorMessageResourceType = typeof(DataAnnotationsObjectValidatorTests))] - public string Bar { get; set; } - } - [Test] public void ValidateObject_Returns_Successful_Result_If_All_Attributes_On_All_Properties_Validate() { @@ -77,6 +68,15 @@ public void ValidateObject_Collects_Error_Messages_From_Validation_Attributes() Assert.AreEqual("Dude, you forgot to enter a Foo", result.Errors.Where(e => e.PropertyName == "Foo").Single().ErrorMessage); Assert.AreEqual("Yo, you have to specify 5 characters for Bar", result.Errors.Where(e => e.PropertyName == "Bar").Single().ErrorMessage); } + + public class TestClass + { + [Required(ErrorMessage = "Dude, you forgot to enter a {0}")] + public object Foo { get; set; } + + [StringLength(5, ErrorMessageResourceName = "ErrorMessage", ErrorMessageResourceType = typeof(DataAnnotationsObjectValidatorTests))] + public string Bar { get; set; } + } [Test] public void ValidateObject_Collects_ValidationAttribute_Objects_From_Failed_Validation() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs index ec30575a7bb..6e25f1e4ea9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs @@ -24,8 +24,8 @@ namespace DotNetNuke.Tests.Urls public class FriendlyUrlTests : UrlTestBase { private const string _defaultPage = Globals.glbDefaultPage; - private int _tabId; private const string _aboutUsPageName = "About Us"; + private int _tabId; private string _redirectMode; private Locale _customLocale; private PortalAliasInfo _primaryAlias; @@ -70,11 +70,11 @@ public override void TestFixtureSetUp() var alias = aliasController.GetPortalAlias(fields[0], this.PortalId); if (alias == null) { - alias = new PortalAliasInfo - { - HTTPAlias = fields[0], - PortalID = this.PortalId, - }; + alias = new PortalAliasInfo + { + HTTPAlias = fields[0], + PortalID = this.PortalId, + }; PortalAliasController.Instance.AddPortalAlias(alias); } }); @@ -133,6 +133,20 @@ public override void TestFixtureTearDown() }); } + [Test] + [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_BaseTestCases")] + public void AdvancedUrlProvider_BaseFriendlyUrl(Dictionary testFields) + { + this.ExecuteTest("Base", testFields); + } + + [Test] + [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_ImprovedTestCases")] + public void AdvancedUrlProvider_ImprovedFriendlyUrl(Dictionary testFields) + { + this.ExecuteTest("Improved", testFields); + } + private void ExecuteTest(string test, Dictionary testFields) { var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); @@ -221,20 +235,6 @@ private void UpdateTabName(int tabId, string newName) tab.TabName = newName; TabController.Instance.UpdateTab(tab); } - - [Test] - [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_BaseTestCases")] - public void AdvancedUrlProvider_BaseFriendlyUrl(Dictionary testFields) - { - this.ExecuteTest("Base", testFields); - } - - [Test] - [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_ImprovedTestCases")] - public void AdvancedUrlProvider_ImprovedFriendlyUrl(Dictionary testFields) - { - this.ExecuteTest("Improved", testFields); - } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_SpaceEncodingTestCases")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs index 3a9ab357fd0..334299063ec 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs @@ -14,6 +14,22 @@ namespace DotNetNuke.Tests.Urls public class TestUtil { + internal static string EmbeddedFilePath + { + get { return "DotNetNuke.Tests.Urls.TestFiles"; } + } + + internal static string FilePath + { + get + { + var uri = new System.Uri(Assembly.GetExecutingAssembly().CodeBase); + string path = Path.GetFullPath(uri.AbsolutePath).Replace("%20", " "); + + return Path.Combine(path.Substring(0, path.IndexOf("bin", System.StringComparison.Ordinal)), "TestFiles"); + } + } + internal static void AddUser(int portalId, string userName, string password, string vanityUrl) { var user = UserController.GetUserByName(portalId, userName); @@ -47,22 +63,6 @@ internal static void DeleteUser(int portalId, string userName) UserController.RemoveUser(user); } } - - internal static string EmbeddedFilePath - { - get { return "DotNetNuke.Tests.Urls.TestFiles"; } - } - - internal static string FilePath - { - get - { - var uri = new System.Uri(Assembly.GetExecutingAssembly().CodeBase); - string path = Path.GetFullPath(uri.AbsolutePath).Replace("%20", " "); - - return Path.Combine(path.Substring(0, path.IndexOf("bin", System.StringComparison.Ordinal)), "TestFiles"); - } - } internal static string GetEmbeddedFileName(string fileName) { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs index 075dbe511c6..d706c937253 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs @@ -27,9 +27,9 @@ namespace DotNetNuke.Tests.Urls public class UrlRewriteTests : UrlTestBase { private const string _defaultPage = Globals.glbDefaultPage; - private int _tabId; private const string _testPage = "Test Page"; private const string _aboutUsPageName = "About Us"; + private int _tabId; private string _redirectMode; private Locale _customLocale; private string _securePageName; @@ -42,57 +42,6 @@ public UrlRewriteTests() { } - private void CreateSimulatedRequest(Uri url) - { - var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", this.WebsitePhysicalAppPath); - simulator.SimulateRequest(url); - - var browserCaps = new HttpBrowserCapabilities { Capabilities = new Hashtable() }; - HttpContext.Current.Request.Browser = browserCaps; - } - - private void ProcessRequest(FriendlyUrlSettings settings, UrlTestHelper testHelper) - { - var provider = new AdvancedUrlRewriter(); - - provider.ProcessTestRequestWithContext( - HttpContext.Current, - HttpContext.Current.Request.Url, - true, - testHelper.Result, - settings); - testHelper.Response = HttpContext.Current.Response; - } - - private string ReplaceTokens(Dictionary testFields, string url, string tabId) - { - var defaultAlias = testFields.GetValue("DefaultAlias", string.Empty); - var httpAlias = testFields.GetValue("Alias", string.Empty); - var tabName = testFields["Page Name"]; - var vanityUrl = testFields.GetValue("VanityUrl", string.Empty); - var homeTabId = testFields.GetValue("HomeTabId", string.Empty); - - var userName = testFields.GetValue("UserName", string.Empty); - string userId = string.Empty; - if (!string.IsNullOrEmpty(userName)) - { - var user = UserController.GetUserByName(this.PortalId, userName); - if (user != null) - { - userId = user.UserID.ToString(); - } - } - - return url.Replace("{alias}", httpAlias) - .Replace("{usealias}", defaultAlias) - .Replace("{tabName}", tabName) - .Replace("{tabId}", tabId) - .Replace("{portalId}", this.PortalId.ToString()) - .Replace("{vanityUrl}", vanityUrl) - .Replace("{userId}", userId) - .Replace("{defaultPage}", _defaultPage); - } - [SetUp] public override void SetUp() { @@ -101,7 +50,7 @@ public override void SetUp() this.DeleteTab(_testPage); this.CreateTab(_testPage); this.UpdateTabName(this._tabId, "About Us"); - this.UpdateTabSkin(this._tabId, string.Empty); + this.UpdateTabSkin(this._tabId, string.Empty); CacheController.FlushPageIndexFromCache(); this.GetDefaultAlias(); this._redirectMode = PortalController.GetPortalSetting("PortalAliasMapping", this.PortalId, "CANONICALURL"); @@ -153,6 +102,57 @@ public override void TearDown() TabController.Instance.DeleteTabUrl(tabUrl, this.PortalId, true); } } + + private void CreateSimulatedRequest(Uri url) + { + var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator("/", this.WebsitePhysicalAppPath); + simulator.SimulateRequest(url); + + var browserCaps = new HttpBrowserCapabilities { Capabilities = new Hashtable() }; + HttpContext.Current.Request.Browser = browserCaps; + } + + private void ProcessRequest(FriendlyUrlSettings settings, UrlTestHelper testHelper) + { + var provider = new AdvancedUrlRewriter(); + + provider.ProcessTestRequestWithContext( + HttpContext.Current, + HttpContext.Current.Request.Url, + true, + testHelper.Result, + settings); + testHelper.Response = HttpContext.Current.Response; + } + + private string ReplaceTokens(Dictionary testFields, string url, string tabId) + { + var defaultAlias = testFields.GetValue("DefaultAlias", string.Empty); + var httpAlias = testFields.GetValue("Alias", string.Empty); + var tabName = testFields["Page Name"]; + var vanityUrl = testFields.GetValue("VanityUrl", string.Empty); + var homeTabId = testFields.GetValue("HomeTabId", string.Empty); + + var userName = testFields.GetValue("UserName", string.Empty); + string userId = string.Empty; + if (!string.IsNullOrEmpty(userName)) + { + var user = UserController.GetUserByName(this.PortalId, userName); + if (user != null) + { + userId = user.UserID.ToString(); + } + } + + return url.Replace("{alias}", httpAlias) + .Replace("{usealias}", defaultAlias) + .Replace("{tabName}", tabName) + .Replace("{tabId}", tabId) + .Replace("{portalId}", this.PortalId.ToString()) + .Replace("{vanityUrl}", vanityUrl) + .Replace("{userId}", userId) + .Replace("{defaultPage}", _defaultPage); + } [TestFixtureSetUp] public override void TestFixtureSetUp() @@ -212,6 +212,60 @@ public override void TestFixtureTearDown() }); } + [Test] + [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_BasicTestCases")] + public void AdvancedUrlRewriter_BasicTest(Dictionary testFields) + { + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); + + this.ExecuteTest(settings, testFields, true); + } + + [Test] + [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_DeletedTabHandlingTestCases")] + public void AdvancedUrlRewriter_DeletedTabHandling(Dictionary testFields) + { + var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); + + var tab = TabController.Instance.GetTabByName(_testPage, this.PortalId); + if (Convert.ToBoolean(testFields["HardDeleted"])) + { + this.DeleteTab(_testPage); + CacheController.FlushPageIndexFromCache(); + } + else + { + tab.IsDeleted = Convert.ToBoolean(testFields["SoftDeleted"]); + tab.DisableLink = Convert.ToBoolean(testFields["Disabled"]); + if (Convert.ToBoolean(testFields["Expired"])) + { + tab.EndDate = DateTime.Now - TimeSpan.FromDays(1); + } + + this.UpdateTab(tab); + CacheController.FlushPageIndexFromCache(); + } + + string deletedTabHandling = testFields.GetValue("DeletedTabHandling"); + + if (!string.IsNullOrEmpty(deletedTabHandling)) + { + switch (deletedTabHandling) + { + case "Do404Error": + settings.DeletedTabHandlingType = DeletedTabHandlingType.Do404Error; + break; + default: + settings.DeletedTabHandlingType = DeletedTabHandlingType.Do301RedirectToPortalHome; + break; + } + } + + this.SetDefaultAlias(testFields); + + this.ExecuteTest(settings, testFields, true); + } + private void DeleteTab(string tabName) { var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); @@ -241,17 +295,17 @@ private void ExecuteTestForTab(TabInfo tab, FriendlyUrlSettings settings, Dictio this.CreateSimulatedRequest(new Uri(testurl)); var request = HttpContext.Current.Request; - var testHelper = new UrlTestHelper - { - HttpAliasFull = scheme + httpAlias + "/", - Result = new UrlAction(request) - { - IsSecureConnection = request.IsSecureConnection, - RawUrl = request.RawUrl, - }, - RequestUri = new Uri(testurl), - QueryStringCol = new NameValueCollection(), - }; + var testHelper = new UrlTestHelper + { + HttpAliasFull = scheme + httpAlias + "/", + Result = new UrlAction(request) + { + IsSecureConnection = request.IsSecureConnection, + RawUrl = request.RawUrl, + }, + RequestUri = new Uri(testurl), + QueryStringCol = new NameValueCollection(), + }; this.ProcessRequest(settings, testHelper); @@ -311,60 +365,6 @@ private void UpdateTabSkin(int tabId, string newSkin) tab.SkinSrc = newSkin; TabController.Instance.UpdateTab(tab); } - - [Test] - [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_BasicTestCases")] - public void AdvancedUrlRewriter_BasicTest(Dictionary testFields) - { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); - - this.ExecuteTest(settings, testFields, true); - } - - [Test] - [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_DeletedTabHandlingTestCases")] - public void AdvancedUrlRewriter_DeletedTabHandling(Dictionary testFields) - { - var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"], this.PortalId); - - var tab = TabController.Instance.GetTabByName(_testPage, this.PortalId); - if (Convert.ToBoolean(testFields["HardDeleted"])) - { - this.DeleteTab(_testPage); - CacheController.FlushPageIndexFromCache(); - } - else - { - tab.IsDeleted = Convert.ToBoolean(testFields["SoftDeleted"]); - tab.DisableLink = Convert.ToBoolean(testFields["Disabled"]); - if (Convert.ToBoolean(testFields["Expired"])) - { - tab.EndDate = DateTime.Now - TimeSpan.FromDays(1); - } - - this.UpdateTab(tab); - CacheController.FlushPageIndexFromCache(); - } - - string deletedTabHandling = testFields.GetValue("DeletedTabHandling"); - - if (!string.IsNullOrEmpty(deletedTabHandling)) - { - switch (deletedTabHandling) - { - case "Do404Error": - settings.DeletedTabHandlingType = DeletedTabHandlingType.Do404Error; - break; - default: - settings.DeletedTabHandlingType = DeletedTabHandlingType.Do301RedirectToPortalHome; - break; - } - } - - this.SetDefaultAlias(testFields); - - this.ExecuteTest(settings, testFields, true); - } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_DoNotRedirect")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs index 77c9183dd2d..10c0b8c5496 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs @@ -55,22 +55,6 @@ protected void CreateTab(string tabName) TabController.Instance.AddTab(tab); } - private void ExecuteScriptFile(string fileName) - { - var sql = TestUtil.ReadStream(fileName); - - if (!string.IsNullOrEmpty(sql)) - { - DataProvider.Instance().ExecuteScript(sql); - } - } - - private string GetTestFolder() - { - var testName = TestContext.CurrentContext.Test.Name; - return testName.Substring(0, testName.IndexOf("_", StringComparison.Ordinal)); - } - protected void GetDefaultAlias() { foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId)) @@ -88,6 +72,22 @@ protected void SetDefaultAlias(Dictionary testFields) this.SetDefaultAlias(testFields["Alias"]); } + private void ExecuteScriptFile(string fileName) + { + var sql = TestUtil.ReadStream(fileName); + + if (!string.IsNullOrEmpty(sql)) + { + DataProvider.Instance().ExecuteScript(sql); + } + } + + private string GetTestFolder() + { + var testName = TestContext.CurrentContext.Test.Name; + return testName.Substring(0, testName.IndexOf("_", StringComparison.Ordinal)); + } + protected void SetDefaultAlias(string defaultAlias) { foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId)) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs index 2ba5384b87e..0fc4b40a55a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs @@ -13,56 +13,40 @@ namespace DotNetNuke.Tests.Urls internal static class UrlTestFactoryClass { - private static void GetTestsWithAliases(string testType, string testName, ArrayList testData) + internal static IEnumerable FriendlyUrl_BaseTestCases { - TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => + get { - string[] fields = line.Split(','); - GetTests(fields[1].Trim(), fields[0].Trim(), testType, testName, testData); - }); + var testData = new ArrayList(); + + TestUtil.ReadStream("FriendlyUrl\\BaseTestList", (line, header) => GetTestsWithAliases("FriendlyUrl", line, testData)); + + return testData; + } } - private static void GetTests(string testPrefix, string alias, string testType, string testName, ArrayList testData) + internal static IEnumerable FriendlyUrl_ForceLowerCaseTestCases { - try + get { - // Read Test File Data - TestUtil.ReadStream(string.Format("{0}\\{1}\\{2}", testType, testName, "TestFile"), (line, header) => - { - var fieldList = new Dictionary(); - fieldList["TestName"] = testName; - fieldList["Alias"] = alias; - string[] headers = header.Split(','); - string[] fields = line.Split(','); - for (int i = 0; i < fields.Length; i++) - { - string key = headers[i].Trim(new[] { '\t', '"' }); - string val = fields[i].Trim(new[] { '\t', '"' }); + var testData = new ArrayList(); - fieldList[key] = val; - } + GetTestsWithAliases("FriendlyUrl", "ForceLowerCase", testData); - string name = testName + "_"; - if (!string.IsNullOrEmpty(testPrefix)) - { - name += testPrefix + "_"; - } - - name += fields[0]; + return testData; + } + } - testData.Add(new TestCaseData(fieldList).SetName(name)); - }); - } - - // ReSharper disable RedundantCatchClause - #pragma warning disable 168 - catch (Exception exc) - #pragma warning restore 168 + internal static IEnumerable FriendlyUrl_ImprovedTestCases + { + get { - throw; + var testData = new ArrayList(); + + TestUtil.ReadStream("FriendlyUrl\\ImprovedTestList", (line, header) => GetTestsWithAliases("FriendlyUrl", line, testData)); + + return testData; } - - // ReSharper restore RedundantCatchClause } internal static FriendlyUrlSettings GetSettings(string testType, string testName, int portalId) @@ -105,57 +89,73 @@ internal static FriendlyUrlSettings GetSettings(string testType, string testName }); return settings; } - - internal static Dictionary GetDictionary(string testType, string testName, string settingsFile) + + private static void GetTestsWithAliases(string testType, string testName, ArrayList testData) { - var dictionary = new Dictionary(); - - // Read Test Settings - TestUtil.ReadStream(string.Format("{0}\\{1}\\{2}", testType, testName, settingsFile), (line, header) => + TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => { string[] fields = line.Split(','); - string key = fields[0].Trim(); - string value = fields[1].Trim(); - - dictionary.Add(key, value); + GetTests(fields[1].Trim(), fields[0].Trim(), testType, testName, testData); }); - return dictionary; } - internal static IEnumerable FriendlyUrl_BaseTestCases + private static void GetTests(string testPrefix, string alias, string testType, string testName, ArrayList testData) { - get + try { - var testData = new ArrayList(); + // Read Test File Data + TestUtil.ReadStream(string.Format("{0}\\{1}\\{2}", testType, testName, "TestFile"), (line, header) => + { + var fieldList = new Dictionary(); + fieldList["TestName"] = testName; + fieldList["Alias"] = alias; + string[] headers = header.Split(','); + string[] fields = line.Split(','); + for (int i = 0; i < fields.Length; i++) + { + string key = headers[i].Trim(new[] { '\t', '"' }); + string val = fields[i].Trim(new[] { '\t', '"' }); - TestUtil.ReadStream("FriendlyUrl\\BaseTestList", (line, header) => GetTestsWithAliases("FriendlyUrl", line, testData)); + fieldList[key] = val; + } - return testData; - } - } + string name = testName + "_"; + if (!string.IsNullOrEmpty(testPrefix)) + { + name += testPrefix + "_"; + } + + name += fields[0]; - internal static IEnumerable FriendlyUrl_ForceLowerCaseTestCases - { - get + testData.Add(new TestCaseData(fieldList).SetName(name)); + }); + } + + // ReSharper disable RedundantCatchClause +#pragma warning disable 168 + catch (Exception exc) +#pragma warning restore 168 { - var testData = new ArrayList(); - - GetTestsWithAliases("FriendlyUrl", "ForceLowerCase", testData); - - return testData; + throw; } + + // ReSharper restore RedundantCatchClause } - internal static IEnumerable FriendlyUrl_ImprovedTestCases + internal static Dictionary GetDictionary(string testType, string testName, string settingsFile) { - get - { - var testData = new ArrayList(); + var dictionary = new Dictionary(); - TestUtil.ReadStream("FriendlyUrl\\ImprovedTestList", (line, header) => GetTestsWithAliases("FriendlyUrl", line, testData)); + // Read Test Settings + TestUtil.ReadStream(string.Format("{0}\\{1}\\{2}", testType, testName, settingsFile), (line, header) => + { + string[] fields = line.Split(','); + string key = fields[0].Trim(); + string value = fields[1].Trim(); - return testData; - } + dictionary.Add(key, value); + }); + return dictionary; } internal static IEnumerable FriendlyUrl_PageExtensionTestCases diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs index 639629a4c4e..090b0467461 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs @@ -46,14 +46,14 @@ public static Term CreateValidSimpleTerm(int vocabularyId) public static Vocabulary CreateValidVocabulary() { - Vocabulary vocabulary = new Vocabulary - { - Name = Constants.VOCABULARY_ValidName, - Type = Constants.VOCABULARY_ValidType, - ScopeTypeId = Constants.VOCABULARY_ValidScopeTypeId, - ScopeId = Constants.VOCABULARY_ValidScopeId, - Weight = Constants.VOCABULARY_ValidWeight, - }; + Vocabulary vocabulary = new Vocabulary + { + Name = Constants.VOCABULARY_ValidName, + Type = Constants.VOCABULARY_ValidType, + ScopeTypeId = Constants.VOCABULARY_ValidScopeTypeId, + ScopeId = Constants.VOCABULARY_ValidScopeId, + Weight = Constants.VOCABULARY_ValidWeight, + }; return vocabulary; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs index 7a583d6c5d5..5e2eb43bef3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs @@ -37,8 +37,6 @@ namespace DotNetNuke.Tests.Utilities public class DnnWebTest : DnnUnitTest { - public int PortalId { get; private set; } - private static bool alreadyLoaded = false; public DnnWebTest(int portalId) @@ -75,6 +73,8 @@ public DnnWebTest(int portalId) this.PortalId = portalId; } + + public int PortalId { get; private set; } private static void InstallComponents() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs index 688a5f88703..3f99fec9bc0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs @@ -14,6 +14,20 @@ namespace DotNetNuke.Tests.Utilities public class HttpContextHelper { + /// + /// Return Response object with default values for missing ones + /// _mockRequest = Mock.Get(_mockhttpContext.Object.Request); + /// syntax _mockRequest.SetupGet(x => x.[PropertyName]).Returns(...); + /// e.g. SetupGet(x => x.ServerVariables).Returns(new NameValueCollection()). + /// + /// HttpResponseBase. + public static Mock RegisterMockHttpContext() + { + var mock = CrateMockHttpContext(); + HttpContextSource.RegisterInstance(mock.Object); + return mock; + } + private static Mock CrateMockHttpContext() { var context = new Mock(); @@ -60,19 +74,5 @@ private static HttpRequestBase GetMockRequestBase() request.SetupGet(x => x.UserLanguages).Returns(new[] { string.Empty }); return request.Object; } - - /// - /// Return Response object with default values for missing ones - /// _mockRequest = Mock.Get(_mockhttpContext.Object.Request); - /// syntax _mockRequest.SetupGet(x => x.[PropertyName]).Returns(...); - /// e.g. SetupGet(x => x.ServerVariables).Returns(new NameValueCollection()). - /// - /// HttpResponseBase. - public static Mock RegisterMockHttpContext() - { - var mock = CrateMockHttpContext(); - HttpContextSource.RegisterInstance(mock.Object); - return mock; - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs index 06b31fe242f..df689d674aa 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs @@ -38,6 +38,12 @@ public class HttpSimulator : IDisposable private readonly NameValueCollection _formVars = new NameValueCollection(); private readonly NameValueCollection _headers = new NameValueCollection(); + private string _applicationPath = "/"; + + private string _physicalApplicationPath = WebsitePhysicalAppPath; + + private string _physicalPath = WebsitePhysicalAppPath; + public HttpSimulator() : this("/", WebsitePhysicalAppPath) { @@ -54,6 +60,12 @@ public HttpSimulator(string applicationPath, string physicalApplicationPath) this.PhysicalApplicationPath = physicalApplicationPath; } + public string Host { get; private set; } + + public string LocalPath { get; private set; } + + public int Port { get; private set; } + /// /// Sets up the HttpContext objects to simulate a GET request. /// @@ -122,6 +134,58 @@ public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollec return this.SimulateRequest(url, httpVerb, null, headers); } + /// + /// Sets the referer for the request. Uses a fluent interface. + /// + /// + /// + public HttpSimulator SetReferer(Uri referer) + { + if (this.WorkerRequest != null) + { + this.WorkerRequest.SetReferer(referer); + } + + this._referer = referer; + return this; + } + + /// + /// Sets a form variable. + /// + /// + /// + /// + public HttpSimulator SetFormVariable(string name, string value) + { + if (this.WorkerRequest != null) + { + throw new InvalidOperationException("Cannot set form variables after calling Simulate()."); + } + + this._formVars.Add(name, value); + + return this; + } + + /// + /// Sets a header value. + /// + /// + /// + /// + public HttpSimulator SetHeader(string name, string value) + { + if (this.WorkerRequest != null) + { + throw new InvalidOperationException("Cannot set headers after calling Simulate()."); + } + + this._headers.Add(name, value); + + return this; + } + /// /// Sets up the HttpContext objects to simulate a request. /// @@ -217,12 +281,52 @@ private void InitializeSession() public class FakeHttpSessionState : NameObjectCollectionBase, IHttpSessionState { + private const bool _isNewSession = true; private readonly string _sessionId = Guid.NewGuid().ToString(); private int _timeout = 30; // minutes - private const bool _isNewSession = true; private readonly HttpStaticObjectsCollection _staticObjects = new HttpStaticObjectsCollection(); private readonly object _syncRoot = new object(); + /// + /// Gets the unique session identifier for the session. + /// + /// + /// + /// The session ID. + /// + /// + public string SessionID + { + get { return this._sessionId; } + } + + /// + /// Gets or sets and sets the time-out period (in minutes) allowed between requests before the session-state provider terminates the session. + /// + /// + /// + /// The time-out period, in minutes. + /// + /// + public int Timeout + { + get { return this._timeout; } + set { this._timeout = value; } + } + + /// + /// Gets a value indicating whether the session was created with the current request. + /// + /// + /// + /// true if the session was created with the current request; otherwise, false. + /// + /// + public bool IsNewSession + { + get { return _isNewSession; } + } + /// /// Ends the current session. /// @@ -292,46 +396,6 @@ public void CopyTo(Array array, int index) throw new NotImplementedException(); } - /// - /// Gets the unique session identifier for the session. - /// - /// - /// - /// The session ID. - /// - /// - public string SessionID - { - get { return this._sessionId; } - } - - /// - /// Gets or sets and sets the time-out period (in minutes) allowed between requests before the session-state provider terminates the session. - /// - /// - /// - /// The time-out period, in minutes. - /// - /// - public int Timeout - { - get { return this._timeout; } - set { this._timeout = value; } - } - - /// - /// Gets a value indicating whether the session was created with the current request. - /// - /// - /// - /// true if the session was created with the current request; otherwise, false. - /// - /// - public bool IsNewSession - { - get { return _isNewSession; } - } - /// /// Gets the current session-state mode. /// @@ -404,36 +468,6 @@ public HttpStaticObjectsCollection StaticObjects get { return this._staticObjects; } } - /// - /// Gets or sets a session-state item value by name. - /// - /// - /// - /// The session-state item value specified in the name parameter. - /// - /// - /// The key name of the session-state item value. - public object this[string name] - { - get { return this.BaseGet(name); } - set { this.BaseSet(name, value); } - } - - /// - /// Gets or sets a session-state item value by numerical index. - /// - /// - /// - /// The session-state item value specified in the index parameter. - /// - /// - /// The numerical index of the session-state item value. - public object this[int index] - { - get { return this.BaseGet(index); } - set { this.BaseSet(index, value); } - } - /// /// Gets an object that can be used to synchronize access to the collection of session-state values. /// @@ -474,72 +508,36 @@ bool IHttpSessionState.IsReadOnly return true; } } - } - - /// - /// Sets the referer for the request. Uses a fluent interface. - /// - /// - /// - public HttpSimulator SetReferer(Uri referer) - { - if (this.WorkerRequest != null) - { - this.WorkerRequest.SetReferer(referer); - } - - this._referer = referer; - return this; - } - - /// - /// Sets a form variable. - /// - /// - /// - /// - public HttpSimulator SetFormVariable(string name, string value) - { - if (this.WorkerRequest != null) - { - throw new InvalidOperationException("Cannot set form variables after calling Simulate()."); - } - - this._formVars.Add(name, value); - - return this; - } - /// - /// Sets a header value. - /// - /// - /// - /// - public HttpSimulator SetHeader(string name, string value) - { - if (this.WorkerRequest != null) - { - throw new InvalidOperationException("Cannot set headers after calling Simulate()."); - } - - this._headers.Add(name, value); - - return this; - } + /// + /// Gets or sets a session-state item value by name. + /// + /// + /// + /// The session-state item value specified in the name parameter. + /// + /// + /// The key name of the session-state item value. + public object this[string name] + { + get { return this.BaseGet(name); } + set { this.BaseSet(name, value); } + } - private void ParseRequestUrl(Uri url) - { - if (url == null) - { - return; - } - - this.Host = url.Host; - this.Port = url.Port; - this.LocalPath = url.LocalPath; - this.Page = StripPrecedingSlashes(RightAfter(url.LocalPath, this.ApplicationPath)); - this._physicalPath = Path.Combine(this._physicalApplicationPath, this.Page.Replace("/", @"\")); + /// + /// Gets or sets a session-state item value by numerical index. + /// + /// + /// + /// The session-state item value specified in the index parameter. + /// + /// + /// The numerical index of the session-state item value. + public object this[int index] + { + get { return this.BaseGet(index); } + set { this.BaseSet(index, value); } + } } private static string RightAfter(string original, string search) @@ -569,19 +567,25 @@ private static string RightAfter(string original, string search) return result; } - public string Host { get; private set; } - - public string LocalPath { get; private set; } - - public int Port { get; private set; } + private void ParseRequestUrl(Uri url) + { + if (url == null) + { + return; + } + + this.Host = url.Host; + this.Port = url.Port; + this.LocalPath = url.LocalPath; + this.Page = StripPrecedingSlashes(RightAfter(url.LocalPath, this.ApplicationPath)); + this._physicalPath = Path.Combine(this._physicalApplicationPath, this.Page.Replace("/", @"\")); + } /// /// Gets portion of the URL after the application. /// public string Page { get; private set; } - private string _applicationPath = "/"; - /// /// Gets or sets the same thing as the IIS Virtual directory. It's /// what gets returned by Request.ApplicationPath. @@ -597,8 +601,6 @@ public string ApplicationPath } } - private string _physicalApplicationPath = WebsitePhysicalAppPath; - /// /// Gets or sets physical path to the application (used for simulation purposes). /// @@ -615,8 +617,6 @@ public string PhysicalApplicationPath } } - private string _physicalPath = WebsitePhysicalAppPath; - /// /// Gets physical path to the requested file (used for simulation purposes). /// @@ -640,34 +640,13 @@ public string ResponseText public SimulatedHttpRequest WorkerRequest { get; private set; } - private static string ExtractQueryStringPart(Uri url) - { - var query = url.Query; - return query.StartsWith("?") ? query.Substring(1) : query; - } - - private void SetHttpRuntimeInternals() + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + /// 2. + public void Dispose() { - // We cheat by using reflection. - - // get singleton property value - var runtime = ReflectionHelper.GetStaticFieldValue("_theRuntime", typeof(HttpRuntime)); - - // set app path property value - ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppPath", runtime, this.PhysicalApplicationPath); - - // set app virtual path property value - const string vpathTypeName = "System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; - var virtualPath = ReflectionHelper.Instantiate(vpathTypeName, new[] { typeof(string) }, new object[] { this.ApplicationPath }); - ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppVPath", runtime, virtualPath); - - // set codegen dir property value - ReflectionHelper.SetPrivateInstanceFieldValue("_codegenDir", runtime, this.PhysicalApplicationPath); - - var environment = GetHostingEnvironment(); - ReflectionHelper.SetPrivateInstanceFieldValue("_appPhysicalPath", environment, this.PhysicalApplicationPath); - ReflectionHelper.SetPrivateInstanceFieldValue("_appVirtualPath", environment, virtualPath); - ReflectionHelper.SetPrivateInstanceFieldValue("_configMapPath", environment, new ConfigMapPath(this)); + HttpContext.Current = null; } protected static HostingEnvironment GetHostingEnvironment() @@ -706,6 +685,36 @@ protected static string NormalizeSlashes(string s) return "/" + normalized; } + private static string ExtractQueryStringPart(Uri url) + { + var query = url.Query; + return query.StartsWith("?") ? query.Substring(1) : query; + } + + private void SetHttpRuntimeInternals() + { + // We cheat by using reflection. + + // get singleton property value + var runtime = ReflectionHelper.GetStaticFieldValue("_theRuntime", typeof(HttpRuntime)); + + // set app path property value + ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppPath", runtime, this.PhysicalApplicationPath); + + // set app virtual path property value + const string vpathTypeName = "System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; + var virtualPath = ReflectionHelper.Instantiate(vpathTypeName, new[] { typeof(string) }, new object[] { this.ApplicationPath }); + ReflectionHelper.SetPrivateInstanceFieldValue("_appDomainAppVPath", runtime, virtualPath); + + // set codegen dir property value + ReflectionHelper.SetPrivateInstanceFieldValue("_codegenDir", runtime, this.PhysicalApplicationPath); + + var environment = GetHostingEnvironment(); + ReflectionHelper.SetPrivateInstanceFieldValue("_appPhysicalPath", environment, this.PhysicalApplicationPath); + ReflectionHelper.SetPrivateInstanceFieldValue("_appVirtualPath", environment, virtualPath); + ReflectionHelper.SetPrivateInstanceFieldValue("_configMapPath", environment, new ConfigMapPath(this)); + } + protected static string StripPrecedingSlashes(string s) { return Regex.Replace(s, "^/*(.*)", "$1"); @@ -766,14 +775,5 @@ public string GetAppPathForPath(string siteId, string path) return this._requestSimulation.ApplicationPath; } } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - /// 2. - public void Dispose() - { - HttpContext.Current = null; - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs index 9a9fdc79881..b6e25611a57 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs @@ -16,31 +16,6 @@ namespace UnitTests.Subtext ////[TestFixture] public class HttpSimulatorTests { - internal class TestHttpHandler : IHttpHandler - { - public void ProcessRequest(HttpContext context) - { - var physicalPath = context.Request.MapPath("/MyHandler.ashx"); - var username = context.Request.Form["username"]; - var id = context.Request.QueryString["id"]; - if (context.Request.UrlReferrer == null) - { - return; - } - - var referer = context.Request.UrlReferrer.ToString(); - - // Imagine, if you will, a bunch of complex interesting - // and fascinating logic here. - context.Response.Write(physicalPath + ":" + username + ":" + id + ":" + referer); - } - - public bool IsReusable - { - get { return true; } - } - } - ////[Test] public void CanGetSetSession() { @@ -78,6 +53,31 @@ public void TestHttpHandlerWritesCorrectResponse() Assert.AreEqual(expected, simulator.ResponseText, "The Expected Response is all wrong."); } // HttpContext.Current is set to null again. } + + internal class TestHttpHandler : IHttpHandler + { + public bool IsReusable + { + get { return true; } + } + + public void ProcessRequest(HttpContext context) + { + var physicalPath = context.Request.MapPath("/MyHandler.ashx"); + var username = context.Request.Form["username"]; + var id = context.Request.QueryString["id"]; + if (context.Request.UrlReferrer == null) + { + return; + } + + var referer = context.Request.UrlReferrer.ToString(); + + // Imagine, if you will, a bunch of complex interesting + // and fascinating logic here. + context.Response.Write(physicalPath + ":" + username + ":" + id + ":" + referer); + } + } ////[Test] public void CanDispose() @@ -156,9 +156,9 @@ public void CanGetQueryString() Assert.AreEqual("param-name", HttpContext.Current.Request.QueryString.ToString()); Assert.AreEqual(1, HttpContext.Current.Request.QueryString.Count); Assert.IsNull(HttpContext.Current.Request.QueryString["param-name"]); - } - - // //[Test] + } + + // //[Test] public void CanSimulateFormPost() { using (var simulator = new HttpSimulator()) @@ -179,9 +179,9 @@ public void CanSimulateFormPost() Assert.AreEqual("Value1", HttpContext.Current.Request.Form["Test1"]); Assert.AreEqual("Value2", HttpContext.Current.Request.Form["Test2"]); } - } - - // //[Test] + } + + // //[Test] public void CanGetResponse() { var simulator = new HttpSimulator(); @@ -189,9 +189,9 @@ public void CanGetResponse() HttpContext.Current.Response.Write("Hello World!"); HttpContext.Current.Response.Flush(); Assert.AreEqual("Hello World!", simulator.ResponseText); - } - - // //[Test] + } + + // //[Test] public void CanGetReferer() { var simulator = new HttpSimulator(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs index 1be4559f7e7..106cba4bfc6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs @@ -61,10 +61,22 @@ public SimulatedHttpRequest(string applicationPath, string physicalAppPath, stri this._physicalFilePath = physicalFilePath; } - internal void SetReferer(Uri referer) - { - this._referer = referer; - } + // public override string GetProtocol() + // { + // return (_port == 443) ? "https:" : "http:"; + // } + + /// + /// Gets the headers. + /// + /// The headers. + public NameValueCollection Headers { get; private set; } + + /// + /// Gets the format exception. + /// + /// The format exception. + public NameValueCollection Form { get; private set; } /// /// Returns the specified member of the request header. @@ -87,6 +99,11 @@ public override string GetServerName() return this._host; } + internal void SetReferer(Uri referer) + { + this._referer = referer; + } + public override int GetLocalPort() { return this._port; @@ -97,23 +114,6 @@ public override bool IsSecure() return (this._port == 443) ? true : false; } - // public override string GetProtocol() - // { - // return (_port == 443) ? "https:" : "http:"; - // } - - /// - /// Gets the headers. - /// - /// The headers. - public NameValueCollection Headers { get; private set; } - - /// - /// Gets the format exception. - /// - /// The format exception. - public NameValueCollection Form { get; private set; } - /// /// Get all nonstandard HTTP header name-value pairs. /// diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs index ee0913eb82c..1af19ebfbb6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs @@ -13,6 +13,20 @@ namespace DotNetNuke.Tests.Utilities public static class MailAssert { + public static void Base64EncodedContentLineContains(string expectedValue, string toAddress, string findByText) + { + var contentLine = ConvertEmailContentFromBase64ToUnicode(GetEmailFileName(toAddress, findByText)); + + Assert.IsTrue(contentLine.Contains(expectedValue)); + } + + public static void ContentLineContains(string expectedValue, string toAddress, string findByText) + { + var contentLine = FindContentUsingRegex(expectedValue, GetEmailFileName(toAddress, findByText)); + + Assert.IsFalse(string.IsNullOrEmpty(contentLine)); + } + private static string ConvertEmailContentFromBase64ToUnicode(string emailFileName) { string emailContent = File.ReadAllText(emailFileName); @@ -86,20 +100,6 @@ private static string GetEmailFileName(string toAddress, string findByText, stri return emailFileName; } - - public static void Base64EncodedContentLineContains(string expectedValue, string toAddress, string findByText) - { - var contentLine = ConvertEmailContentFromBase64ToUnicode(GetEmailFileName(toAddress, findByText)); - - Assert.IsTrue(contentLine.Contains(expectedValue)); - } - - public static void ContentLineContains(string expectedValue, string toAddress, string findByText) - { - var contentLine = FindContentUsingRegex(expectedValue, GetEmailFileName(toAddress, findByText)); - - Assert.IsFalse(string.IsNullOrEmpty(contentLine)); - } public static void FromLineContains(string expectedValue, string toAddress, string findByText) { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnAuthorizeAttributeTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnAuthorizeAttributeTests.cs index d8b705797ad..c7bdeafdf68 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnAuthorizeAttributeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Attributes/DnnAuthorizeAttributeTests.cs @@ -117,29 +117,6 @@ public void RegisteredUser_IsAllowed_ByDefault() this._mockRepository.VerifyAll(); } - private UserInfo SetUpUserWithRole(string roleName) - { - var user = new UserInfo - { - UserID = 1, - PortalID = 1, - }; - - var roles = new List - { - new UserRoleInfo - { - RoleName = roleName, - Status = RoleStatus.Approved - }, - }; - - this._mockRoleController.Setup(x => x.GetUserRoles(user, true)).Returns(roles); - RoleController.SetTestableInstance(this._mockRoleController.Object); - - return user; - } - [Test] public void RegisteredUser_IsDenied_If_IncludedIn_DeniedRoles() { @@ -196,6 +173,29 @@ public void RegisteredUser_IsAllowed_If_IncludedIn_DeniedRoles_But_IsSuperUser() this._mockRepository.VerifyAll(); } + private UserInfo SetUpUserWithRole(string roleName) + { + var user = new UserInfo + { + UserID = 1, + PortalID = 1, + }; + + var roles = new List + { + new UserRoleInfo + { + RoleName = roleName, + Status = RoleStatus.Approved + }, + }; + + this._mockRoleController.Setup(x => x.GetUserRoles(user, true)).Returns(roles); + RoleController.SetTestableInstance(this._mockRoleController.Object); + + return user; + } + [Test] public void RegisteredUser_IsDenied_If_IncludedIn_StaticRoles() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs index 8269b8ab85c..f0cc2ae5171 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs @@ -23,10 +23,10 @@ public void InitHelpers_Sets_Dnn_Property() var mockViewPage = new Mock() { CallBase = true }; var mockController = new Mock(); var mockDnnController = mockController.As(); - var viewContext = new ViewContext - { - Controller = mockController.Object, - }; + var viewContext = new ViewContext + { + Controller = mockController.Object, + }; mockViewPage.Object.ViewContext = viewContext; // Act diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs index ea2d4d413c6..3d35584e2a1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs @@ -197,10 +197,10 @@ private static void SetupMockModuleApplication(ControllerContext context, ViewEn mockApp.Object.ViewEngines = engines; (context.Controller as IDnnController).ViewEngineCollectionEx = engines; - var activeModuleRequest = new ModuleRequestResult - { - ModuleApplication = mockApp.Object, - }; + var activeModuleRequest = new ModuleRequestResult + { + ModuleApplication = mockApp.Object, + }; context.HttpContext.SetModuleRequestResult(activeModuleRequest); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleApplicationTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleApplicationTests.cs index ae020ced7ba..44ad62612f0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleApplicationTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleApplicationTests.cs @@ -246,12 +246,12 @@ private static ModuleRequestContext CreateModuleContext(string controllerName, s routeData.Values.Add("action", actionName); var moduleContext = new ModuleInstanceContext { Configuration = new ModuleInfo { ModuleID = 42 } }; - return new ModuleRequestContext - { - HttpContext = MockHelper.CreateMockHttpContext("http://localhost/Portal/Page/ModuleRoute"), - RouteData = routeData, - ModuleContext = moduleContext, - }; + return new ModuleRequestContext + { + HttpContext = MockHelper.CreateMockHttpContext("http://localhost/Portal/Page/ModuleRoute"), + RouteData = routeData, + ModuleContext = moduleContext, + }; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleExecutionEngineTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleExecutionEngineTests.cs index 6c15b36c972..de56ea753e5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleExecutionEngineTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/Modules/ModuleExecutionEngineTests.cs @@ -90,11 +90,11 @@ public void ExecuteModuleResult_Calls_IDnnViewResult_ExecuteResult() var viewResultMock = actionResultMock.As(); var controllerContext = MockHelper.CreateMockControllerContext(); - var moduleRequestResult = new ModuleRequestResult - { - ActionResult = actionResultMock.Object, - ControllerContext = controllerContext, - }; + var moduleRequestResult = new ModuleRequestResult + { + ActionResult = actionResultMock.Object, + ControllerContext = controllerContext, + }; // Act engine.ExecuteModuleResult(moduleRequestResult, new StringWriter()); @@ -114,11 +114,11 @@ public void ExecuteModuleResult_Calls_IDnnViewResult_ExecuteResult_With_ModuleRe var viewResultMock = actionResultMock.As(); var controllerContext = MockHelper.CreateMockControllerContext(); - var moduleRequestResult = new ModuleRequestResult - { - ActionResult = actionResultMock.Object, - ControllerContext = controllerContext, - }; + var moduleRequestResult = new ModuleRequestResult + { + ActionResult = actionResultMock.Object, + ControllerContext = controllerContext, + }; // Act engine.ExecuteModuleResult(moduleRequestResult, new StringWriter()); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs index e23a61be705..74bf3ab3cda 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs @@ -34,8 +34,8 @@ public void SetsWwwAuthenticateHeaderOn401() public void OmitsWwwAuthenticateHeaderOn401FromXmlHttpRequest() { // Arrange - var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) - { RequestMessage = new HttpRequestMessage() }; + var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) + { RequestMessage = new HttpRequestMessage() }; response.RequestMessage.Headers.Add("X-REQUESTED-WITH", "XmlHttpRequest"); // Act diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs index 47eb84535b2..5272f04399c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs @@ -19,10 +19,6 @@ namespace DotNetNuke.Tests.Web.Api [TestFixture] public class DnnApiControllerTests { - internal class DnnApiControllerHelper : DnnApiController - { - } - [TearDown] public void TearDown() { @@ -67,27 +63,31 @@ public void GetsPortalSettingsViaTestablePortalController() // Assert mockPortalController.Verify(x => x.GetCurrentPortalSettings(), Times.Once()); Assert.AreEqual(expectedPortalSettings, result); - } - - // A test that would be nice to run, but I see not good way to test the source of the - // userinfo -// [Test] -// public void UserInfoComesFromPortalSettings() -// { -// //Arrange -// var controller = new DnnApiControllerHelper(); -// var mockPortalController = new Mock(); -// var expectedPortalSettings = new PortalSettings(); - // expectedPortalSettings.UserInfo = ?????? -// mockPortalController.Setup(x => x.GetCurrentPortalSettings()).Returns(expectedPortalSettings); -// TestablePortalController.SetTestableInstance(mockPortalController.Object); -// -// //Act -// var result = controller.PortalSettings; -// -// //Assert -// mockPortalController.Verify(x => x.GetCurrentPortalSettings(), Times.Once()); -// Assert.AreEqual(expectedPortalSettings, result); -// } + } + + internal class DnnApiControllerHelper : DnnApiController + { + } + + // A test that would be nice to run, but I see not good way to test the source of the + // userinfo + // [Test] + // public void UserInfoComesFromPortalSettings() + // { + // //Arrange + // var controller = new DnnApiControllerHelper(); + // var mockPortalController = new Mock(); + // var expectedPortalSettings = new PortalSettings(); + // expectedPortalSettings.UserInfo = ?????? + // mockPortalController.Setup(x => x.GetCurrentPortalSettings()).Returns(expectedPortalSettings); + // TestablePortalController.SetTestableInstance(mockPortalController.Object); + // + // //Act + // var result = controller.PortalSettings; + // + // //Assert + // mockPortalController.Verify(x => x.GetCurrentPortalSettings(), Times.Once()); + // Assert.AreEqual(expectedPortalSettings, result); + // } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs index e9434012e66..9c96ab95922 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs @@ -19,6 +19,10 @@ public class DnnDependencyResolverTests private IServiceProvider _serviceProvider; private IDependencyResolver _dependencyResolver; + private interface ITestService + { + } + [TestFixtureSetUp] public void FixtureSetUp() { @@ -109,10 +113,6 @@ public void BeginScope_GetServices() Assert.AreEqual(1, actual.Length); Assert.AreEqual(expected.GetType(), actual[0].GetType()); } - - private interface ITestService - { - } private class TestService : ITestService { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs index 608947999de..c61b8e80007 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs @@ -29,6 +29,10 @@ namespace DotNetNuke.Tests.Web.Api [TestFixture] public class JwtAuthMessageHandlerTests { + // { "type":"JWT","alg":"HS256"} . {"sub":"host","nbf":1,"exp":4102444799,"sid":"0123456789ABCDEF"} . (HS256_KEY="secret") + private const string ValidToken = + "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0.nfWCOVNk5M7L7EPDe3i3j4aAPRerbxgmcjOxaC-LWUQ"; + private Mock _mockDataProvider; private Mock _mockMembership; private Mock _mockDataService; @@ -36,10 +40,6 @@ public class JwtAuthMessageHandlerTests private Mock _mockUserController; private Mock _mockPortalController; - // { "type":"JWT","alg":"HS256"} . {"sub":"host","nbf":1,"exp":4102444799,"sid":"0123456789ABCDEF"} . (HS256_KEY="secret") - private const string ValidToken = - "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0.nfWCOVNk5M7L7EPDe3i3j4aAPRerbxgmcjOxaC-LWUQ"; - public void SetupMockServices() { MockComponentProvider.CreateDataCacheProvider(); @@ -75,6 +75,34 @@ public void SetupMockServices() // _mockUserController.Setup(x => x.ValidateUser(It.IsAny(), It.IsAny(), It.IsAny())).Returns(UserValidStatus.VALID); } + + [Test] + public void ReturnsResponseAsReceived() + { + // Arrange + var response = new HttpResponseMessage(HttpStatusCode.OK) { RequestMessage = new HttpRequestMessage() }; + + // Act + var handler = new JwtAuthMessageHandler(true, false); + var response2 = handler.OnOutboundResponse(response, CancellationToken.None); + + // Assert + Assert.AreEqual(response, response2); + } + + [Test] + public void MissingAuthoizationHeaderReturnsNullResponse() + { + // Arrange + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); + + // Act + var handler = new JwtAuthMessageHandler(true, false); + var response = handler.OnInboundRequest(request, CancellationToken.None); + + // Assert + Assert.IsNull(response); + } private static IDataReader GetUser() { @@ -108,24 +136,6 @@ private static IDataReader GetUser() return table.CreateDataReader(); } - private IDataReader GetPortalGroups() - { - var table = new DataTable("ModuleDefinitions"); - var pkId = table.Columns.Add("PortalGroupID", typeof(int)); - table.Columns.Add("MasterPortalID", typeof(int)); - table.Columns.Add("PortalGroupName", typeof(string)); - table.Columns.Add("PortalGroupDescription", typeof(string)); - table.Columns.Add("AuthenticationDomain", typeof(string)); - table.Columns.Add("CreatedByUserID", typeof(int)); - table.Columns.Add("CreatedOnDate", typeof(DateTime)); - table.Columns.Add("LastModifiedByUserID", typeof(int)); - table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - table.PrimaryKey = new[] { pkId }; - - table.Rows.Add(0, 0, "test", "descr", "domain", -1, DateTime.Now, -1, DateTime.Now); - return table.CreateDataReader(); - } - private static IDataReader GetPortalsCallBack(string culture) { return GetPortalCallBack(0, culture); @@ -165,6 +175,24 @@ private static IDataReader GetPortalCallBack(int portalId, string culture) return table.CreateDataReader(); } + private IDataReader GetPortalGroups() + { + var table = new DataTable("ModuleDefinitions"); + var pkId = table.Columns.Add("PortalGroupID", typeof(int)); + table.Columns.Add("MasterPortalID", typeof(int)); + table.Columns.Add("PortalGroupName", typeof(string)); + table.Columns.Add("PortalGroupDescription", typeof(string)); + table.Columns.Add("AuthenticationDomain", typeof(string)); + table.Columns.Add("CreatedByUserID", typeof(int)); + table.Columns.Add("CreatedOnDate", typeof(DateTime)); + table.Columns.Add("LastModifiedByUserID", typeof(int)); + table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + table.PrimaryKey = new[] { pkId }; + + table.Rows.Add(0, 0, "test", "descr", "domain", -1, DateTime.Now, -1, DateTime.Now); + return table.CreateDataReader(); + } + private static PersistedToken GetPersistedToken(string sessionId) { if ("0123456789ABCDEF".Equals(sessionId)) @@ -200,34 +228,6 @@ private static UserInfo GetUserByIdCallback(int portalId, int userId) return null; } - - [Test] - public void ReturnsResponseAsReceived() - { - // Arrange - var response = new HttpResponseMessage(HttpStatusCode.OK) { RequestMessage = new HttpRequestMessage() }; - - // Act - var handler = new JwtAuthMessageHandler(true, false); - var response2 = handler.OnOutboundResponse(response, CancellationToken.None); - - // Assert - Assert.AreEqual(response, response2); - } - - [Test] - public void MissingAuthoizationHeaderReturnsNullResponse() - { - // Arrange - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); - - // Act - var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, CancellationToken.None); - - // Assert - Assert.IsNull(response); - } [Test] public void WrongAuthoizationSchemeReturnsNullResponse() diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs index d59df4d833f..90df3a9b156 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs @@ -22,6 +22,9 @@ namespace DotNetNuke.Tests.Web.Api [TestFixture] public class StandardTabAndModuleInfoProviderTests { + private const int ValidPortalId = 0; + private const int ValidTabModuleId = 999; + private Mock _mockModuleController; private IModuleController _moduleController; private Mock _mockTabController; @@ -32,9 +35,6 @@ public class StandardTabAndModuleInfoProviderTests private ITabModulesController _tabModuleController; private TabInfo _tabInfo; private ModuleInfo _moduleInfo; - - private const int ValidPortalId = 0; - private const int ValidTabModuleId = 999; private const int ValidModuleId = 456; private const int ValidTabId = 46; @@ -56,7 +56,10 @@ public void Setup() this._tabInfo = new TabInfo { TabID = ValidTabId }; this._moduleInfo = new ModuleInfo { - TabModuleID = ValidTabModuleId, TabID = ValidTabId, ModuleID = ValidModuleId, PortalID = ValidPortalId, + TabModuleID = ValidTabModuleId, + TabID = ValidTabId, + ModuleID = ValidModuleId, + PortalID = ValidPortalId, }; this._mockTabController.Setup(x => x.GetTab(ValidTabId, ValidPortalId)).Returns(this._tabInfo); @@ -68,6 +71,46 @@ public void Setup() new Dictionary { { ValidTabModuleId, MonikerSettingValue } }); } + [TearDown] + public void TearDown() + { + ModuleController.ClearInstance(); + TabController.ClearInstance(); + } + + [Test] + public void ValidTabAndModuleIdLoadsActiveModule() + { + // Arrange + var request = new HttpRequestMessage(); + request.Headers.Add("tabid", ValidTabId.ToString(CultureInfo.InvariantCulture)); + request.Headers.Add("moduleid", ValidModuleId.ToString(CultureInfo.InvariantCulture)); + + // Act + ModuleInfo returnedModuleInfo; + var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); + + // Assert + Assert.IsTrue(result); + Assert.AreSame(this._moduleInfo, returnedModuleInfo); + } + + [Test] + public void ExistingMonikerValueInHeaderShouldFindTheCorrectModuleInfo() + { + // Arrange + var request = new HttpRequestMessage(); + request.Headers.Add("X-DNN-MONIKER", MonikerSettingValue); + + // Act + ModuleInfo returnedModuleInfo; + var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); + + // Assert + Assert.IsTrue(result); + Assert.AreSame(this._moduleInfo, returnedModuleInfo); + } + private static IDataReader GetPortalsCallBack(string culture) { return GetPortalCallBack(0, culture); @@ -107,13 +150,6 @@ private static IDataReader GetPortalCallBack(int portalId, string culture) return table.CreateDataReader(); } - [TearDown] - public void TearDown() - { - ModuleController.ClearInstance(); - TabController.ClearInstance(); - } - private void RegisterMock(Action register, out Mock mock, out T instance) where T : class { @@ -122,39 +158,6 @@ private void RegisterMock(Action register, out Mock mock, out T instanc register(instance); } - [Test] - public void ValidTabAndModuleIdLoadsActiveModule() - { - // Arrange - var request = new HttpRequestMessage(); - request.Headers.Add("tabid", ValidTabId.ToString(CultureInfo.InvariantCulture)); - request.Headers.Add("moduleid", ValidModuleId.ToString(CultureInfo.InvariantCulture)); - - // Act - ModuleInfo returnedModuleInfo; - var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - - // Assert - Assert.IsTrue(result); - Assert.AreSame(this._moduleInfo, returnedModuleInfo); - } - - [Test] - public void ExistingMonikerValueInHeaderShouldFindTheCorrectModuleInfo() - { - // Arrange - var request = new HttpRequestMessage(); - request.Headers.Add("X-DNN-MONIKER", MonikerSettingValue); - - // Act - ModuleInfo returnedModuleInfo; - var result = new StandardTabAndModuleInfoProvider().TryFindModuleInfo(request, out returnedModuleInfo); - - // Assert - Assert.IsTrue(result); - Assert.AreSame(this._moduleInfo, returnedModuleInfo); - } - [Test] public void ExistingMonikerValueInQueryStringShouldFindTheCorrectModuleInfo() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/App.config b/DNN Platform/Tests/DotNetNuke.Tests.Web/App.config index e57cb5d4d35..928751a9acb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/App.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/App.config @@ -1,23 +1,23 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs index fa1dfdf3bc4..ac785903539 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs @@ -21,8 +21,8 @@ public override bool HasViewPermission(SearchResult searchResult) // Returns the URL to the first instance of the module the user has access to view public override string GetDocUrl(SearchResult searchResult) - { - return "http://www.google.com"; + { + return "http://www.google.com"; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs index e15bdf16420..79c6e0edc9c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs @@ -73,9 +73,9 @@ public class SearchServiceControllerTests private const string CultureEnUs = "en-US"; private const string SearchIndexFolder = @"App_Data\SearchTests"; - private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; - private const int DefaultSearchRetryTimes = 5; + + private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private Mock _mockCBO; private Mock _mockHostController; private Mock _mockCachingProvider; @@ -147,6 +147,109 @@ public void TearDown() PortalController.ClearInstance(); ModuleController.ClearInstance(); } + + [Test] + public void GetSearchResultsDetailed() + { + const string keyword = "super"; + const string moduleBody = "super content is here"; + const string userUrl = "mysite/userid/1"; + const string tabUrl1 = "mysite/Home"; + const string tabUrl2 = "mysite/AboutUs"; + + // first tab with 2 modules + var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId2, Body = moduleBody, RoleId = 731 }; + var doc3 = new SearchDocument { UniqueKey = "key03", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId1, Body = moduleBody, RoleId = 731 }; + + // second tab with 1 module + var doc4 = new SearchDocument { UniqueKey = "key04", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId0 }; + var doc5 = new SearchDocument { UniqueKey = "key05", TabId = TabId2, Title = keyword, Url = tabUrl2, SearchTypeId = ModuleSearchTypeId, ModuleDefId = HtmlModuleId, ModuleId = HtmlModuleId3, ModifiedTimeUtc = DateTime.UtcNow, Body = moduleBody, RoleId = 731 }; + + // user doc + var userdoc = new SearchDocument { UniqueKey = "key06", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId731 }; + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(doc3); + this._internalSearchController.AddSearchDocument(doc4); + this._internalSearchController.AddSearchDocument(doc5); + this._internalSearchController.AddSearchDocument(userdoc); + + var query = new SearchQuery + { + KeyWords = keyword, + SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId }, + RoleId = 731, + }; + + // Run + var search = this.GetGroupedDetailViewResults(query); + + // Assert + var groupedDetailViews = search as List ?? search.ToList(); + + // Overall 3 groups - tab1, tab2 and user + Assert.AreEqual(3, groupedDetailViews.Count()); + + // Tab 1 has 2 DetailViews + Assert.AreEqual(2, groupedDetailViews.Single(x => x.DocumentUrl == tabUrl1).Results.Count()); + + // Tab 2 has 1 DetailViews + Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == tabUrl2).Results.Count()); + + // UserUrl has 1 DetailViews + Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == userUrl).Results.Count()); + } + + [Test] + public void GetSearchResultsBasic() + { + const string keyword = "awesome"; + const string userUrl = "mysite/userid/1"; + const string tabUrl1 = "mysite/Home"; + const string tabUrl2 = "mysite/AboutUs"; + + var now = DateTime.UtcNow; + var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId731 }; + var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; + var userdoc = new SearchDocument { UniqueKey = "key03", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; + + this._internalSearchController.AddSearchDocument(doc1); + this._internalSearchController.AddSearchDocument(doc2); + this._internalSearchController.AddSearchDocument(userdoc); + this._internalSearchController.Commit(); + + var query = new SearchQuery + { + KeyWords = keyword, + PortalIds = new List { PortalId0 }, + SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId }, + BeginModifiedTimeUtc = now.AddMinutes(-1), + EndModifiedTimeUtc = now.AddMinutes(+1), + PageIndex = 1, + PageSize = 15, + SortField = 0, + TitleSnippetLength = 120, + BodySnippetLength = 300, + WildCardSearch = true, + }; + + // Run + var search = this.GetGroupBasicViewResults(query); + + // Assert - overall 2 groups: tabs and users + var groupedBasicViews = search as List ?? search.ToList(); + Assert.AreEqual(2, groupedBasicViews.Count()); + + // 1 User results + Assert.AreEqual(1, groupedBasicViews.Single(x => x.DocumentTypeName == "user").Results.Count()); + + // User result should have 1 attribute(avatar) + Assert.AreEqual(1, groupedBasicViews.Single(x => x.DocumentTypeName == "user").Results.ElementAt(0).Attributes.Count()); + + // 2 Tabs results + Assert.AreEqual(2, groupedBasicViews.Single(x => x.DocumentTypeName == "tab").Results.Count()); + } private void CreateNewLuceneControllerInstance() { @@ -341,7 +444,7 @@ private IDataReader GetTabs() table.Columns.Add("LastModifiedByUserID", typeof(int)); table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - table.Rows.Add(56, 5, 0, "Home", null, 0, "//Home", "C3174A2E-374D-4779-BE5F-BCDFF410E097", "A111A742-C18F-495D-8A23-BD0ECC70BBFE", null, "3A34424A-3CCA-4934-AE15-B9A80EB6D259", 1, null, null, 0, null, null, null, 0, "[G]Skins/Xcillion/Inner.ascx", "[G]Containers/Xcillion/NoTitle.ascx", null, null, null, "false", null, null, 0, 0, 0.5, 86, "Home", 1, -1, null, 0, null, null, -1, DateTime.Now, -1, DateTime.Now); + table.Rows.Add(56, 5, 0, "Home", null, 0, "//Home", "C3174A2E-374D-4779-BE5F-BCDFF410E097", "A111A742-C18F-495D-8A23-BD0ECC70BBFE", null, "3A34424A-3CCA-4934-AE15-B9A80EB6D259", 1, null, null, 0, null, null, null, 0, "[G]Skins/Xcillion/Inner.ascx", "[G]Containers/Xcillion/NoTitle.ascx", null, null, null, "false", null, null, 0, 0, 0.5, 86, "Home", 1, -1, null, 0, null, null, -1, DateTime.Now, -1, DateTime.Now); table.Rows.Add(57, 13, 0, "About Us", null, 0, "//AboutUs", "26A4236F-3AAA-4E15-8908-45D35675C677", "8426D3BC-E930-49CA-BDEB-4D41F194B6AC", null, "1461572D-97E8-41F8-BB1A-916DCA48890A", 1, null, null, 0, null, null, null, 0, "[G]Skins/Xcillion/Inner.ascx", "[G]Containers/Xcillion/NoTitle.ascx", null, null, null, "true", null, null, 0, 0, 0.5, 97, "About Us", 1, -1, null, 0, null, null, -1, DateTime.Now, -1, DateTime.Now); return table.CreateDataReader(); @@ -547,109 +650,6 @@ private IEnumerable GetGroupedDetailViewResults(SearchQuery s return results; } - [Test] - public void GetSearchResultsDetailed() - { - const string keyword = "super"; - const string moduleBody = "super content is here"; - const string userUrl = "mysite/userid/1"; - const string tabUrl1 = "mysite/Home"; - const string tabUrl2 = "mysite/AboutUs"; - - // first tab with 2 modules - var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId2, Body = moduleBody, RoleId = 731 }; - var doc3 = new SearchDocument { UniqueKey = "key03", TabId = TabId1, Title = keyword, Url = tabUrl1, SearchTypeId = ModuleSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, ModuleDefId = HtmlModuleDefId, ModuleId = HtmlModuleId1, Body = moduleBody, RoleId = 731 }; - - // second tab with 1 module - var doc4 = new SearchDocument { UniqueKey = "key04", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId0 }; - var doc5 = new SearchDocument { UniqueKey = "key05", TabId = TabId2, Title = keyword, Url = tabUrl2, SearchTypeId = ModuleSearchTypeId, ModuleDefId = HtmlModuleId, ModuleId = HtmlModuleId3, ModifiedTimeUtc = DateTime.UtcNow, Body = moduleBody, RoleId = 731 }; - - // user doc - var userdoc = new SearchDocument { UniqueKey = "key06", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, RoleId = RoleId731 }; - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(doc3); - this._internalSearchController.AddSearchDocument(doc4); - this._internalSearchController.AddSearchDocument(doc5); - this._internalSearchController.AddSearchDocument(userdoc); - - var query = new SearchQuery - { - KeyWords = keyword, - SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId }, - RoleId = 731, - }; - - // Run - var search = this.GetGroupedDetailViewResults(query); - - // Assert - var groupedDetailViews = search as List ?? search.ToList(); - - // Overall 3 groups - tab1, tab2 and user - Assert.AreEqual(3, groupedDetailViews.Count()); - - // Tab 1 has 2 DetailViews - Assert.AreEqual(2, groupedDetailViews.Single(x => x.DocumentUrl == tabUrl1).Results.Count()); - - // Tab 2 has 1 DetailViews - Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == tabUrl2).Results.Count()); - - // UserUrl has 1 DetailViews - Assert.AreEqual(1, groupedDetailViews.Single(x => x.DocumentUrl == userUrl).Results.Count()); - } - - [Test] - public void GetSearchResultsBasic() - { - const string keyword = "awesome"; - const string userUrl = "mysite/userid/1"; - const string tabUrl1 = "mysite/Home"; - const string tabUrl2 = "mysite/AboutUs"; - - var now = DateTime.UtcNow; - var doc1 = new SearchDocument { UniqueKey = "key01", TabId = TabId1, Url = tabUrl1, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId731 }; - var doc2 = new SearchDocument { UniqueKey = "key02", TabId = TabId2, Url = tabUrl2, Title = keyword, SearchTypeId = TabSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; - var userdoc = new SearchDocument { UniqueKey = "key03", Url = userUrl, Title = keyword, SearchTypeId = UserSearchTypeId, ModifiedTimeUtc = now, PortalId = PortalId0, RoleId = RoleId0 }; - - this._internalSearchController.AddSearchDocument(doc1); - this._internalSearchController.AddSearchDocument(doc2); - this._internalSearchController.AddSearchDocument(userdoc); - this._internalSearchController.Commit(); - - var query = new SearchQuery - { - KeyWords = keyword, - PortalIds = new List { PortalId0 }, - SearchTypeIds = new[] { ModuleSearchTypeId, TabSearchTypeId, UserSearchTypeId }, - BeginModifiedTimeUtc = now.AddMinutes(-1), - EndModifiedTimeUtc = now.AddMinutes(+1), - PageIndex = 1, - PageSize = 15, - SortField = 0, - TitleSnippetLength = 120, - BodySnippetLength = 300, - WildCardSearch = true, - }; - - // Run - var search = this.GetGroupBasicViewResults(query); - - // Assert - overall 2 groups: tabs and users - var groupedBasicViews = search as List ?? search.ToList(); - Assert.AreEqual(2, groupedBasicViews.Count()); - - // 1 User results - Assert.AreEqual(1, groupedBasicViews.Single(x => x.DocumentTypeName == "user").Results.Count()); - - // User result should have 1 attribute(avatar) - Assert.AreEqual(1, groupedBasicViews.Single(x => x.DocumentTypeName == "user").Results.ElementAt(0).Attributes.Count()); - - // 2 Tabs results - Assert.AreEqual(2, groupedBasicViews.Single(x => x.DocumentTypeName == "tab").Results.Count()); - } - [Test] public void ModifyingDocumentsDoesNotCreateDuplicates() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs index c760893b4a3..436e343de39 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs @@ -21,6 +21,13 @@ namespace DotNetNuke.Tests.Web.InternalServices [TestFixture] public class TabVersionControllerTests { + private const int UserID = 1; + private const int TabID = 99; + + private Mock _mockCBO; + private Mock _mockUserController; + private Mock _mockHostController; + private class TabVersionControllerTestable : TabVersionController { } @@ -44,13 +51,6 @@ public static IEnumerable TestCases() } } - private Mock _mockCBO; - private Mock _mockUserController; - private Mock _mockHostController; - - private const int UserID = 1; - private const int TabID = 99; - // Assuming 12:00 Aug 15, 2018 server local time private readonly DateTime ServerCreateOnDate = new DateTime(2018, 08, 15, 12, 0, 0, DateTimeKind.Unspecified); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs index 3641693c01e..7c01201f655 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs @@ -24,14 +24,6 @@ public class ModuleSettingsPresenterTests private const string _tabModuleSettingName = "tabModuleKey{0}"; private const string _tabModuleSettingValue = "value{0}"; - public class TestSettingsPresenter : ModuleSettingsPresenter, SettingsModel> - { - public TestSettingsPresenter(ISettingsView view) - : base(view) - { - } - } - [Test] public void ModuleSettingsPresenter_Load_Initialises_Both_Dictionaries_On_PostBack() { @@ -93,6 +85,14 @@ public void ModuleSettingsPresenter_LoadSettings_Loads_Both_Dictionaries() Assert.IsInstanceOf>(view.Object.Model.TabModuleSettings); Assert.AreEqual(_tabModuleSettingCount, view.Object.Model.TabModuleSettings.Count); } + + public class TestSettingsPresenter : ModuleSettingsPresenter, SettingsModel> + { + public TestSettingsPresenter(ISettingsView view) + : base(view) + { + } + } [Test] public void ModuleSettingsPresenter_SaveSettings_Saves_ModuleSettings() diff --git a/DNN Platform/Website/Default.aspx.cs b/DNN Platform/Website/Default.aspx.cs index 235528961bc..46cbd57c23f 100644 --- a/DNN Platform/Website/Default.aspx.cs +++ b/DNN Platform/Website/Default.aspx.cs @@ -59,8 +59,6 @@ public partial class DefaultPage : CDefault, IClientAPICallbackEventHandler "])+name=('|\")robots('|\")", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); - protected INavigationManager NavigationManager { get; } - public DefaultPage() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); @@ -93,6 +91,16 @@ public int PageScrollTop set { this.ScrollTop.Value = value.ToString(); } } + public string CurrentSkinPath + { + get + { + return ((PortalSettings)HttpContext.Current.Items["PortalSettings"]).ActiveTab.SkinPath; + } + } + + protected INavigationManager NavigationManager { get; } + protected string HtmlAttributeList { get @@ -129,14 +137,6 @@ protected string HtmlAttributeList } } - public string CurrentSkinPath - { - get - { - return ((PortalSettings)HttpContext.Current.Items["PortalSettings"]).ActiveTab.SkinPath; - } - } - public string RaiseClientAPICallbackEvent(string eventArgument) { var dict = this.ParsePageCallBackArgs(eventArgument); @@ -162,6 +162,160 @@ public string RaiseClientAPICallbackEvent(string eventArgument) return string.Empty; } + protected bool NonProductionVersion() + { + return DotNetNukeContext.Current.Application.Status != ReleaseMode.Stable; + } + + /// ----------------------------------------------------------------------------- + /// + /// Contains the functionality to populate the Root aspx page with controls. + /// + /// + /// + /// - obtain PortalSettings from Current Context + /// - set global page settings. + /// - initialise reference paths to load the cascading style sheets + /// - add skin control placeholder. This holds all the modules and content of the page. + /// + /// ----------------------------------------------------------------------------- + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + // set global page settings + this.InitializePage(); + + // load skin control and register UI js + UI.Skins.Skin ctlSkin; + if (this.PortalSettings.EnablePopUps) + { + ctlSkin = UrlUtils.InPopUp() ? UI.Skins.Skin.GetPopUpSkin(this) : UI.Skins.Skin.GetSkin(this); + + // register popup js + JavaScript.RequestRegistration(CommonJs.jQueryUI); + + var popupFilePath = HttpContext.Current.IsDebuggingEnabled + ? "~/js/Debug/dnn.modalpopup.js" + : "~/js/dnn.modalpopup.js"; + + ClientResourceManager.RegisterScript(this, popupFilePath, FileOrder.Js.DnnModalPopup); + } + else + { + ctlSkin = UI.Skins.Skin.GetSkin(this); + } + + // DataBind common paths for the client resource loader + this.ClientResourceLoader.DataBind(); + this.ClientResourceLoader.PreRender += (sender, args) => JavaScript.Register(this.Page); + + // check for and read skin package level doctype + this.SetSkinDoctype(); + + // Manage disabled pages + if (this.PortalSettings.ActiveTab.DisableLink) + { + if (TabPermissionController.CanAdminPage()) + { + var heading = Localization.GetString("PageDisabled.Header"); + var message = Localization.GetString("PageDisabled.Text"); + UI.Skins.Skin.AddPageMessage(ctlSkin, heading, message, + ModuleMessage.ModuleMessageType.YellowWarning); + } + else + { + if (this.PortalSettings.HomeTabId > 0) + { + this.Response.Redirect(this.NavigationManager.NavigateURL(this.PortalSettings.HomeTabId), true); + } + else + { + this.Response.Redirect(Globals.GetPortalDomainName(this.PortalSettings.PortalAlias.HTTPAlias, this.Request, true), true); + } + } + } + + // Manage canonical urls + if (this.PortalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.CanonicalUrl) + { + string primaryHttpAlias = null; + if (Config.GetFriendlyUrlProvider() == "advanced") // advanced mode compares on the primary alias as set during alias identification + { + if (this.PortalSettings.PrimaryAlias != null && this.PortalSettings.PortalAlias != null) + { + if (string.Compare(this.PortalSettings.PrimaryAlias.HTTPAlias, this.PortalSettings.PortalAlias.HTTPAlias, StringComparison.InvariantCulture) != 0) + { + primaryHttpAlias = this.PortalSettings.PrimaryAlias.HTTPAlias; + } + } + } + else // other modes just depend on the default alias + { + if (string.Compare(this.PortalSettings.PortalAlias.HTTPAlias, this.PortalSettings.DefaultPortalAlias, StringComparison.InvariantCulture) != 0) + { + primaryHttpAlias = this.PortalSettings.DefaultPortalAlias; + } + } + + if (primaryHttpAlias != null && string.IsNullOrEmpty(this.CanonicalLinkUrl)) // a primary http alias was identified + { + var originalurl = this.Context.Items["UrlRewrite:OriginalUrl"].ToString(); + this.CanonicalLinkUrl = originalurl.Replace(this.PortalSettings.PortalAlias.HTTPAlias, primaryHttpAlias); + + if (UrlUtils.IsSecureConnectionOrSslOffload(this.Request)) + { + this.CanonicalLinkUrl = this.CanonicalLinkUrl.Replace("http://", "https://"); + } + } + } + + // check if running with known account defaults + if (this.Request.IsAuthenticated && string.IsNullOrEmpty(this.Request.QueryString["runningDefault"]) == false) + { + var userInfo = HttpContext.Current.Items["UserInfo"] as UserInfo; + var usernameLower = userInfo?.Username?.ToLowerInvariant(); + + // only show message to default users + if ("admin".Equals(usernameLower) || "host".Equals(usernameLower)) + { + var messageText = this.RenderDefaultsWarning(); + var messageTitle = Localization.GetString("InsecureDefaults.Title", Localization.GlobalResourceFile); + UI.Skins.Skin.AddPageMessage(ctlSkin, messageTitle, messageText, ModuleMessage.ModuleMessageType.RedError); + } + } + + // add CSS links + ClientResourceManager.RegisterDefaultStylesheet(this, string.Concat(Globals.ApplicationPath, "/Resources/Shared/stylesheets/dnndefault/7.0.0/default.css")); + ClientResourceManager.RegisterIEStylesheet(this, string.Concat(Globals.HostPath, "ie.css")); + + ClientResourceManager.RegisterStyleSheet(this, string.Concat(ctlSkin.SkinPath, "skin.css"), FileOrder.Css.SkinCss); + ClientResourceManager.RegisterStyleSheet(this, ctlSkin.SkinSrc.Replace(".ascx", ".css"), FileOrder.Css.SpecificSkinCss); + + // add skin to page + this.SkinPlaceHolder.Controls.Add(ctlSkin); + + ClientResourceManager.RegisterStyleSheet(this, string.Concat(this.PortalSettings.HomeDirectory, "portal.css"), FileOrder.Css.PortalCss); + + // add Favicon + this.ManageFavicon(); + + // ClientCallback Logic + ClientAPI.HandleClientAPICallbackEvent(this); + + // add viewstateuserkey to protect against CSRF attacks + if (this.User.Identity.IsAuthenticated) + { + this.ViewStateUserKey = this.User.Identity.Name; + } + + // set the async postback timeout. + if (AJAX.IsEnabled()) + { + AJAX.GetScriptManager(this).AsyncPostBackTimeout = Host.AsyncTimeout; + } + } + /// ----------------------------------------------------------------------------- /// /// @@ -542,160 +696,6 @@ private IFileInfo GetBackgroundFileInfoCallBack(CacheItemArgs itemArgs) return FileManager.Instance.GetFile(this.PortalSettings.PortalId, this.PortalSettings.BackgroundFile); } - protected bool NonProductionVersion() - { - return DotNetNukeContext.Current.Application.Status != ReleaseMode.Stable; - } - - /// ----------------------------------------------------------------------------- - /// - /// Contains the functionality to populate the Root aspx page with controls. - /// - /// - /// - /// - obtain PortalSettings from Current Context - /// - set global page settings. - /// - initialise reference paths to load the cascading style sheets - /// - add skin control placeholder. This holds all the modules and content of the page. - /// - /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - // set global page settings - this.InitializePage(); - - // load skin control and register UI js - UI.Skins.Skin ctlSkin; - if (this.PortalSettings.EnablePopUps) - { - ctlSkin = UrlUtils.InPopUp() ? UI.Skins.Skin.GetPopUpSkin(this) : UI.Skins.Skin.GetSkin(this); - - // register popup js - JavaScript.RequestRegistration(CommonJs.jQueryUI); - - var popupFilePath = HttpContext.Current.IsDebuggingEnabled - ? "~/js/Debug/dnn.modalpopup.js" - : "~/js/dnn.modalpopup.js"; - - ClientResourceManager.RegisterScript(this, popupFilePath, FileOrder.Js.DnnModalPopup); - } - else - { - ctlSkin = UI.Skins.Skin.GetSkin(this); - } - - // DataBind common paths for the client resource loader - this.ClientResourceLoader.DataBind(); - this.ClientResourceLoader.PreRender += (sender, args) => JavaScript.Register(this.Page); - - // check for and read skin package level doctype - this.SetSkinDoctype(); - - // Manage disabled pages - if (this.PortalSettings.ActiveTab.DisableLink) - { - if (TabPermissionController.CanAdminPage()) - { - var heading = Localization.GetString("PageDisabled.Header"); - var message = Localization.GetString("PageDisabled.Text"); - UI.Skins.Skin.AddPageMessage(ctlSkin, heading, message, - ModuleMessage.ModuleMessageType.YellowWarning); - } - else - { - if (this.PortalSettings.HomeTabId > 0) - { - this.Response.Redirect(this.NavigationManager.NavigateURL(this.PortalSettings.HomeTabId), true); - } - else - { - this.Response.Redirect(Globals.GetPortalDomainName(this.PortalSettings.PortalAlias.HTTPAlias, this.Request, true), true); - } - } - } - - // Manage canonical urls - if (this.PortalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.CanonicalUrl) - { - string primaryHttpAlias = null; - if (Config.GetFriendlyUrlProvider() == "advanced") // advanced mode compares on the primary alias as set during alias identification - { - if (this.PortalSettings.PrimaryAlias != null && this.PortalSettings.PortalAlias != null) - { - if (string.Compare(this.PortalSettings.PrimaryAlias.HTTPAlias, this.PortalSettings.PortalAlias.HTTPAlias, StringComparison.InvariantCulture) != 0) - { - primaryHttpAlias = this.PortalSettings.PrimaryAlias.HTTPAlias; - } - } - } - else // other modes just depend on the default alias - { - if (string.Compare(this.PortalSettings.PortalAlias.HTTPAlias, this.PortalSettings.DefaultPortalAlias, StringComparison.InvariantCulture) != 0) - { - primaryHttpAlias = this.PortalSettings.DefaultPortalAlias; - } - } - - if (primaryHttpAlias != null && string.IsNullOrEmpty(this.CanonicalLinkUrl)) // a primary http alias was identified - { - var originalurl = this.Context.Items["UrlRewrite:OriginalUrl"].ToString(); - this.CanonicalLinkUrl = originalurl.Replace(this.PortalSettings.PortalAlias.HTTPAlias, primaryHttpAlias); - - if (UrlUtils.IsSecureConnectionOrSslOffload(this.Request)) - { - this.CanonicalLinkUrl = this.CanonicalLinkUrl.Replace("http://", "https://"); - } - } - } - - // check if running with known account defaults - if (this.Request.IsAuthenticated && string.IsNullOrEmpty(this.Request.QueryString["runningDefault"]) == false) - { - var userInfo = HttpContext.Current.Items["UserInfo"] as UserInfo; - var usernameLower = userInfo?.Username?.ToLowerInvariant(); - - // only show message to default users - if ("admin".Equals(usernameLower) || "host".Equals(usernameLower)) - { - var messageText = this.RenderDefaultsWarning(); - var messageTitle = Localization.GetString("InsecureDefaults.Title", Localization.GlobalResourceFile); - UI.Skins.Skin.AddPageMessage(ctlSkin, messageTitle, messageText, ModuleMessage.ModuleMessageType.RedError); - } - } - - // add CSS links - ClientResourceManager.RegisterDefaultStylesheet(this, string.Concat(Globals.ApplicationPath, "/Resources/Shared/stylesheets/dnndefault/7.0.0/default.css")); - ClientResourceManager.RegisterIEStylesheet(this, string.Concat(Globals.HostPath, "ie.css")); - - ClientResourceManager.RegisterStyleSheet(this, string.Concat(ctlSkin.SkinPath, "skin.css"), FileOrder.Css.SkinCss); - ClientResourceManager.RegisterStyleSheet(this, ctlSkin.SkinSrc.Replace(".ascx", ".css"), FileOrder.Css.SpecificSkinCss); - - // add skin to page - this.SkinPlaceHolder.Controls.Add(ctlSkin); - - ClientResourceManager.RegisterStyleSheet(this, string.Concat(this.PortalSettings.HomeDirectory, "portal.css"), FileOrder.Css.PortalCss); - - // add Favicon - this.ManageFavicon(); - - // ClientCallback Logic - ClientAPI.HandleClientAPICallbackEvent(this); - - // add viewstateuserkey to protect against CSRF attacks - if (this.User.Identity.IsAuthenticated) - { - this.ViewStateUserKey = this.User.Identity.Name; - } - - // set the async postback timeout. - if (AJAX.IsEnabled()) - { - AJAX.GetScriptManager(this).AsyncPostBackTimeout = Host.AsyncTimeout; - } - } - /// ----------------------------------------------------------------------------- /// /// Initialize the Scrolltop html control which controls the open / closed nature of each module. diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs index fe00546c671..3e129830198 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs @@ -52,22 +52,22 @@ namespace DotNetNuke.Modules.Admin.Authentication /// public partial class Login : UserModuleBase { + private const string LOGIN_PATH = "/login"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Login)); - private readonly INavigationManager _navigationManager; - private static readonly Regex UserLanguageRegex = new Regex( "(.*)(&|\\?)(language=)([^&\\?]+)(.*)", RegexOptions.IgnoreCase | RegexOptions.Compiled); - public Login() - { - this._navigationManager = this.DependencyProvider.GetRequiredService(); - } + private readonly INavigationManager _navigationManager; private readonly List _loginControls = new List(); private readonly List _defaultauthLogin = new List(); private readonly List _oAuthControls = new List(); - private const string LOGIN_PATH = "/login"; + + public Login() + { + this._navigationManager = this.DependencyProvider.GetRequiredService(); + } /// /// Gets or sets and sets the current AuthenticationType. @@ -255,33 +255,6 @@ protected string RedirectURL } } - private bool IsRedirectingFromLoginUrl() - { - return this.Request.UrlReferrer != null && - this.Request.UrlReferrer.LocalPath.ToLowerInvariant().EndsWith(LOGIN_PATH); - } - - private bool NeedRedirectAfterLogin => - this.LoginStatus == UserLoginStatus.LOGIN_SUCCESS - || this.LoginStatus == UserLoginStatus.LOGIN_SUPERUSER - || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD - || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; - - /// - /// Replaces the original language with user language. - /// - /// - /// - /// - /// - private static string ReplaceLanguage(string Url, string originalLanguage, string newLanguage) - { - var returnValue = Host.UseFriendlyUrls - ? Regex.Replace(Url, "(.*)(/" + originalLanguage + "/)(.*)", "$1/" + newLanguage + "/$3", RegexOptions.IgnoreCase) - : UserLanguageRegex.Replace(Url, "$1$2$3" + newLanguage + "$5"); - return returnValue; - } - /// /// Gets or sets a value indicating whether gets and sets a flag that determines whether a permanent auth cookie should be created. /// @@ -335,6 +308,33 @@ protected UserLoginStatus LoginStatus } } + private bool NeedRedirectAfterLogin => + this.LoginStatus == UserLoginStatus.LOGIN_SUCCESS + || this.LoginStatus == UserLoginStatus.LOGIN_SUPERUSER + || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD + || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; + + /// + /// Replaces the original language with user language. + /// + /// + /// + /// + /// + private static string ReplaceLanguage(string Url, string originalLanguage, string newLanguage) + { + var returnValue = Host.UseFriendlyUrls + ? Regex.Replace(Url, "(.*)(/" + originalLanguage + "/)(.*)", "$1/" + newLanguage + "/$3", RegexOptions.IgnoreCase) + : UserLanguageRegex.Replace(Url, "$1$2$3" + newLanguage + "$5"); + return returnValue; + } + + private bool IsRedirectingFromLoginUrl() + { + return this.Request.UrlReferrer != null && + this.Request.UrlReferrer.LocalPath.ToLowerInvariant().EndsWith(LOGIN_PATH); + } + /// /// Gets or sets and sets the current UserToken. /// @@ -379,6 +379,138 @@ protected string UserName } } + /// + /// Page_Init runs when the control is initialised. + /// + /// + /// + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.ctlPassword.PasswordUpdated += this.PasswordUpdated; + this.ctlProfile.ProfileUpdated += this.ProfileUpdated; + this.ctlUser.UserCreateCompleted += this.UserCreateCompleted; + this.ctlDataConsent.DataConsentCompleted += this.DataConsentCompleted; + + // Set the User Control Properties + this.ctlUser.ID = "User"; + + // Set the Password Control Properties + this.ctlPassword.ID = "Password"; + + // Set the Profile Control Properties + this.ctlProfile.ID = "Profile"; + + // Set the Data Consent Control Properties + this.ctlDataConsent.ID = "DataConsent"; + + // Override the redirected page title if page has loaded with ctl=Login + if (this.Request.QueryString["ctl"] != null) + { + if (this.Request.QueryString["ctl"].ToLowerInvariant() == "login") + { + var myPage = (CDefault)this.Page; + if (myPage.PortalSettings.LoginTabId == this.TabId || myPage.PortalSettings.LoginTabId == -1) + { + myPage.Title = Localization.GetString("ControlTitle_login", this.LocalResourceFile); + } + } + } + } + + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cmdAssociate.Click += this.cmdAssociate_Click; + this.cmdCreateUser.Click += this.cmdCreateUser_Click; + this.cmdProceed.Click += this.cmdProceed_Click; + + // Verify if portal has a customized login page + if (!Null.IsNull(this.PortalSettings.LoginTabId) && Globals.IsAdminControl()) + { + if (Globals.ValidateLoginTabID(this.PortalSettings.LoginTabId)) + { + // login page exists and trying to access this control directly with url param -> not allowed + var parameters = new string[3]; + if (!string.IsNullOrEmpty(this.Request.QueryString["returnUrl"])) + { + parameters[0] = "returnUrl=" + HttpUtility.UrlEncode(this.Request.QueryString["returnUrl"]); + } + + if (!string.IsNullOrEmpty(this.Request.QueryString["username"])) + { + parameters[1] = "username=" + HttpUtility.UrlEncode(this.Request.QueryString["username"]); + } + + if (!string.IsNullOrEmpty(this.Request.QueryString["verificationcode"])) + { + parameters[2] = "verificationcode=" + HttpUtility.UrlEncode(this.Request.QueryString["verificationcode"]); + } + + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.LoginTabId, string.Empty, parameters)); + } + } + + if (this.Page.IsPostBack == false) + { + try + { + this.PageNo = 0; + } + catch (Exception ex) + { + // control not there + Logger.Error(ex); + } + } + + if (!this.Request.IsAuthenticated || this.UserNeedsVerification()) + { + this.ShowPanel(); + } + else // user is already authenticated + { + // if a Login Page has not been specified for the portal + if (Globals.IsAdminControl()) + { + // redirect browser + this.Response.Redirect(this.RedirectURL, true); + } + else // make module container invisible if user is not a page admin + { + var path = this.RedirectURL.Split('?')[0]; + if (this.NeedRedirectAfterLogin && path != this._navigationManager.NavigateURL() && path != this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId)) + { + this.Response.Redirect(this.RedirectURL, true); + } + + if (TabPermissionController.CanAdminPage()) + { + this.ShowPanel(); + } + else + { + this.ContainerControl.Visible = false; + } + } + } + + this.divCaptcha.Visible = this.UseCaptcha; + + if (this.UseCaptcha) + { + this.ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", Localization.SharedResourceFile); + this.ctlCaptcha.Text = Localization.GetString("CaptchaText", Localization.SharedResourceFile); + } + } + private void AddLoginControlAttributes(AuthenticationLoginBase loginControl) { // search selected authentication control for username and password fields @@ -1012,138 +1144,6 @@ private bool LocaleEnabled(string locale) return LocaleController.Instance.GetLocales(this.PortalSettings.PortalId).ContainsKey(locale); } - /// - /// Page_Init runs when the control is initialised. - /// - /// - /// - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.ctlPassword.PasswordUpdated += this.PasswordUpdated; - this.ctlProfile.ProfileUpdated += this.ProfileUpdated; - this.ctlUser.UserCreateCompleted += this.UserCreateCompleted; - this.ctlDataConsent.DataConsentCompleted += this.DataConsentCompleted; - - // Set the User Control Properties - this.ctlUser.ID = "User"; - - // Set the Password Control Properties - this.ctlPassword.ID = "Password"; - - // Set the Profile Control Properties - this.ctlProfile.ID = "Profile"; - - // Set the Data Consent Control Properties - this.ctlDataConsent.ID = "DataConsent"; - - // Override the redirected page title if page has loaded with ctl=Login - if (this.Request.QueryString["ctl"] != null) - { - if (this.Request.QueryString["ctl"].ToLowerInvariant() == "login") - { - var myPage = (CDefault)this.Page; - if (myPage.PortalSettings.LoginTabId == this.TabId || myPage.PortalSettings.LoginTabId == -1) - { - myPage.Title = Localization.GetString("ControlTitle_login", this.LocalResourceFile); - } - } - } - } - - /// - /// Page_Load runs when the control is loaded. - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cmdAssociate.Click += this.cmdAssociate_Click; - this.cmdCreateUser.Click += this.cmdCreateUser_Click; - this.cmdProceed.Click += this.cmdProceed_Click; - - // Verify if portal has a customized login page - if (!Null.IsNull(this.PortalSettings.LoginTabId) && Globals.IsAdminControl()) - { - if (Globals.ValidateLoginTabID(this.PortalSettings.LoginTabId)) - { - // login page exists and trying to access this control directly with url param -> not allowed - var parameters = new string[3]; - if (!string.IsNullOrEmpty(this.Request.QueryString["returnUrl"])) - { - parameters[0] = "returnUrl=" + HttpUtility.UrlEncode(this.Request.QueryString["returnUrl"]); - } - - if (!string.IsNullOrEmpty(this.Request.QueryString["username"])) - { - parameters[1] = "username=" + HttpUtility.UrlEncode(this.Request.QueryString["username"]); - } - - if (!string.IsNullOrEmpty(this.Request.QueryString["verificationcode"])) - { - parameters[2] = "verificationcode=" + HttpUtility.UrlEncode(this.Request.QueryString["verificationcode"]); - } - - this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.LoginTabId, string.Empty, parameters)); - } - } - - if (this.Page.IsPostBack == false) - { - try - { - this.PageNo = 0; - } - catch (Exception ex) - { - // control not there - Logger.Error(ex); - } - } - - if (!this.Request.IsAuthenticated || this.UserNeedsVerification()) - { - this.ShowPanel(); - } - else // user is already authenticated - { - // if a Login Page has not been specified for the portal - if (Globals.IsAdminControl()) - { - // redirect browser - this.Response.Redirect(this.RedirectURL, true); - } - else // make module container invisible if user is not a page admin - { - var path = this.RedirectURL.Split('?')[0]; - if (this.NeedRedirectAfterLogin && path != this._navigationManager.NavigateURL() && path != this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId)) - { - this.Response.Redirect(this.RedirectURL, true); - } - - if (TabPermissionController.CanAdminPage()) - { - this.ShowPanel(); - } - else - { - this.ContainerControl.Visible = false; - } - } - } - - this.divCaptcha.Visible = this.UseCaptcha; - - if (this.UseCaptcha) - { - this.ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", Localization.SharedResourceFile); - this.ctlCaptcha.Text = Localization.GetString("CaptchaText", Localization.SharedResourceFile); - } - } - /// /// cmdAssociate_Click runs when the associate button is clicked. /// diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs index 5ac9dd9c562..2f789068b47 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs @@ -21,31 +21,6 @@ namespace DotNetNuke.Modules.Admin.Authentication /// public partial class Logoff : UserModuleBase { - private void Redirect() - { - // Redirect browser back to portal - this.Response.Redirect(AuthenticationController.GetLogoffRedirectURL(this.PortalSettings, this.Request), true); - } - - private void DoLogoff() - { - try - { - // Remove user from cache - if (this.User != null) - { - DataCache.ClearUserCache(this.PortalSettings.PortalId, this.Context.User.Identity.Name); - } - - var objPortalSecurity = PortalSecurity.Instance; - objPortalSecurity.SignOut(); - } - catch (Exception exc) // Page failed to load - { - Exceptions.ProcessPageLoadException(exc); - } - } - /// /// Page_Load runs when the control is loaded. /// @@ -98,6 +73,31 @@ protected void UserLogOff(object sender, EventArgs e) { this.DoLogoff(); } + + private void Redirect() + { + // Redirect browser back to portal + this.Response.Redirect(AuthenticationController.GetLogoffRedirectURL(this.PortalSettings, this.Request), true); + } + + private void DoLogoff() + { + try + { + // Remove user from cache + if (this.User != null) + { + DataCache.ClearUserCache(this.PortalSettings.PortalId, this.Context.User.Identity.Name); + } + + var objPortalSecurity = PortalSecurity.Instance; + objPortalSecurity.SignOut(); + } + catch (Exception exc) // Page failed to load + { + Exceptions.ProcessPageLoadException(exc); + } + } protected void UserRedirect(object sender, EventArgs e) { diff --git a/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs index 157e69b7776..e71ab60b7d8 100644 --- a/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs @@ -23,15 +23,15 @@ namespace DotNetNuke.Modules.Admin.EditExtension public partial class AuthenticationEditor : PackageEditorBase { private readonly INavigationManager _navigationManager; + + private AuthenticationInfo _AuthSystem; + private AuthenticationSettingsBase _SettingsControl; public AuthenticationEditor() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - private AuthenticationInfo _AuthSystem; - private AuthenticationSettingsBase _SettingsControl; - protected AuthenticationInfo AuthSystem { get @@ -66,6 +66,40 @@ protected AuthenticationSettingsBase SettingsControl } } + public override void Initialize() + { + this.pnlSettings.Visible = !this.IsSuperTab; + if (this.IsSuperTab) + { + this.lblHelp.Text = Localization.GetString("HostHelp", this.LocalResourceFile); + } + else + { + if (this.SettingsControl == null) + { + this.lblHelp.Text = Localization.GetString("NoSettings", this.LocalResourceFile); + } + else + { + this.lblHelp.Text = Localization.GetString("AdminHelp", this.LocalResourceFile); + } + } + + this.BindAuthentication(); + } + + public override void UpdatePackage() + { + if (this.authenticationForm.IsValid) + { + var authInfo = this.authenticationForm.DataSource as AuthenticationInfo; + if (authInfo != null) + { + AuthenticationController.UpdateAuthentication(authInfo); + } + } + } + /// ----------------------------------------------------------------------------- /// /// This routine Binds the Authentication System. @@ -105,40 +139,6 @@ private void BindAuthentication() } } - public override void Initialize() - { - this.pnlSettings.Visible = !this.IsSuperTab; - if (this.IsSuperTab) - { - this.lblHelp.Text = Localization.GetString("HostHelp", this.LocalResourceFile); - } - else - { - if (this.SettingsControl == null) - { - this.lblHelp.Text = Localization.GetString("NoSettings", this.LocalResourceFile); - } - else - { - this.lblHelp.Text = Localization.GetString("AdminHelp", this.LocalResourceFile); - } - } - - this.BindAuthentication(); - } - - public override void UpdatePackage() - { - if (this.authenticationForm.IsValid) - { - var authInfo = this.authenticationForm.DataSource as AuthenticationInfo; - if (authInfo != null) - { - AuthenticationController.UpdateAuthentication(authInfo); - } - } - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); diff --git a/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs index 2dd6e10dca0..b0201888cd4 100644 --- a/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs @@ -42,28 +42,42 @@ public EditExtension() this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - protected bool IsSuperTab + public string Mode { get { - return this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab; + return Convert.ToString(this.ModuleContext.Settings["Extensions_Mode"]); } } - protected string ReturnUrl + public int PackageID { - get { return (string)this.ViewState["ReturnUrl"]; } - set { this.ViewState["ReturnUrl"] = value; } + get + { + var packageID = Null.NullInteger; + if (this.Request.QueryString["PackageID"] != null) + { + packageID = int.Parse(this.Request.QueryString["PackageID"]); + } + + return packageID; + } } - public string Mode + protected bool IsSuperTab { get { - return Convert.ToString(this.ModuleContext.Settings["Extensions_Mode"]); + return this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab; } } + protected string ReturnUrl + { + get { return (string)this.ViewState["ReturnUrl"]; } + set { this.ViewState["ReturnUrl"] = value; } + } + protected string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); protected PackageInfo Package @@ -94,31 +108,76 @@ protected IPackageEditor PackageEditor } } - public int PackageID + protected PropertyEditorMode ViewMode { get { - var packageID = Null.NullInteger; - if (this.Request.QueryString["PackageID"] != null) + var viewMode = PropertyEditorMode.View; + if (this.Request.IsLocal && this.IsSuperTab) { - packageID = int.Parse(this.Request.QueryString["PackageID"]); + viewMode = PropertyEditorMode.Edit; } - return packageID; + return viewMode; } } - protected PropertyEditorMode ViewMode + protected override void OnInit(EventArgs e) { - get + base.OnInit(e); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + } + + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cmdCancel.Click += this.OnCancelClick; + this.cmdDelete.Click += this.OnDeleteClick; + this.cmdPackage.Click += this.OnPackageClick; + this.cmdUpdate.Click += this.OnUpdateClick; + this.Page.PreRenderComplete += (sender, args) => + { + if (UrlUtils.InPopUp()) + { + var title = string.Format("{0} > {1}", this.Page.Title, this.Package.FriendlyName); + this.Page.Title = title; + } + }; + + this.BindData(); + + if (!this.IsPostBack) { - var viewMode = PropertyEditorMode.View; - if (this.Request.IsLocal && this.IsSuperTab) + this.ReturnUrl = this.Request.UrlReferrer != null ? this.Request.UrlReferrer.ToString() : this._navigationManager.NavigateURL(); + switch (this.DisplayMode) { - viewMode = PropertyEditorMode.Edit; + case "editor": + this.packageSettingsSection.Visible = false; + break; + case "settings": + this.extensionSection.Visible = false; + break; } + } - return viewMode; + switch (this.DisplayMode) + { + case "editor": + this.cmdCancel.Visible = this.cmdCancel.Enabled = false; + this.cmdUpdate.Visible = this.cmdUpdate.Enabled = false; + this.cmdPackage.Visible = this.cmdPackage.Enabled = false; + this.cmdDelete.Visible = this.cmdDelete.Enabled = false; + break; + case "settings": + this.cmdCancel.Visible = this.cmdCancel.Enabled = false; + break; } } @@ -234,65 +293,6 @@ private void UpdatePackage(bool displayMessage) } } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - } - - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the control is loaded. - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cmdCancel.Click += this.OnCancelClick; - this.cmdDelete.Click += this.OnDeleteClick; - this.cmdPackage.Click += this.OnPackageClick; - this.cmdUpdate.Click += this.OnUpdateClick; - this.Page.PreRenderComplete += (sender, args) => - { - if (UrlUtils.InPopUp()) - { - var title = string.Format("{0} > {1}", this.Page.Title, this.Package.FriendlyName); - this.Page.Title = title; - } - }; - - this.BindData(); - - if (!this.IsPostBack) - { - this.ReturnUrl = this.Request.UrlReferrer != null ? this.Request.UrlReferrer.ToString() : this._navigationManager.NavigateURL(); - switch (this.DisplayMode) - { - case "editor": - this.packageSettingsSection.Visible = false; - break; - case "settings": - this.extensionSection.Visible = false; - break; - } - } - - switch (this.DisplayMode) - { - case "editor": - this.cmdCancel.Visible = this.cmdCancel.Enabled = false; - this.cmdUpdate.Visible = this.cmdUpdate.Enabled = false; - this.cmdPackage.Visible = this.cmdPackage.Enabled = false; - this.cmdDelete.Visible = this.cmdDelete.Enabled = false; - break; - case "settings": - this.cmdCancel.Visible = this.cmdCancel.Enabled = false; - break; - } - } - protected void OnCancelClick(object sender, EventArgs e) { this.Response.Redirect(this.ReturnUrl); diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs index 14a5dda03a0..7de9f309c44 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs @@ -163,9 +163,9 @@ protected IEnumerable LoadPortalsList() var groups = PortalGroupController.Instance.GetPortalGroups().ToArray(); var mygroup = (from @group in groups select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) - select portals.ToArray()).FirstOrDefault(); + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); var result = new List(); if (mygroup != null && mygroup.Any()) diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs index 142d0bf191c..b85dc05f0c0 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs @@ -25,6 +25,8 @@ public partial class SearchResults : PortalModuleBase private const int DefaultPageSize = 15; private const int DefaultSortOption = 0; + private const string MyFileName = "SearchResults.ascx"; + private IList _searchContentSources; private IList _searchPortalIds; @@ -150,31 +152,6 @@ protected string LinkTarget protected string MaxDescriptionLength => this.GetIntegerSetting("MaxDescriptionLength", 100).ToString(); - private IList SearchPortalIds - { - get - { - if (this._searchPortalIds == null) - { - this._searchPortalIds = new List(); - if (!string.IsNullOrEmpty(Convert.ToString(this.Settings["ScopeForPortals"]))) - { - List list = Convert.ToString(this.Settings["ScopeForPortals"]).Split('|').ToList(); - foreach (string l in list) - { - this._searchPortalIds.Add(Convert.ToInt32(l)); - } - } - else - { - this._searchPortalIds.Add(this.PortalId); // no setting, just search current portal by default - } - } - - return this._searchPortalIds; - } - } - protected IList SearchContentSources { get @@ -228,13 +205,36 @@ protected IList SearchContentSources } } - private const string MyFileName = "SearchResults.ascx"; - protected string DefaultText { get { return Localization.GetSafeJSString("DefaultText", Localization.GetResourceFile(this, MyFileName)); } } + private IList SearchPortalIds + { + get + { + if (this._searchPortalIds == null) + { + this._searchPortalIds = new List(); + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings["ScopeForPortals"]))) + { + List list = Convert.ToString(this.Settings["ScopeForPortals"]).Split('|').ToList(); + foreach (string l in list) + { + this._searchPortalIds.Add(Convert.ToInt32(l)); + } + } + else + { + this._searchPortalIds.Add(this.PortalId); // no setting, just search current portal by default + } + } + + return this._searchPortalIds; + } + } + protected string NoResultsText { get { return Localization.GetSafeJSString("NoResults", Localization.GetResourceFile(this, MyFileName)); } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs index 411187f42e5..0f973ea6d68 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs @@ -14,6 +14,18 @@ namespace DotNetNuke.Modules.Admin.Users public partial class DataConsent : UserModuleBase { + public delegate void DataConsentEventHandler(object sender, DataConsentEventArgs e); + + public event DataConsentEventHandler DataConsentCompleted; + + public enum DataConsentStatus + { + Consented, + Cancelled, + RemovedAccount, + FailedToRemoveAccount, + } + public string DeleteMeConfirmString { get @@ -32,10 +44,6 @@ public string DeleteMeConfirmString } } - public delegate void DataConsentEventHandler(object sender, DataConsentEventArgs e); - - public event DataConsentEventHandler DataConsentCompleted; - public void OnDataConsentComplete(DataConsentEventArgs e) { this.DataConsentCompleted?.Invoke(this, e); @@ -130,13 +138,5 @@ public DataConsentEventArgs(DataConsentStatus status) /// public DataConsentStatus Status { get; set; } } - - public enum DataConsentStatus - { - Consented, - Cancelled, - RemovedAccount, - FailedToRemoveAccount, - } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs index a6702ed5ae5..fb9f9f69f58 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs @@ -45,6 +45,31 @@ public EditUser() this._navigationManager = this.DependencyProvider.GetRequiredService(); } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the current Page No. + /// + public int PageNo + { + get + { + int _PageNo = 0; + if (this.ViewState["PageNo"] != null && !this.IsPostBack) + { + _PageNo = Convert.ToInt32(this.ViewState["PageNo"]); + } + + return _PageNo; + } + + set + { + this.ViewState["PageNo"] = value; + } + } + + public bool ShowVanityUrl { get; private set; } + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether to display the Manage Services tab. @@ -147,28 +172,75 @@ protected string UserFilter /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the current Page No. + /// Page_Init runs when the control is initialised. /// - public int PageNo + /// + /// + protected override void OnInit(EventArgs e) { - get - { - int _PageNo = 0; - if (this.ViewState["PageNo"] != null && !this.IsPostBack) - { - _PageNo = Convert.ToInt32(this.ViewState["PageNo"]); - } + base.OnInit(e); - return _PageNo; - } + this.cmdDelete.Click += this.cmdDelete_Click; + this.cmdUpdate.Click += this.cmdUpdate_Click; - set + this.ctlServices.SubscriptionUpdated += this.SubscriptionUpdated; + this.ctlProfile.ProfileUpdateCompleted += this.ProfileUpdateCompleted; + this.ctlPassword.PasswordUpdated += this.PasswordUpdated; + this.ctlPassword.PasswordQuestionAnswerUpdated += this.PasswordQuestionAnswerUpdated; + + this.email.ValidationExpression = this.PortalSettings.Registration.EmailValidator; + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + JavaScript.RequestRegistration(CommonJs.Knockout); + + // Set the Membership Control Properties + this.ctlMembership.ID = "Membership"; + this.ctlMembership.ModuleConfiguration = this.ModuleConfiguration; + this.ctlMembership.UserId = this.UserId; + + // Set the Password Control Properties + this.ctlPassword.ID = "Password"; + this.ctlPassword.ModuleConfiguration = this.ModuleConfiguration; + this.ctlPassword.UserId = this.UserId; + + // Set the Profile Control Properties + this.ctlProfile.ID = "Profile"; + this.ctlProfile.ModuleConfiguration = this.ModuleConfiguration; + this.ctlProfile.UserId = this.UserId; + + // Set the Services Control Properties + this.ctlServices.ID = "MemberServices"; + this.ctlServices.ModuleConfiguration = this.ModuleConfiguration; + this.ctlServices.UserId = this.UserId; + + // Define DisplayName filed Enabled Property: + object setting = GetSetting(this.UserPortalID, "Security_DisplayNameFormat"); + if ((setting != null) && (!string.IsNullOrEmpty(Convert.ToString(setting)))) { - this.ViewState["PageNo"] = value; + this.displayName.Enabled = false; } } - public bool ShowVanityUrl { get; private set; } + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + try + { + // Bind the User information to the controls + this.BindData(); + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } private void BindData() { @@ -348,78 +420,6 @@ private void UpdateDisplayName() } } - /// ----------------------------------------------------------------------------- - /// - /// Page_Init runs when the control is initialised. - /// - /// - /// - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.cmdDelete.Click += this.cmdDelete_Click; - this.cmdUpdate.Click += this.cmdUpdate_Click; - - this.ctlServices.SubscriptionUpdated += this.SubscriptionUpdated; - this.ctlProfile.ProfileUpdateCompleted += this.ProfileUpdateCompleted; - this.ctlPassword.PasswordUpdated += this.PasswordUpdated; - this.ctlPassword.PasswordQuestionAnswerUpdated += this.PasswordQuestionAnswerUpdated; - - this.email.ValidationExpression = this.PortalSettings.Registration.EmailValidator; - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - JavaScript.RequestRegistration(CommonJs.Knockout); - - // Set the Membership Control Properties - this.ctlMembership.ID = "Membership"; - this.ctlMembership.ModuleConfiguration = this.ModuleConfiguration; - this.ctlMembership.UserId = this.UserId; - - // Set the Password Control Properties - this.ctlPassword.ID = "Password"; - this.ctlPassword.ModuleConfiguration = this.ModuleConfiguration; - this.ctlPassword.UserId = this.UserId; - - // Set the Profile Control Properties - this.ctlProfile.ID = "Profile"; - this.ctlProfile.ModuleConfiguration = this.ModuleConfiguration; - this.ctlProfile.UserId = this.UserId; - - // Set the Services Control Properties - this.ctlServices.ID = "MemberServices"; - this.ctlServices.ModuleConfiguration = this.ModuleConfiguration; - this.ctlServices.UserId = this.UserId; - - // Define DisplayName filed Enabled Property: - object setting = GetSetting(this.UserPortalID, "Security_DisplayNameFormat"); - if ((setting != null) && (!string.IsNullOrEmpty(Convert.ToString(setting)))) - { - this.displayName.Enabled = false; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the control is loaded. - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - try - { - // Bind the User information to the controls - this.BindData(); - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - protected void cmdDelete_Click(object sender, EventArgs e) { UserInfo user = this.User; diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs index 5206b7cf919..d70e39d9c6a 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs @@ -42,6 +42,82 @@ public ManageUsers() this._navigationManager = this.DependencyProvider.GetRequiredService(); } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the current Page No. + /// + public int PageNo + { + get + { + int _PageNo = 0; + if (this.ViewState["PageNo"] != null && !this.IsPostBack) + { + _PageNo = Convert.ToInt32(this.ViewState["PageNo"]); + } + + return _PageNo; + } + + set + { + this.ViewState["PageNo"] = value; + } + } + + public ModuleActionCollection ModuleActions + { + get + { + var Actions = new ModuleActionCollection(); + if (!this.IsProfile) + { + if (!this.AddUser && !this.IsEdit) + { + Actions.Add( + this.GetNextActionID(), + Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "add.gif", + this.EditUrl(), + false, + SecurityAccessLevel.Admin, + true, + false); + if (ProfileProviderConfig.CanEditProviderProperties) + { + Actions.Add( + this.GetNextActionID(), + Localization.GetString("ManageProfile.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "icon_profile_16px.gif", + this.EditUrl("ManageProfile"), + false, + SecurityAccessLevel.Admin, + true, + false); + } + + Actions.Add( + this.GetNextActionID(), + Localization.GetString("Cancel.Action", this.LocalResourceFile), + ModuleActionType.AddContent, + string.Empty, + "lt.gif", + this.ReturnUrl, + false, + SecurityAccessLevel.Admin, + true, + false); + } + } + + return Actions; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether to display the Manage Services tab. @@ -159,79 +235,109 @@ protected bool EditProfileMode /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the current Page No. + /// Page_Init runs when the control is initialised. /// - public int PageNo + /// + /// + protected override void OnInit(EventArgs e) { - get + base.OnInit(e); + + this.cmdCancel.Click += this.cmdCancel_Click; + this.cmdAdd.Click += this.cmdAdd_Click; + + this.ctlUser.UserCreateCompleted += this.UserCreateCompleted; + this.ctlUser.UserDeleted += this.UserDeleted; + this.ctlUser.UserRemoved += this.UserRemoved; + this.ctlUser.UserRestored += this.UserRestored; + this.ctlUser.UserUpdateCompleted += this.UserUpdateCompleted; + this.ctlUser.UserUpdateError += this.UserUpdateError; + + this.ctlProfile.ProfileUpdateCompleted += this.ProfileUpdateCompleted; + this.ctlPassword.PasswordUpdated += this.PasswordUpdated; + this.ctlPassword.PasswordQuestionAnswerUpdated += this.PasswordQuestionAnswerUpdated; + this.ctlMembership.MembershipAuthorized += this.MembershipAuthorized; + this.ctlMembership.MembershipPasswordUpdateChanged += this.MembershipPasswordUpdateChanged; + this.ctlMembership.MembershipUnAuthorized += this.MembershipUnAuthorized; + this.ctlMembership.MembershipUnLocked += this.MembershipUnLocked; + this.ctlMembership.MembershipDemoteFromSuperuser += this.MembershipDemoteFromSuperuser; + this.ctlMembership.MembershipPromoteToSuperuser += this.MembershipPromoteToSuperuser; + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + + // Set the Membership Control Properties + this.ctlMembership.ID = "Membership"; + this.ctlMembership.ModuleConfiguration = this.ModuleConfiguration; + this.ctlMembership.UserId = this.UserId; + + // Set the User Control Properties + this.ctlUser.ID = "User"; + this.ctlUser.ModuleConfiguration = this.ModuleConfiguration; + this.ctlUser.UserId = this.UserId; + + // Set the Roles Control Properties + this.ctlRoles.ID = "SecurityRoles"; + this.ctlRoles.ModuleConfiguration = this.ModuleConfiguration; + this.ctlRoles.ParentModule = this; + + // Set the Password Control Properties + this.ctlPassword.ID = "Password"; + this.ctlPassword.ModuleConfiguration = this.ModuleConfiguration; + this.ctlPassword.UserId = this.UserId; + + // Set the Profile Control Properties + this.ctlProfile.ID = "Profile"; + this.ctlProfile.ModuleConfiguration = this.ModuleConfiguration; + this.ctlProfile.UserId = this.UserId; + + // Customise the Control Title + if (this.AddUser) { - int _PageNo = 0; - if (this.ViewState["PageNo"] != null && !this.IsPostBack) + if (!this.Request.IsAuthenticated) { - _PageNo = Convert.ToInt32(this.ViewState["PageNo"]); + // Register + this.ModuleConfiguration.ModuleTitle = Localization.GetString("Register.Title", this.LocalResourceFile); } - - return _PageNo; - } - - set - { - this.ViewState["PageNo"] = value; + else + { + // Add User + this.ModuleConfiguration.ModuleTitle = Localization.GetString("AddUser.Title", this.LocalResourceFile); + } + + this.userContainer.CssClass += " register"; } - } - - public ModuleActionCollection ModuleActions + } + + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) { - get + base.OnLoad(e); + + try { - var Actions = new ModuleActionCollection(); - if (!this.IsProfile) + // Add an Action Event Handler to the Skin + this.AddActionHandler(this.ModuleAction_Click); + + // Bind the User information to the controls + this.BindData(); + + this.loginLink.NavigateUrl = Globals.LoginURL(this.RedirectURL, this.Request.QueryString["override"] != null); + + if (this.PortalSettings.EnablePopUps) { - if (!this.AddUser && !this.IsEdit) - { - Actions.Add( - this.GetNextActionID(), - Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), - ModuleActionType.AddContent, - string.Empty, - "add.gif", - this.EditUrl(), - false, - SecurityAccessLevel.Admin, - true, - false); - if (ProfileProviderConfig.CanEditProviderProperties) - { - Actions.Add( - this.GetNextActionID(), - Localization.GetString("ManageProfile.Action", this.LocalResourceFile), - ModuleActionType.AddContent, - string.Empty, - "icon_profile_16px.gif", - this.EditUrl("ManageProfile"), - false, - SecurityAccessLevel.Admin, - true, - false); - } - - Actions.Add( - this.GetNextActionID(), - Localization.GetString("Cancel.Action", this.LocalResourceFile), - ModuleActionType.AddContent, - string.Empty, - "lt.gif", - this.ReturnUrl, - false, - SecurityAccessLevel.Admin, - true, - false); - } + this.loginLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(this.loginLink.NavigateUrl, this, this.PortalSettings, true, false, 300, 650)); } - - return Actions; } - } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } private void BindData() { @@ -464,106 +570,56 @@ private void ShowPanel() this.actionsRow.Visible = false; } } - + + protected void cmdCancel_Click(object sender, EventArgs e) + { + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } + /// ----------------------------------------------------------------------------- /// - /// Page_Init runs when the control is initialised. + /// cmdRegister_Click runs when the Register button is clicked. /// /// /// - protected override void OnInit(EventArgs e) + protected void cmdAdd_Click(object sender, EventArgs e) { - base.OnInit(e); - - this.cmdCancel.Click += this.cmdCancel_Click; - this.cmdAdd.Click += this.cmdAdd_Click; - - this.ctlUser.UserCreateCompleted += this.UserCreateCompleted; - this.ctlUser.UserDeleted += this.UserDeleted; - this.ctlUser.UserRemoved += this.UserRemoved; - this.ctlUser.UserRestored += this.UserRestored; - this.ctlUser.UserUpdateCompleted += this.UserUpdateCompleted; - this.ctlUser.UserUpdateError += this.UserUpdateError; - - this.ctlProfile.ProfileUpdateCompleted += this.ProfileUpdateCompleted; - this.ctlPassword.PasswordUpdated += this.PasswordUpdated; - this.ctlPassword.PasswordQuestionAnswerUpdated += this.PasswordQuestionAnswerUpdated; - this.ctlMembership.MembershipAuthorized += this.MembershipAuthorized; - this.ctlMembership.MembershipPasswordUpdateChanged += this.MembershipPasswordUpdateChanged; - this.ctlMembership.MembershipUnAuthorized += this.MembershipUnAuthorized; - this.ctlMembership.MembershipUnLocked += this.MembershipUnLocked; - this.ctlMembership.MembershipDemoteFromSuperuser += this.MembershipDemoteFromSuperuser; - this.ctlMembership.MembershipPromoteToSuperuser += this.MembershipPromoteToSuperuser; - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - - // Set the Membership Control Properties - this.ctlMembership.ID = "Membership"; - this.ctlMembership.ModuleConfiguration = this.ModuleConfiguration; - this.ctlMembership.UserId = this.UserId; - - // Set the User Control Properties - this.ctlUser.ID = "User"; - this.ctlUser.ModuleConfiguration = this.ModuleConfiguration; - this.ctlUser.UserId = this.UserId; - - // Set the Roles Control Properties - this.ctlRoles.ID = "SecurityRoles"; - this.ctlRoles.ModuleConfiguration = this.ModuleConfiguration; - this.ctlRoles.ParentModule = this; - - // Set the Password Control Properties - this.ctlPassword.ID = "Password"; - this.ctlPassword.ModuleConfiguration = this.ModuleConfiguration; - this.ctlPassword.UserId = this.UserId; - - // Set the Profile Control Properties - this.ctlProfile.ID = "Profile"; - this.ctlProfile.ModuleConfiguration = this.ModuleConfiguration; - this.ctlProfile.UserId = this.UserId; - - // Customise the Control Title - if (this.AddUser) + if (this.IsAdmin == false && this.HasManageUsersModulePermission() == false) { - if (!this.Request.IsAuthenticated) - { - // Register - this.ModuleConfiguration.ModuleTitle = Localization.GetString("Register.Title", this.LocalResourceFile); - } - else + return; + } + + if (this.ctlUser.IsValid && this.ctlProfile.IsValid) + { + this.ctlUser.CreateUser(); + } + else + { + if (this.ctlUser.CreateStatus != UserCreateStatus.AddUser) { - // Add User - this.ModuleConfiguration.ModuleTitle = Localization.GetString("AddUser.Title", this.LocalResourceFile); + this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(this.ctlUser.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); } - - this.userContainer.CssClass += " register"; } } /// ----------------------------------------------------------------------------- /// - /// Page_Load runs when the control is loaded. + /// MembershipPasswordUpdateChanged runs when the Admin has forced the User to update their password. /// /// /// - protected override void OnLoad(EventArgs e) + protected void MembershipPasswordUpdateChanged(object sender, EventArgs e) { - base.OnLoad(e); - + if (this.IsAdmin == false) + { + return; + } + try { - // Add an Action Event Handler to the Skin - this.AddActionHandler(this.ModuleAction_Click); - - // Bind the User information to the controls - this.BindData(); - - this.loginLink.NavigateUrl = Globals.LoginURL(this.RedirectURL, this.Request.QueryString["override"] != null); + this.AddModuleMessage("UserPasswordUpdateChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); - if (this.PortalSettings.EnablePopUps) - { - this.loginLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(this.loginLink.NavigateUrl, this, this.PortalSettings, true, false, 300, 650)); - } + this.BindMembership(); } catch (Exception exc) // Module failed to load { @@ -571,42 +627,11 @@ protected override void OnLoad(EventArgs e) } } - protected void cmdCancel_Click(object sender, EventArgs e) - { - this.Response.Redirect(this._navigationManager.NavigateURL(), true); - } - private bool HasManageUsersModulePermission() { return ModulePermissionController.HasModulePermission(this.ModuleConfiguration.ModulePermissions, "MANAGEUSER"); } - /// ----------------------------------------------------------------------------- - /// - /// cmdRegister_Click runs when the Register button is clicked. - /// - /// - /// - protected void cmdAdd_Click(object sender, EventArgs e) - { - if (this.IsAdmin == false && this.HasManageUsersModulePermission() == false) - { - return; - } - - if (this.ctlUser.IsValid && this.ctlProfile.IsValid) - { - this.ctlUser.CreateUser(); - } - else - { - if (this.ctlUser.CreateStatus != UserCreateStatus.AddUser) - { - this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(this.ctlUser.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); - } - } - } - /// ----------------------------------------------------------------------------- /// /// ModuleAction_Click handles all ModuleAction events raised from the skin. @@ -667,31 +692,6 @@ private void MembershipAuthorized(object sender, EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - - /// ----------------------------------------------------------------------------- - /// - /// MembershipPasswordUpdateChanged runs when the Admin has forced the User to update their password. - /// - /// - /// - protected void MembershipPasswordUpdateChanged(object sender, EventArgs e) - { - if (this.IsAdmin == false) - { - return; - } - - try - { - this.AddModuleMessage("UserPasswordUpdateChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); - - this.BindMembership(); - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs index 1c2a3e1f017..c7f81b6342a 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs @@ -32,73 +32,37 @@ public partial class MemberServices : UserModuleBase /// ----------------------------------------------------------------------------- /// - /// FormatPrice formats the Fee amount and filters out null-values. + /// DataBind binds the data to the controls. /// - /// - /// - /// The price to format. - /// The correctly formatted price. /// ----------------------------------------------------------------------------- - private string FormatPrice(float price) - { - string formatPrice = Null.NullString; - try - { - if (price != Null.NullSingle) - { - formatPrice = price.ToString("##0.00"); - } - else - { - formatPrice = string.Empty; - } - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - - return formatPrice; - } - - private void Subscribe(int roleID, bool cancel) + public override void DataBind() { - RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == roleID); - - if (objRole.IsPublic && objRole.ServiceFee == 0.0) + if (this.Request.IsAuthenticated) { - RoleController.Instance.UpdateUserRole(this.PortalId, this.UserInfo.UserID, roleID, RoleStatus.Approved, false, cancel); + Localization.LocalizeDataGrid(ref this.grdServices, this.LocalResourceFile); + this.grdServices.DataSource = RoleController.Instance.GetUserRoles(this.UserInfo, false); + this.grdServices.DataBind(); - // Raise SubscriptionUpdated Event - this.OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(cancel, objRole.RoleName)); - } - else - { - if (!cancel) - { - this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID, true); - } - else - { - this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID + "&cancel=1", true); - } + // if no service available then hide options + this.ServicesRow.Visible = this.grdServices.Items.Count > 0; } - } - - private void UseTrial(int roleID) + } + + /// ----------------------------------------------------------------------------- + /// + /// Raises the SubscriptionUpdated Event. + /// + /// ----------------------------------------------------------------------------- + public void OnSubscriptionUpdated(SubscriptionUpdatedEventArgs e) { - RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == roleID); - - if (objRole.IsPublic && objRole.TrialFee == 0.0) + if (this.IsUserOrAdmin == false) { - RoleController.Instance.UpdateUserRole(this.PortalId, this.UserInfo.UserID, roleID, RoleStatus.Approved, false, false); - - // Raise SubscriptionUpdated Event - this.OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName)); + return; } - else + + if (this.SubscriptionUpdated != null) { - this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID, true); + this.SubscriptionUpdated(this, e); } } @@ -173,6 +137,78 @@ protected string FormatPrice(float price, int period, string frequency) return formatPrice; } + + /// ----------------------------------------------------------------------------- + /// + /// FormatPrice formats the Fee amount and filters out null-values. + /// + /// + /// + /// The price to format. + /// The correctly formatted price. + /// ----------------------------------------------------------------------------- + private string FormatPrice(float price) + { + string formatPrice = Null.NullString; + try + { + if (price != Null.NullSingle) + { + formatPrice = price.ToString("##0.00"); + } + else + { + formatPrice = string.Empty; + } + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + + return formatPrice; + } + + private void Subscribe(int roleID, bool cancel) + { + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == roleID); + + if (objRole.IsPublic && objRole.ServiceFee == 0.0) + { + RoleController.Instance.UpdateUserRole(this.PortalId, this.UserInfo.UserID, roleID, RoleStatus.Approved, false, cancel); + + // Raise SubscriptionUpdated Event + this.OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(cancel, objRole.RoleName)); + } + else + { + if (!cancel) + { + this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID, true); + } + else + { + this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID + "&cancel=1", true); + } + } + } + + private void UseTrial(int roleID) + { + RoleInfo objRole = RoleController.Instance.GetRole(this.PortalSettings.PortalId, r => r.RoleID == roleID); + + if (objRole.IsPublic && objRole.TrialFee == 0.0) + { + RoleController.Instance.UpdateUserRole(this.PortalId, this.UserInfo.UserID, roleID, RoleStatus.Approved, false, false); + + // Raise SubscriptionUpdated Event + this.OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName)); + } + else + { + this.Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + this.TabId + "&RoleID=" + roleID, true); + } + } /// ----------------------------------------------------------------------------- /// @@ -325,42 +361,6 @@ protected bool ShowTrial(int roleID) return showTrial; } - /// ----------------------------------------------------------------------------- - /// - /// DataBind binds the data to the controls. - /// - /// ----------------------------------------------------------------------------- - public override void DataBind() - { - if (this.Request.IsAuthenticated) - { - Localization.LocalizeDataGrid(ref this.grdServices, this.LocalResourceFile); - this.grdServices.DataSource = RoleController.Instance.GetUserRoles(this.UserInfo, false); - this.grdServices.DataBind(); - - // if no service available then hide options - this.ServicesRow.Visible = this.grdServices.Items.Count > 0; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Raises the SubscriptionUpdated Event. - /// - /// ----------------------------------------------------------------------------- - public void OnSubscriptionUpdated(SubscriptionUpdatedEventArgs e) - { - if (this.IsUserOrAdmin == false) - { - return; - } - - if (this.SubscriptionUpdated != null) - { - this.SubscriptionUpdated(this, e); - } - } - /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. @@ -377,6 +377,30 @@ protected override void OnLoad(EventArgs e) this.lblRSVP.Text = string.Empty; } + protected void grdServices_ItemCommand(object source, DataGridCommandEventArgs e) + { + string commandName = e.CommandName; + int roleID = Convert.ToInt32(e.CommandArgument); + if (commandName == Localization.GetString("Subscribe", this.LocalResourceFile) || commandName == Localization.GetString("Renew", this.LocalResourceFile)) + { + // Subscribe + this.Subscribe(roleID, false); + } + else if (commandName == Localization.GetString("Unsubscribe", this.LocalResourceFile)) + { + // Unsubscribe + this.Subscribe(roleID, true); + } + else if (commandName == "UseTrial") + { + // Use Trial + this.UseTrial(roleID); + } + + // Rebind Grid + this.DataBind(); + } + /// ----------------------------------------------------------------------------- /// /// cmdRSVP_Click runs when the Subscribe to RSVP Code Roles Button is clicked. @@ -424,30 +448,6 @@ private void cmdRSVP_Click(object sender, EventArgs e) this.DataBind(); } - - protected void grdServices_ItemCommand(object source, DataGridCommandEventArgs e) - { - string commandName = e.CommandName; - int roleID = Convert.ToInt32(e.CommandArgument); - if (commandName == Localization.GetString("Subscribe", this.LocalResourceFile) || commandName == Localization.GetString("Renew", this.LocalResourceFile)) - { - // Subscribe - this.Subscribe(roleID, false); - } - else if (commandName == Localization.GetString("Unsubscribe", this.LocalResourceFile)) - { - // Unsubscribe - this.Subscribe(roleID, true); - } - else if (commandName == "UseTrial") - { - // Use Trial - this.UseTrial(roleID); - } - - // Rebind Grid - this.DataBind(); - } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs index 1e8dcb4719d..72d616671af 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs @@ -38,6 +38,17 @@ public Membership() this._navigationManager = this.DependencyProvider.GetRequiredService(); } + /// ----------------------------------------------------------------------------- + /// + /// Raises the MembershipAuthorized Event + /// + /// ----------------------------------------------------------------------------- + public event EventHandler MembershipAuthorized; + + public event EventHandler MembershipPasswordUpdateChanged; + + public event EventHandler MembershipUnAuthorized; + /// ----------------------------------------------------------------------------- /// /// Gets the UserMembership associated with this control. @@ -57,17 +68,6 @@ public UserMembership UserMembership } } - /// ----------------------------------------------------------------------------- - /// - /// Raises the MembershipAuthorized Event - /// - /// ----------------------------------------------------------------------------- - public event EventHandler MembershipAuthorized; - - public event EventHandler MembershipPasswordUpdateChanged; - - public event EventHandler MembershipUnAuthorized; - public event EventHandler MembershipUnLocked; public event EventHandler MembershipPromoteToSuperuser; diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Password.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Password.ascx.cs index a1c10d1bc02..ae0bcfb18ab 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Password.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Password.ascx.cs @@ -40,16 +40,12 @@ public partial class Password : UserModuleBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Password)); - protected bool UseCaptcha - { - get - { - return Convert.ToBoolean(GetSetting(this.PortalId, "Security_CaptchaChangePassword")); - } - } - public delegate void PasswordUpdatedEventHandler(object sender, PasswordUpdatedEventArgs e); + public event PasswordUpdatedEventHandler PasswordUpdated; + + public event PasswordUpdatedEventHandler PasswordQuestionAnswerUpdated; + /// ----------------------------------------------------------------------------- /// /// Gets the UserMembership associated with this control. @@ -68,9 +64,13 @@ public UserMembership Membership } } - public event PasswordUpdatedEventHandler PasswordUpdated; - - public event PasswordUpdatedEventHandler PasswordQuestionAnswerUpdated; + protected bool UseCaptcha + { + get + { + return Convert.ToBoolean(GetSetting(this.PortalId, "Security_CaptchaChangePassword")); + } + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs index 090be2ad39b..5266992810a 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs @@ -27,20 +27,6 @@ namespace DesktopModules.Admin.Security /// ----------------------------------------------------------------------------- public partial class DNNProfile : ProfileUserControlBase { - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets whether to display the Visibility controls. - /// - /// ----------------------------------------------------------------------------- - protected bool ShowVisibility - { - get - { - object setting = GetSetting(this.PortalId, "Profile_DisplayVisibility"); - return Convert.ToBoolean(setting) && this.IsUser; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the EditorMode. @@ -71,6 +57,20 @@ public bool IsValid return this.ProfileProperties.IsValid || this.IsAdmin; } } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether to display the Visibility controls. + /// + /// ----------------------------------------------------------------------------- + protected bool ShowVisibility + { + get + { + object setting = GetSetting(this.PortalId, "Profile_DisplayVisibility"); + return Convert.ToBoolean(setting) && this.IsUser; + } + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs index 8d42967d175..fef019515ca 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs @@ -32,45 +32,19 @@ namespace DotNetNuke.Modules.Admin.Users /// ----------------------------------------------------------------------------- public partial class ProfileDefinitions : PortalModuleBase, IActionable { + private const int COLUMN_REQUIRED = 11; + private const int COLUMN_VISIBLE = 12; + private const int COLUMN_MOVE_DOWN = 2; + private readonly INavigationManager _navigationManager; public ProfileDefinitions() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - - private const int COLUMN_REQUIRED = 11; - private const int COLUMN_VISIBLE = 12; - private const int COLUMN_MOVE_DOWN = 2; private const int COLUMN_MOVE_UP = 3; private ProfilePropertyDefinitionCollection _profileProperties; private bool _requiredColumnHidden = false; - - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets whether we are dealing with SuperUsers. - /// - /// ----------------------------------------------------------------------------- - protected bool IsSuperUser - { - get - { - return Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the collection of Profile Proeprties. - /// - /// ----------------------------------------------------------------------------- - protected ProfilePropertyDefinitionCollection ProfileProperties - { - get - { - return this._profileProperties ?? (this._profileProperties = ProfileController.GetPropertyDefinitionsByPortal(this.UsersPortalId, false, false)); - } - } /// ----------------------------------------------------------------------------- /// @@ -106,25 +80,6 @@ public string ReturnUrl return returnURL; } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the Portal Id whose Users we are managing. - /// - /// ----------------------------------------------------------------------------- - protected int UsersPortalId - { - get - { - int intPortalId = this.PortalId; - if (this.IsSuperUser) - { - intPortalId = Null.NullInteger; - } - - return intPortalId; - } - } public ModuleActionCollection ModuleActions { @@ -157,6 +112,107 @@ public ModuleActionCollection ModuleActions } } + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether we are dealing with SuperUsers. + /// + /// ----------------------------------------------------------------------------- + protected bool IsSuperUser + { + get + { + return Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the collection of Profile Proeprties. + /// + /// ----------------------------------------------------------------------------- + protected ProfilePropertyDefinitionCollection ProfileProperties + { + get + { + return this._profileProperties ?? (this._profileProperties = ProfileController.GetPropertyDefinitionsByPortal(this.UsersPortalId, false, false)); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Portal Id whose Users we are managing. + /// + /// ----------------------------------------------------------------------------- + protected int UsersPortalId + { + get + { + int intPortalId = this.PortalId; + if (this.IsSuperUser) + { + intPortalId = Null.NullInteger; + } + + return intPortalId; + } + } + + public string DisplayDataType(ProfilePropertyDefinition definition) + { + string retValue = Null.NullString; + var listController = new ListController(); + ListEntryInfo definitionEntry = listController.GetListEntryInfo("DataType", definition.DataType); + if (definitionEntry != null) + { + retValue = definitionEntry.Value; + } + + return retValue; + } + + public string DisplayDefaultVisibility(ProfilePropertyDefinition definition) + { + string retValue = Null.NullString; + if (!string.IsNullOrEmpty(definition.DefaultVisibility.ToString())) + { + retValue = this.LocalizeString(definition.DefaultVisibility.ToString()) ?? definition.DefaultVisibility.ToString(); + } + + return retValue; + } + + protected override void LoadViewState(object savedState) + { + if (savedState != null) + { + // Load State from the array of objects that was saved with SaveViewState. + var myState = (object[])savedState; + + // Load Base Controls ViewState + if (myState[0] != null) + { + base.LoadViewState(myState[0]); + } + + // Load ModuleID + if (myState[1] != null) + { + this._profileProperties = (ProfilePropertyDefinitionCollection)myState[1]; + } + } + } + + protected override object SaveViewState() + { + var allStates = new object[2]; + + // Save the Base Controls ViewState + allStates[0] = base.SaveViewState(); + allStates[1] = this.ProfileProperties; + + return allStates; + } + /// ----------------------------------------------------------------------------- /// /// Helper function that determines whether the client-side functionality is possible. @@ -337,62 +393,6 @@ private void ProcessPostBack() this.ProfileProperties.Sort(); } - - protected override void LoadViewState(object savedState) - { - if (savedState != null) - { - // Load State from the array of objects that was saved with SaveViewState. - var myState = (object[])savedState; - - // Load Base Controls ViewState - if (myState[0] != null) - { - base.LoadViewState(myState[0]); - } - - // Load ModuleID - if (myState[1] != null) - { - this._profileProperties = (ProfilePropertyDefinitionCollection)myState[1]; - } - } - } - - protected override object SaveViewState() - { - var allStates = new object[2]; - - // Save the Base Controls ViewState - allStates[0] = base.SaveViewState(); - allStates[1] = this.ProfileProperties; - - return allStates; - } - - public string DisplayDataType(ProfilePropertyDefinition definition) - { - string retValue = Null.NullString; - var listController = new ListController(); - ListEntryInfo definitionEntry = listController.GetListEntryInfo("DataType", definition.DataType); - if (definitionEntry != null) - { - retValue = definitionEntry.Value; - } - - return retValue; - } - - public string DisplayDefaultVisibility(ProfilePropertyDefinition definition) - { - string retValue = Null.NullString; - if (!string.IsNullOrEmpty(definition.DefaultVisibility.ToString())) - { - retValue = this.LocalizeString(definition.DefaultVisibility.ToString()) ?? definition.DefaultVisibility.ToString(); - } - - return retValue; - } public void Update() { @@ -491,6 +491,41 @@ protected override void OnLoad(EventArgs e) } } + /// ----------------------------------------------------------------------------- + /// + /// grdProfileProperties_ItemDataBound runs when a row in the grid is bound to its data source + /// Grid. + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected void grdProfileProperties_ItemDataBound(object sender, DataGridItemEventArgs e) + { + DataGridItem item = e.Item; + if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + { + Control imgColumnControl = item.Controls[1].Controls[0]; + if (imgColumnControl is ImageButton) + { + var delImage = (ImageButton)imgColumnControl; + var profProperty = (ProfilePropertyDefinition)item.DataItem; + + switch (profProperty.PropertyName.ToLowerInvariant()) + { + case "lastname": + case "firstname": + case "preferredtimezone": + case "preferredlocale": + delImage.Visible = false; + break; + default: + delImage.Visible = true; + break; + } + } + } + } + /// ----------------------------------------------------------------------------- /// /// cmdRefresh_Click runs when the refresh button is clciked. @@ -610,40 +645,5 @@ private void grdProfileProperties_ItemCreated(object sender, DataGridItemEventAr } } } - - /// ----------------------------------------------------------------------------- - /// - /// grdProfileProperties_ItemDataBound runs when a row in the grid is bound to its data source - /// Grid. - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected void grdProfileProperties_ItemDataBound(object sender, DataGridItemEventArgs e) - { - DataGridItem item = e.Item; - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - Control imgColumnControl = item.Controls[1].Controls[0]; - if (imgColumnControl is ImageButton) - { - var delImage = (ImageButton)imgColumnControl; - var profProperty = (ProfilePropertyDefinition)item.DataItem; - - switch (profProperty.PropertyName.ToLowerInvariant()) - { - case "lastname": - case "firstname": - case "preferredtimezone": - case "preferredlocale": - delImage.Visible = false; - break; - default: - delImage.Visible = true; - break; - } - } - } - } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs index 2cdf8ed4f8f..f84cb3a13c9 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs @@ -56,6 +56,23 @@ public SecurityRoles() this._navigationManager = this.DependencyProvider.GetRequiredService(); } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the ParentModule (if one exists). + /// + /// + /// + /// ----------------------------------------------------------------------------- + public PortalModuleBase ParentModule { get; set; } + + public ModuleActionCollection ModuleActions + { + get + { + return new ModuleActionCollection(); + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the Return Url for the page. @@ -177,20 +194,50 @@ protected int PageSize /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the ParentModule (if one exists). + /// DataBind binds the data to the controls. + /// + /// ----------------------------------------------------------------------------- + public override void DataBind() + { + if (!ModulePermissionController.CanEditModuleContent(this.ModuleConfiguration)) + { + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); + } + + base.DataBind(); + + // Localize Headers + Localization.LocalizeDataGrid(ref this.grdUserRoles, this.LocalResourceFile); + + // Bind the role data to the datalist + this.BindData(); + + this.BindGrid(); + } + + /// ----------------------------------------------------------------------------- + /// + /// DeleteButonVisible returns a boolean indicating if the delete button for + /// the specified UserID, RoleID pair should be shown. /// /// /// + /// The ID of the user to check delete button visibility for. + /// The ID of the role to check delete button visibility for. + /// /// ----------------------------------------------------------------------------- - public PortalModuleBase ParentModule { get; set; } - - public ModuleActionCollection ModuleActions + public bool DeleteButtonVisible(int UserID, int RoleID) { - get + // [DNN-4285] Check if the role can be removed (only handles case of Administrator and Administrator Role + bool canDelete = RoleController.CanRemoveUserFromRole(this.PortalSettings, UserID, RoleID); + if (RoleID == this.PortalSettings.AdministratorRoleId && canDelete) { - return new ModuleActionCollection(); + // User can only delete if in Admin role + canDelete = PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); } - } + + return canDelete; + } /// ----------------------------------------------------------------------------- /// @@ -405,53 +452,6 @@ private void GetDates(int UserId, int RoleId) this.effectiveDatePicker.SelectedDate = effectiveDate; this.expiryDatePicker.SelectedDate = expiryDate; } - - /// ----------------------------------------------------------------------------- - /// - /// DataBind binds the data to the controls. - /// - /// ----------------------------------------------------------------------------- - public override void DataBind() - { - if (!ModulePermissionController.CanEditModuleContent(this.ModuleConfiguration)) - { - this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); - } - - base.DataBind(); - - // Localize Headers - Localization.LocalizeDataGrid(ref this.grdUserRoles, this.LocalResourceFile); - - // Bind the role data to the datalist - this.BindData(); - - this.BindGrid(); - } - - /// ----------------------------------------------------------------------------- - /// - /// DeleteButonVisible returns a boolean indicating if the delete button for - /// the specified UserID, RoleID pair should be shown. - /// - /// - /// - /// The ID of the user to check delete button visibility for. - /// The ID of the role to check delete button visibility for. - /// - /// ----------------------------------------------------------------------------- - public bool DeleteButtonVisible(int UserID, int RoleID) - { - // [DNN-4285] Check if the role can be removed (only handles case of Administrator and Administrator Role - bool canDelete = RoleController.CanRemoveUserFromRole(this.PortalSettings, UserID, RoleID); - if (RoleID == this.PortalSettings.AdministratorRoleId && canDelete) - { - // User can only delete if in Admin role - canDelete = PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); - } - - return canDelete; - } /// ----------------------------------------------------------------------------- /// @@ -484,6 +484,34 @@ public string FormatUser(int UserID, string DisplayName) { return "" + DisplayName + ""; } + + public void cmdDeleteUserRole_click(object sender, ImageClickEventArgs e) + { + if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) == false) + { + return; + } + + try + { + var cmdDeleteUserRole = (ImageButton)sender; + int roleId = Convert.ToInt32(cmdDeleteUserRole.Attributes["roleId"]); + int userId = Convert.ToInt32(cmdDeleteUserRole.Attributes["userId"]); + + RoleInfo role = RoleController.Instance.GetRole(this.PortalId, r => r.RoleID == roleId); + if (!RoleController.DeleteUserRole(UserController.GetUserById(this.PortalId, userId), role, this.PortalSettings, this.chkNotify.Checked)) + { + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("RoleRemoveError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + } + + this.BindGrid(); + } + catch (Exception exc) + { + Exceptions.LogException(exc); + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("RoleRemoveError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + } + } /// ----------------------------------------------------------------------------- /// @@ -569,6 +597,30 @@ protected override void OnLoad(EventArgs e) } } + protected void grdUserRoles_ItemDataBound(object sender, DataGridItemEventArgs e) + { + DataGridItem item = e.Item; + if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + { + var userRole = (UserRoleInfo)item.DataItem; + if (this.RoleId == Null.NullInteger) + { + if (userRole.RoleID == Convert.ToInt32(this.cboRoles.SelectedValue)) + { + this.cmdAdd.Text = Localization.GetString("UpdateRole.Text", this.LocalResourceFile); + } + } + + if (this.UserId == Null.NullInteger) + { + if (userRole.UserID == this.SelectedUserID) + { + this.cmdAdd.Text = Localization.GetString("UpdateRole.Text", this.LocalResourceFile); + } + } + } + } + /// ----------------------------------------------------------------------------- /// /// cboUsers_SelectedIndexChanged runs when the selected User is changed in the @@ -702,34 +754,6 @@ private void cmdAdd_Click(object sender, EventArgs e) } } - public void cmdDeleteUserRole_click(object sender, ImageClickEventArgs e) - { - if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) == false) - { - return; - } - - try - { - var cmdDeleteUserRole = (ImageButton)sender; - int roleId = Convert.ToInt32(cmdDeleteUserRole.Attributes["roleId"]); - int userId = Convert.ToInt32(cmdDeleteUserRole.Attributes["userId"]); - - RoleInfo role = RoleController.Instance.GetRole(this.PortalId, r => r.RoleID == roleId); - if (!RoleController.DeleteUserRole(UserController.GetUserById(this.PortalId, userId), role, this.PortalSettings, this.chkNotify.Checked)) - { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("RoleRemoveError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - } - - this.BindGrid(); - } - catch (Exception exc) - { - Exceptions.LogException(exc); - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("RoleRemoveError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - } - } - /// ----------------------------------------------------------------------------- /// /// grdUserRoles_ItemCreated runs when an item in the UserRoles Grid is created. @@ -768,29 +792,5 @@ private void grdUserRoles_ItemCreated(object sender, DataGridItemEventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - - protected void grdUserRoles_ItemDataBound(object sender, DataGridItemEventArgs e) - { - DataGridItem item = e.Item; - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - var userRole = (UserRoleInfo)item.DataItem; - if (this.RoleId == Null.NullInteger) - { - if (userRole.RoleID == Convert.ToInt32(this.cboRoles.SelectedValue)) - { - this.cmdAdd.Text = Localization.GetString("UpdateRole.Text", this.LocalResourceFile); - } - } - - if (this.UserId == Null.NullInteger) - { - if (userRole.UserID == this.SelectedUserID) - { - this.cmdAdd.Text = Localization.GetString("UpdateRole.Text", this.LocalResourceFile); - } - } - } - } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs index 26dc3eee3be..66005777fbb 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs @@ -107,124 +107,6 @@ public string CssClass } } - /// - /// method checks to see if its allowed to change the username - /// valid if a host, or an admin where the username is in only 1 portal. - /// - /// - private bool CanUpdateUsername() - { - // do not allow for non-logged in users - if (this.Request.IsAuthenticated == false || this.AddUser) - { - return false; - } - - // can only update username if a host/admin and account being managed is not a superuser - if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) - { - // only allow updates for non-superuser accounts - if (this.User.IsSuperUser == false) - { - return true; - } - } - - // if an admin, check if the user is only within this portal - if (UserController.Instance.GetCurrentUserInfo().IsInRole(this.PortalSettings.AdministratorRoleName)) - { - // only allow updates for non-superuser accounts - if (this.User.IsSuperUser) - { - return false; - } - - if (PortalController.GetPortalsByUser(this.User.UserID).Count == 1) - { - return true; - } - } - - return false; - } - - private void UpdateDisplayName() - { - // Update DisplayName to conform to Format - if (!string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) - { - this.User.UpdateDisplayName(this.PortalSettings.Registration.DisplayNameFormat); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Validate validates the User. - /// - private bool Validate() - { - // Check User Editor - bool _IsValid = this.userForm.IsValid; - - // Check Password is valid - if (this.AddUser && this.ShowPassword) - { - this.CreateStatus = UserCreateStatus.AddUser; - if (!this.chkRandom.Checked) - { - // 1. Check Password is Valid - if (this.CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(this.txtPassword.Text)) - { - this.CreateStatus = UserCreateStatus.InvalidPassword; - } - - if (this.CreateStatus == UserCreateStatus.AddUser) - { - this.User.Membership.Password = this.txtPassword.Text; - } - } - else - { - // Generate a random password for the user - this.User.Membership.Password = UserController.GeneratePassword(); - } - - // Check Question/Answer - if (this.CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) - { - if (string.IsNullOrEmpty(this.txtQuestion.Text)) - { - // Invalid Question - this.CreateStatus = UserCreateStatus.InvalidQuestion; - } - else - { - this.User.Membership.PasswordQuestion = this.txtQuestion.Text; - } - - if (this.CreateStatus == UserCreateStatus.AddUser) - { - if (string.IsNullOrEmpty(this.txtAnswer.Text)) - { - // Invalid Question - this.CreateStatus = UserCreateStatus.InvalidAnswer; - } - else - { - this.User.Membership.PasswordAnswer = this.txtAnswer.Text; - } - } - } - - if (this.CreateStatus != UserCreateStatus.AddUser) - { - _IsValid = false; - } - } - - return _IsValid; - } - /// ----------------------------------------------------------------------------- /// /// CreateUser creates a new user in the Database. @@ -402,6 +284,124 @@ public override void DataBind() } } + /// + /// method checks to see if its allowed to change the username + /// valid if a host, or an admin where the username is in only 1 portal. + /// + /// + private bool CanUpdateUsername() + { + // do not allow for non-logged in users + if (this.Request.IsAuthenticated == false || this.AddUser) + { + return false; + } + + // can only update username if a host/admin and account being managed is not a superuser + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) + { + // only allow updates for non-superuser accounts + if (this.User.IsSuperUser == false) + { + return true; + } + } + + // if an admin, check if the user is only within this portal + if (UserController.Instance.GetCurrentUserInfo().IsInRole(this.PortalSettings.AdministratorRoleName)) + { + // only allow updates for non-superuser accounts + if (this.User.IsSuperUser) + { + return false; + } + + if (PortalController.GetPortalsByUser(this.User.UserID).Count == 1) + { + return true; + } + } + + return false; + } + + private void UpdateDisplayName() + { + // Update DisplayName to conform to Format + if (!string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) + { + this.User.UpdateDisplayName(this.PortalSettings.Registration.DisplayNameFormat); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Validate validates the User. + /// + private bool Validate() + { + // Check User Editor + bool _IsValid = this.userForm.IsValid; + + // Check Password is valid + if (this.AddUser && this.ShowPassword) + { + this.CreateStatus = UserCreateStatus.AddUser; + if (!this.chkRandom.Checked) + { + // 1. Check Password is Valid + if (this.CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(this.txtPassword.Text)) + { + this.CreateStatus = UserCreateStatus.InvalidPassword; + } + + if (this.CreateStatus == UserCreateStatus.AddUser) + { + this.User.Membership.Password = this.txtPassword.Text; + } + } + else + { + // Generate a random password for the user + this.User.Membership.Password = UserController.GeneratePassword(); + } + + // Check Question/Answer + if (this.CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) + { + if (string.IsNullOrEmpty(this.txtQuestion.Text)) + { + // Invalid Question + this.CreateStatus = UserCreateStatus.InvalidQuestion; + } + else + { + this.User.Membership.PasswordQuestion = this.txtQuestion.Text; + } + + if (this.CreateStatus == UserCreateStatus.AddUser) + { + if (string.IsNullOrEmpty(this.txtAnswer.Text)) + { + // Invalid Question + this.CreateStatus = UserCreateStatus.InvalidAnswer; + } + else + { + this.User.Membership.PasswordAnswer = this.txtAnswer.Text; + } + } + } + + if (this.CreateStatus != UserCreateStatus.AddUser) + { + _IsValid = false; + } + } + + return _IsValid; + } + /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. diff --git a/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs index 0ca99563148..50fc2e80b8b 100644 --- a/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs @@ -15,17 +15,17 @@ namespace DotNetNuke.Modules.UrlManagement public partial class ProviderSettings : ModuleUserControlBase { + private readonly INavigationManager _navigationManager; + private int _providerId; private IExtensionUrlProviderSettingsControl _providerSettingsControl; - - private string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); - - private readonly INavigationManager _navigationManager; public ProviderSettings() { this._navigationManager = Globals.DependencyProvider.GetService(); } + + private string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); protected override void OnInit(EventArgs e) { @@ -45,12 +45,12 @@ protected override void OnInit(EventArgs e) var settingsControl = this.Page.LoadControl(settingsControlSrc); - this.providerSettingsPlaceHolder.Controls.Add(settingsControl); - -// ReSharper disable SuspiciousTypeConversion.Global - this._providerSettingsControl = settingsControl as IExtensionUrlProviderSettingsControl; + this.providerSettingsPlaceHolder.Controls.Add(settingsControl); + + // ReSharper disable SuspiciousTypeConversion.Global + this._providerSettingsControl = settingsControl as IExtensionUrlProviderSettingsControl; -// ReSharper restore SuspiciousTypeConversion.Global + // ReSharper restore SuspiciousTypeConversion.Global if (this._providerSettingsControl != null) { this._providerSettingsControl.Provider = provider.ProviderConfig; diff --git a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs index a742336c5b5..feff0931bed 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs @@ -40,12 +40,6 @@ public override void LoadSettings() } } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - this.cmdLoadDefault.Click += this.cmdLoadDefault_Click; - } - public override void UpdateSettings() { try @@ -59,6 +53,12 @@ public override void UpdateSettings() Exceptions.ProcessModuleLoadException(this, exc); } } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.cmdLoadDefault.Click += this.cmdLoadDefault_Click; + } protected void cmdLoadDefault_Click(object sender, EventArgs e) { diff --git a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs index b77caf7bf5d..35f08506e51 100644 --- a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs +++ b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs @@ -38,25 +38,25 @@ public Login() } /// - /// Gets a value indicating whether gets whether the Captcha control is used to validate the login. + /// Gets a value indicating whether check if the Auth System is Enabled (for the Portal). /// - protected bool UseCaptcha + /// + public override bool Enabled { get { - return AuthenticationConfig.GetConfig(this.PortalId).UseCaptcha; + return AuthenticationConfig.GetConfig(this.PortalId).Enabled; } } /// - /// Gets a value indicating whether check if the Auth System is Enabled (for the Portal). + /// Gets a value indicating whether gets whether the Captcha control is used to validate the login. /// - /// - public override bool Enabled + protected bool UseCaptcha { get { - return AuthenticationConfig.GetConfig(this.PortalId).Enabled; + return AuthenticationConfig.GetConfig(this.PortalId).UseCaptcha; } } @@ -224,6 +224,46 @@ protected override void OnLoad(EventArgs e) this.divCaptcha1.Visible = this.UseCaptcha; this.divCaptcha2.Visible = this.UseCaptcha; } + + protected string GetRedirectUrl(bool checkSettings = true) + { + var redirectUrl = string.Empty; + var redirectAfterLogin = this.PortalSettings.Registration.RedirectAfterLogin; + if (checkSettings && redirectAfterLogin > 0) // redirect to after registration page + { + redirectUrl = this._navigationManager.NavigateURL(redirectAfterLogin); + } + else + { + if (this.Request.QueryString["returnurl"] != null) + { + // return to the url passed to register + redirectUrl = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); + + // clean the return url to avoid possible XSS attack. + redirectUrl = UrlUtils.ValidReturnUrl(redirectUrl); + + if (redirectUrl.Contains("?returnurl")) + { + string baseURL = redirectUrl.Substring( + 0, + redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal)); + string returnURL = + redirectUrl.Substring(redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal) + 11); + + redirectUrl = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); + } + } + + if (string.IsNullOrEmpty(redirectUrl)) + { + // redirect to current page + redirectUrl = this._navigationManager.NavigateURL(); + } + } + + return redirectUrl; + } private void OnLoginClick(object sender, EventArgs e) { @@ -272,54 +312,14 @@ private void OnLoginClick(object sender, EventArgs e) } // Raise UserAuthenticated Event - var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN") - { - Authenticated = authenticated, - Message = message, - RememberMe = this.chkCookie.Checked, - }; + var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN") + { + Authenticated = authenticated, + Message = message, + RememberMe = this.chkCookie.Checked, + }; this.OnUserAuthenticated(eventArgs); } } - - protected string GetRedirectUrl(bool checkSettings = true) - { - var redirectUrl = string.Empty; - var redirectAfterLogin = this.PortalSettings.Registration.RedirectAfterLogin; - if (checkSettings && redirectAfterLogin > 0) // redirect to after registration page - { - redirectUrl = this._navigationManager.NavigateURL(redirectAfterLogin); - } - else - { - if (this.Request.QueryString["returnurl"] != null) - { - // return to the url passed to register - redirectUrl = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); - - // clean the return url to avoid possible XSS attack. - redirectUrl = UrlUtils.ValidReturnUrl(redirectUrl); - - if (redirectUrl.Contains("?returnurl")) - { - string baseURL = redirectUrl.Substring( - 0, - redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal)); - string returnURL = - redirectUrl.Substring(redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal) + 11); - - redirectUrl = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); - } - } - - if (string.IsNullOrEmpty(redirectUrl)) - { - // redirect to current page - redirectUrl = this._navigationManager.NavigateURL(); - } - } - - return redirectUrl; - } } } diff --git a/DNN Platform/Website/ErrorPage.aspx.cs b/DNN Platform/Website/ErrorPage.aspx.cs index 9bea7fa9970..58de87edc27 100644 --- a/DNN Platform/Website/ErrorPage.aspx.cs +++ b/DNN Platform/Website/ErrorPage.aspx.cs @@ -35,36 +35,6 @@ namespace DotNetNuke.Services.Exceptions /// ----------------------------------------------------------------------------- public partial class ErrorPage : Page { - private void ManageError(string status) - { - string errorMode = Config.GetCustomErrorMode(); - - string errorMessage = HttpUtility.HtmlEncode(this.Request.QueryString["error"]); - string errorMessage2 = HttpUtility.HtmlEncode(this.Request.QueryString["error2"]); - string localizedMessage = Localization.GetString(status + ".Error", Localization.GlobalResourceFile); - if (localizedMessage != null) - { - localizedMessage = localizedMessage.Replace("src=\"images/403-3.gif\"", "src=\"" + this.ResolveUrl("~/images/403-3.gif") + "\""); - - if (!string.IsNullOrEmpty(errorMessage2) && ((errorMode == "Off") || ((errorMode == "RemoteOnly") && this.Request.IsLocal))) - { - this.ErrorPlaceHolder.Controls.Add(new LiteralControl(string.Format(localizedMessage, errorMessage2))); - } - else - { - this.ErrorPlaceHolder.Controls.Add(new LiteralControl(string.Format(localizedMessage, errorMessage))); - } - } - - int statusCode; - int.TryParse(status, out statusCode); - - if (statusCode > -1) - { - this.Response.StatusCode = statusCode; - } - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -131,5 +101,35 @@ protected override void OnLoad(EventArgs e) this.hypReturn.Text = localizedMessage; } + + private void ManageError(string status) + { + string errorMode = Config.GetCustomErrorMode(); + + string errorMessage = HttpUtility.HtmlEncode(this.Request.QueryString["error"]); + string errorMessage2 = HttpUtility.HtmlEncode(this.Request.QueryString["error2"]); + string localizedMessage = Localization.GetString(status + ".Error", Localization.GlobalResourceFile); + if (localizedMessage != null) + { + localizedMessage = localizedMessage.Replace("src=\"images/403-3.gif\"", "src=\"" + this.ResolveUrl("~/images/403-3.gif") + "\""); + + if (!string.IsNullOrEmpty(errorMessage2) && ((errorMode == "Off") || ((errorMode == "RemoteOnly") && this.Request.IsLocal))) + { + this.ErrorPlaceHolder.Controls.Add(new LiteralControl(string.Format(localizedMessage, errorMessage2))); + } + else + { + this.ErrorPlaceHolder.Controls.Add(new LiteralControl(string.Format(localizedMessage, errorMessage))); + } + } + + int statusCode; + int.TryParse(status, out statusCode); + + if (statusCode > -1) + { + this.Response.StatusCode = statusCode; + } + } } } diff --git a/DNN Platform/Website/Install/Install.aspx.cs b/DNN Platform/Website/Install/Install.aspx.cs index ea860758ebb..26ce9cf58f4 100644 --- a/DNN Platform/Website/Install/Install.aspx.cs +++ b/DNN Platform/Website/Install/Install.aspx.cs @@ -32,6 +32,100 @@ public partial class Install : Page private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Install)); private static readonly object installLocker = new object(); + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (Upgrade.Upgrade.UpdateNewtonsoftVersion()) + { + this.Response.Redirect(this.Request.RawUrl, true); + } + + // if previous config deleted create new empty one + string installConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Install", "DotNetNuke.install.config"); + if (!File.Exists(installConfig)) + { + File.Copy(installConfig + ".resources", installConfig); + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + Config.AddFCNMode(Config.FcnMode.Single); + + // Get current Script time-out + int scriptTimeOut = this.Server.ScriptTimeout; + + string mode = string.Empty; + if (this.Request.QueryString["mode"] != null) + { + mode = this.Request.QueryString["mode"].ToLowerInvariant(); + } + + // Disable Client side caching + this.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); + + // Check mode is not Nothing + if (mode == "none") + { + this.NoUpgrade(); + } + else + { + // Set Script timeout to MAX value + this.Server.ScriptTimeout = int.MaxValue; + + switch (Globals.Status) + { + case Globals.UpgradeStatus.Install: + this.InstallApplication(); + + // Force an App Restart + Config.Touch(); + break; + case Globals.UpgradeStatus.Upgrade: + this.UpgradeApplication(); + + // Force an App Restart + Config.Touch(); + break; + case Globals.UpgradeStatus.None: + // Check mode + switch (mode) + { + case "addportal": + this.AddPortal(); + break; + case "installresources": + this.InstallResources(); + break; + case "executescripts": + this.ExecuteScripts(); + break; + } + + break; + case Globals.UpgradeStatus.Error: + this.NoUpgrade(); + break; + } + + // restore Script timeout + this.Server.ScriptTimeout = scriptTimeOut; + } + } + + private static void RegisterInstallBegining() + { + InstallBlocker.Instance.RegisterInstallBegining(); + } + + private static void RegisterInstallEnd() + { + InstallBlocker.Instance.RegisterInstallEnd(); + } + private void ExecuteScripts() { // Start Timer @@ -192,16 +286,6 @@ private void InstallApplication() } } - private static void RegisterInstallBegining() - { - InstallBlocker.Instance.RegisterInstallBegining(); - } - - private static void RegisterInstallEnd() - { - InstallBlocker.Instance.RegisterInstallEnd(); - } - private void WriteInstallationHeader() { this.Response.Write("

Version: " + Globals.FormatVersion(DotNetNukeContext.Current.Application.Version) + "

"); @@ -510,89 +594,5 @@ private void NoUpgrade() // Write out Footer HtmlUtils.WriteFooter(this.Response); } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (Upgrade.Upgrade.UpdateNewtonsoftVersion()) - { - this.Response.Redirect(this.Request.RawUrl, true); - } - - // if previous config deleted create new empty one - string installConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Install", "DotNetNuke.install.config"); - if (!File.Exists(installConfig)) - { - File.Copy(installConfig + ".resources", installConfig); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - Config.AddFCNMode(Config.FcnMode.Single); - - // Get current Script time-out - int scriptTimeOut = this.Server.ScriptTimeout; - - string mode = string.Empty; - if (this.Request.QueryString["mode"] != null) - { - mode = this.Request.QueryString["mode"].ToLowerInvariant(); - } - - // Disable Client side caching - this.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); - - // Check mode is not Nothing - if (mode == "none") - { - this.NoUpgrade(); - } - else - { - // Set Script timeout to MAX value - this.Server.ScriptTimeout = int.MaxValue; - - switch (Globals.Status) - { - case Globals.UpgradeStatus.Install: - this.InstallApplication(); - - // Force an App Restart - Config.Touch(); - break; - case Globals.UpgradeStatus.Upgrade: - this.UpgradeApplication(); - - // Force an App Restart - Config.Touch(); - break; - case Globals.UpgradeStatus.None: - // Check mode - switch (mode) - { - case "addportal": - this.AddPortal(); - break; - case "installresources": - this.InstallResources(); - break; - case "executescripts": - this.ExecuteScripts(); - break; - } - - break; - case Globals.UpgradeStatus.Error: - this.NoUpgrade(); - break; - } - - // restore Script timeout - this.Server.ScriptTimeout = scriptTimeOut; - } - } } } diff --git a/DNN Platform/Website/Install/UpgradeWizard.aspx.cs b/DNN Platform/Website/Install/UpgradeWizard.aspx.cs index 117dbe8f21d..7dc8229cf84 100644 --- a/DNN Platform/Website/Install/UpgradeWizard.aspx.cs +++ b/DNN Platform/Website/Install/UpgradeWizard.aspx.cs @@ -37,9 +37,9 @@ namespace DotNetNuke.Services.Install /// ----------------------------------------------------------------------------- public partial class UpgradeWizard : PageBase { - private const string LocalesFile = "/Install/App_LocalResources/Locales.xml"; protected static readonly string StatusFilename = "upgradestat.log.resources.txt"; protected static new string LocalResourceFile = "~/Install/App_LocalResources/UpgradeWizard.aspx.resx"; + private const string LocalesFile = "/Install/App_LocalResources/Locales.xml"; private static string _culture; private static string[] _supportedLanguages; @@ -47,6 +47,11 @@ public partial class UpgradeWizard : PageBase private static bool _upgradeRunning; private static int _upgradeProgress; + // steps shown in UI + private static IInstallationStep upgradeDatabase = new InstallDatabaseStep(); + private static IInstallationStep upgradeExtensions = new InstallExtensionsStep(); + private static IInstallationStep iisVerification = new IISVerificationStep(); + protected Version ApplicationVersion { get @@ -78,27 +83,17 @@ private static string StatusFile private static bool IsAuthenticated { get; set; } - private void LocalizePage() + protected string LocalizeString(string key) { - this.SetBrowserLanguage(); - this.Page.Title = this.LocalizeString("Title"); - if (Globals.FormatVersion(this.ApplicationVersion) == Globals.FormatVersion(this.CurrentVersion)) - { - this.versionLabel.Visible = false; - this.currentVersionLabel.Visible = false; - this.versionsMatch.Text = this.LocalizeString("VersionsMatch"); - if (Globals.IncrementalVersionExists(this.CurrentVersion)) - { - this.versionsMatch.Text = this.LocalizeString("VersionsMatchButIncrementalExists"); - } - } - else - { - this.versionLabel.Text = string.Format(this.LocalizeString("Version"), Globals.FormatVersion(this.ApplicationVersion)); - this.currentVersionLabel.Text = string.Format(this.LocalizeString("CurrentVersion"), Globals.FormatVersion(this.CurrentVersion)); - } + return Localization.GetString(key, LocalResourceFile, _culture); } + protected override void OnError(EventArgs e) + { + HttpContext.Current.Response.Clear(); + HttpContext.Current.Server.Transfer("~/ErrorPage.aspx"); + } + private static void GetInstallerLocales() { var filePath = Globals.ApplicationMapPath + LocalesFile.Replace("/", "\\"); @@ -135,28 +130,6 @@ private static void GetInstallerLocales() } } - private void SetBrowserLanguage() - { - string cultureCode; - if (string.IsNullOrEmpty(this.PageLocale.Value) && string.IsNullOrEmpty(_culture)) - { - cultureCode = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(_supportedLanguages); - } - else if (string.IsNullOrEmpty(this.PageLocale.Value) && !string.IsNullOrEmpty(_culture)) - { - cultureCode = _culture; - } - else - { - cultureCode = this.PageLocale.Value; - } - - this.PageLocale.Value = cultureCode; - _culture = cultureCode; - - Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureCode); - } - private static string LocalizeStringStatic(string key) { return Localization.GetString(key, LocalResourceFile, _culture); @@ -252,6 +225,49 @@ private static void LaunchUpgrade() // restore Script timeout HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; } + + private void LocalizePage() + { + this.SetBrowserLanguage(); + this.Page.Title = this.LocalizeString("Title"); + if (Globals.FormatVersion(this.ApplicationVersion) == Globals.FormatVersion(this.CurrentVersion)) + { + this.versionLabel.Visible = false; + this.currentVersionLabel.Visible = false; + this.versionsMatch.Text = this.LocalizeString("VersionsMatch"); + if (Globals.IncrementalVersionExists(this.CurrentVersion)) + { + this.versionsMatch.Text = this.LocalizeString("VersionsMatchButIncrementalExists"); + } + } + else + { + this.versionLabel.Text = string.Format(this.LocalizeString("Version"), Globals.FormatVersion(this.ApplicationVersion)); + this.currentVersionLabel.Text = string.Format(this.LocalizeString("CurrentVersion"), Globals.FormatVersion(this.CurrentVersion)); + } + } + + private void SetBrowserLanguage() + { + string cultureCode; + if (string.IsNullOrEmpty(this.PageLocale.Value) && string.IsNullOrEmpty(_culture)) + { + cultureCode = TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(_supportedLanguages); + } + else if (string.IsNullOrEmpty(this.PageLocale.Value) && !string.IsNullOrEmpty(_culture)) + { + cultureCode = _culture; + } + else + { + cultureCode = this.PageLocale.Value; + } + + this.PageLocale.Value = cultureCode; + _culture = cultureCode; + + Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureCode); + } private static void CurrentStepActivity(string status) { @@ -324,17 +340,6 @@ private void SslRequiredCheck() } } - protected string LocalizeString(string key) - { - return Localization.GetString(key, LocalResourceFile, _culture); - } - - protected override void OnError(EventArgs e) - { - HttpContext.Current.Response.Clear(); - HttpContext.Current.Server.Transfer("~/ErrorPage.aspx"); - } - /// ----------------------------------------------------------------------------- /// /// Page_Init runs when the Page is initialised. @@ -392,11 +397,6 @@ protected override void OnLoad(EventArgs e) Upgrade.Upgrade.RemoveInvalidAntiForgeryCookie(); } } - - // steps shown in UI - private static IInstallationStep upgradeDatabase = new InstallDatabaseStep(); - private static IInstallationStep upgradeExtensions = new InstallExtensionsStep(); - private static IInstallationStep iisVerification = new IISVerificationStep(); // Ordered List of Steps (and weight in percentage) to be executed private static IDictionary _steps = new Dictionary @@ -422,35 +422,6 @@ public static Tuple ValidateInput(Dictionary accou return new Tuple(result, errorMsg); } - private static bool VerifyHostUser(Dictionary accountInfo, out string errorMsg) - { - var result = true; - errorMsg = string.Empty; - - UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE; - var userRequestIpAddressController = UserRequestIPAddressController.Instance; - var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request)); - UserInfo hostUser = UserController.ValidateUser(-1, accountInfo["username"], accountInfo["password"], "DNN", string.Empty, string.Empty, ipAddress, ref loginStatus); - - if (loginStatus == UserLoginStatus.LOGIN_FAILURE || !hostUser.IsSuperUser) - { - result = false; - errorMsg = LocalizeStringStatic("InvalidCredentials"); - } - else - { - IsAuthenticated = true; - } - - if (result && (!accountInfo.ContainsKey("acceptTerms") || accountInfo["acceptTerms"] != "Y")) - { - result = false; - errorMsg = LocalizeStringStatic("AcceptTerms.Required"); - } - - return result; - } - [System.Web.Services.WebMethod] public static void RunUpgrade(Dictionary accountInfo) { @@ -513,5 +484,34 @@ public static object GetInstallationLog(int startRow) return data; } + + private static bool VerifyHostUser(Dictionary accountInfo, out string errorMsg) + { + var result = true; + errorMsg = string.Empty; + + UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE; + var userRequestIpAddressController = UserRequestIPAddressController.Instance; + var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request)); + UserInfo hostUser = UserController.ValidateUser(-1, accountInfo["username"], accountInfo["password"], "DNN", string.Empty, string.Empty, ipAddress, ref loginStatus); + + if (loginStatus == UserLoginStatus.LOGIN_FAILURE || !hostUser.IsSuperUser) + { + result = false; + errorMsg = LocalizeStringStatic("InvalidCredentials"); + } + else + { + IsAuthenticated = true; + } + + if (result && (!accountInfo.ContainsKey("acceptTerms") || accountInfo["acceptTerms"] != "Y")) + { + result = false; + errorMsg = LocalizeStringStatic("AcceptTerms.Required"); + } + + return result; + } } } diff --git a/DNN Platform/Website/KeepAlive.aspx.cs b/DNN Platform/Website/KeepAlive.aspx.cs index 3e322926b2f..6f451b591f8 100644 --- a/DNN Platform/Website/KeepAlive.aspx.cs +++ b/DNN Platform/Website/KeepAlive.aspx.cs @@ -8,11 +8,6 @@ namespace DotNetNuke.Common.Utilities public partial class KeepAlive : Page { - // This call is required by the Web Form Designer. - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -26,5 +21,10 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); } + + // This call is required by the Web Form Designer. + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Containers/DropDownActions.ascx.cs b/DNN Platform/Website/admin/Containers/DropDownActions.ascx.cs index 624fc194676..fa1ef59e22d 100644 --- a/DNN Platform/Website/admin/Containers/DropDownActions.ascx.cs +++ b/DNN Platform/Website/admin/Containers/DropDownActions.ascx.cs @@ -37,9 +37,18 @@ public NavigationProvider Control } } - private void Page_Load(object sender, EventArgs e) + public void BindDropDown() { - this.cmdGo.Attributes.Add("onclick", "if (cmdGo_OnClick(dnn.dom.getById('" + this.Control.NavigationControl.ClientID + "')) == false) return false;"); + DNNNodeCollection objNodes; + objNodes = Navigation.GetActionNodes(this.ActionRoot, this); + foreach (DNNNode objNode in objNodes) + { + this.ProcessNodes(objNode); + } + + this.Control.Bind(objNodes); + + this.Visible = this.DisplayControl(objNodes); } protected override void OnLoad(EventArgs e) @@ -58,6 +67,20 @@ protected override void OnLoad(EventArgs e) } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this.m_objControl = NavigationProvider.Instance(this.ProviderName); + this.Control.ControlID = "ctl" + this.ID; + this.Control.Initialize(); + this.spActions.Controls.Add(this.Control.NavigationControl); + } + + private void Page_Load(object sender, EventArgs e) + { + this.cmdGo.Attributes.Add("onclick", "if (cmdGo_OnClick(dnn.dom.getById('" + this.Control.NavigationControl.ClientID + "')) == false) return false;"); + } + private void cmdGo_Click(object sender, ImageClickEventArgs e) { try @@ -74,20 +97,6 @@ private void cmdGo_Click(object sender, ImageClickEventArgs e) } } - public void BindDropDown() - { - DNNNodeCollection objNodes; - objNodes = Navigation.GetActionNodes(this.ActionRoot, this); - foreach (DNNNode objNode in objNodes) - { - this.ProcessNodes(objNode); - } - - this.Control.Bind(objNodes); - - this.Visible = this.DisplayControl(objNodes); - } - private void ProcessNodes(DNNNode objParent) { if (!string.IsNullOrEmpty(objParent.JSFunction)) @@ -102,14 +111,5 @@ private void ProcessNodes(DNNNode objParent) this.ProcessNodes(objNode); } } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - this.m_objControl = NavigationProvider.Instance(this.ProviderName); - this.Control.ControlID = "ctl" + this.ID; - this.Control.Initialize(); - this.spActions.Controls.Add(this.Control.NavigationControl); - } } } diff --git a/DNN Platform/Website/admin/Containers/PrintModule.ascx.cs b/DNN Platform/Website/admin/Containers/PrintModule.ascx.cs index cf7d6e224c3..7d30a53ba94 100644 --- a/DNN Platform/Website/admin/Containers/PrintModule.ascx.cs +++ b/DNN Platform/Website/admin/Containers/PrintModule.ascx.cs @@ -54,43 +54,43 @@ protected override void OnLoad(EventArgs e) } } - private void DisplayAction(ModuleAction action) - { - if (action.CommandName == ModuleActionType.PrintModule) - { - if (action.Visible) - { - if ((this.PortalSettings.UserMode == PortalSettings.Mode.Edit) || (action.Secure == SecurityAccessLevel.Anonymous || action.Secure == SecurityAccessLevel.View)) - { - if (this.ModuleContext.Configuration.DisplayPrint) - { - 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; - } - else - { - ModuleActionIcon.ImageUrl = "~/images/" + action.Icon; - } + private void DisplayAction(ModuleAction action) + { + if (action.CommandName == ModuleActionType.PrintModule) + { + if (action.Visible) + { + if ((this.PortalSettings.UserMode == PortalSettings.Mode.Edit) || (action.Secure == SecurityAccessLevel.Anonymous || action.Secure == SecurityAccessLevel.View)) + { + if (this.ModuleContext.Configuration.DisplayPrint) + { + 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; + } + else + { + ModuleActionIcon.ImageUrl = "~/images/" + action.Icon; + } - ModuleActionIcon.ToolTip = action.Title; - ModuleActionIcon.ID = "ico" + action.ID; - ModuleActionIcon.CausesValidation = false; - - ModuleActionIcon.Click += this.IconAction_Click; - - this.Controls.Add(ModuleActionIcon); - } - } - } - } - - foreach (ModuleAction subAction in action.Actions) - { - this.DisplayAction(subAction); + ModuleActionIcon.ToolTip = action.Title; + ModuleActionIcon.ID = "ico" + action.ID; + ModuleActionIcon.CausesValidation = false; + + ModuleActionIcon.Click += this.IconAction_Click; + + this.Controls.Add(ModuleActionIcon); + } + } + } + } + + foreach (ModuleAction subAction in action.Actions) + { + this.DisplayAction(subAction); + } } - } private void IconAction_Click(object sender, ImageClickEventArgs e) { diff --git a/DNN Platform/Website/admin/Containers/Title.ascx.cs b/DNN Platform/Website/admin/Containers/Title.ascx.cs index 506cec7da1b..ebb5cc0bff2 100644 --- a/DNN Platform/Website/admin/Containers/Title.ascx.cs +++ b/DNN Platform/Website/admin/Containers/Title.ascx.cs @@ -25,17 +25,6 @@ public partial class Title : SkinObjectBase private const string MyFileName = "Title.ascx"; public string CssClass { get; set; } - - private bool CanEditModule() - { - var canEdit = false; - if (this.ModuleControl != null && this.ModuleControl.ModuleContext.ModuleId > Null.NullInteger) - { - canEdit = (this.PortalSettings.UserMode == PortalSettings.Mode.Edit) && TabPermissionController.CanAdminPage() && !Globals.IsAdminControl(); - } - - return canEdit; - } protected override void OnInit(EventArgs e) { @@ -75,6 +64,17 @@ protected override void OnPreRender(EventArgs e) this.titleToolbar.Visible = true; } } + + private bool CanEditModule() + { + var canEdit = false; + if (this.ModuleControl != null && this.ModuleControl.ModuleContext.ModuleId > Null.NullInteger) + { + canEdit = (this.PortalSettings.UserMode == PortalSettings.Mode.Edit) && TabPermissionController.CanAdminPage() && !Globals.IsAdminControl(); + } + + return canEdit; + } private void UpdateTitle(object source, DNNLabelEditEventArgs e) { diff --git a/DNN Platform/Website/admin/Containers/Visibility.ascx.cs b/DNN Platform/Website/admin/Containers/Visibility.ascx.cs index be0f66a3117..0ea8bc9bd8f 100644 --- a/DNN Platform/Website/admin/Containers/Visibility.ascx.cs +++ b/DNN Platform/Website/admin/Containers/Visibility.ascx.cs @@ -32,6 +32,21 @@ public partial class Visibility : SkinObjectBase { private int _animationFrames = 5; private Panel _pnlModuleContent; + + public int AnimationFrames + { + get + { + return this._animationFrames; + } + + set + { + this._animationFrames = value; + } + } + + public string BorderWidth { get; set; } private string MinIconLoc { @@ -83,21 +98,6 @@ private string ModulePath return this.ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1); } } - - public int AnimationFrames - { - get - { - return this._animationFrames; - } - - set - { - this._animationFrames = value; - } - } - - public string BorderWidth { get; set; } public bool ContentVisible { @@ -126,13 +126,13 @@ public bool ContentVisible DNNClientAPI.MinMaxPersistanceType.Cookie, value); } - } - -// ReSharper disable InconsistentNaming -// TODO can this be renamed with a capital M - public string minIcon { get; set; } + } + + // ReSharper disable InconsistentNaming + // TODO can this be renamed with a capital M + public string minIcon { get; set; } -// ReSharper restore InconsistentNaming + // ReSharper restore InconsistentNaming public string MaxIcon { get; set; } public string ResourceFile diff --git a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs index 6efe5e08e84..e97010d15d1 100644 --- a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs +++ b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs @@ -64,13 +64,13 @@ protected string MoveText protected bool IsShared { get; set; } + protected string ModuleTitle { get; set; } + protected string LocalizeString(string key) { return Localization.GetString(key, Localization.GlobalResourceFile); } - protected string ModuleTitle { get; set; } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -88,11 +88,6 @@ protected override void OnInit(EventArgs e) ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); } - private void actionButton_Click(object sender, EventArgs e) - { - this.ProcessAction(this.Request.Params["__EVENTARGUMENT"]); - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -196,5 +191,10 @@ protected override void Render(HtmlTextWriter writer) this.Page.ClientScript.RegisterForEventValidation(this.actionButton.UniqueID, id.ToString()); } } + + private void actionButton_Click(object sender, EventArgs e) + { + this.ProcessAction(this.Request.Params["__EVENTARGUMENT"]); + } } } diff --git a/DNN Platform/Website/admin/Modules/Export.ascx.cs b/DNN Platform/Website/admin/Modules/Export.ascx.cs index 5eb0917ba74..ebdd2fc3292 100644 --- a/DNN Platform/Website/admin/Modules/Export.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Export.ascx.cs @@ -38,13 +38,13 @@ public partial class Export : PortalModuleBase { private readonly INavigationManager _navigationManager; + private new int ModuleId = -1; + private ModuleInfo _module; + public Export() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - - private new int ModuleId = -1; - private ModuleInfo _module; private ModuleInfo Module { @@ -62,6 +62,66 @@ private string ReturnURL } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (this.Request.QueryString["moduleid"] != null) + { + int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); + } + + if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "EXPORT", this.Module)) + { + this.Response.Redirect(Globals.AccessDeniedURL(), true); + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cmdExport.Click += this.OnExportClick; + + try + { + if (this.Request.QueryString["moduleid"] != null) + { + int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); + } + + if (!this.Page.IsPostBack) + { + this.cmdCancel.NavigateUrl = this.ReturnURL; + + this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); + this.cboFolders.Services.Parameters.Add("permission", "ADD"); + if (this.Module != null) + { + this.txtFile.Text = CleanName(this.Module.ModuleTitle); + } + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + private static string CleanName(string name) + { + var strName = name; + const string strBadChars = ". ~`!@#$%^&*()-_+={[}]|\\:;<,>?/\"'"; + + int intCounter; + for (intCounter = 0; intCounter <= strBadChars.Length - 1; intCounter++) + { + strName = strName.Replace(strBadChars.Substring(intCounter, 1), string.Empty); + } + + return strName; + } + private string ExportModule(int moduleID, string fileName, IFolderInfo folder) { var strMessage = string.Empty; @@ -146,66 +206,6 @@ private string ExportModule(int moduleID, string fileName, IFolderInfo folder) return strMessage; } - private static string CleanName(string name) - { - var strName = name; - const string strBadChars = ". ~`!@#$%^&*()-_+={[}]|\\:;<,>?/\"'"; - - int intCounter; - for (intCounter = 0; intCounter <= strBadChars.Length - 1; intCounter++) - { - strName = strName.Replace(strBadChars.Substring(intCounter, 1), string.Empty); - } - - return strName; - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (this.Request.QueryString["moduleid"] != null) - { - int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); - } - - if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "EXPORT", this.Module)) - { - this.Response.Redirect(Globals.AccessDeniedURL(), true); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cmdExport.Click += this.OnExportClick; - - try - { - if (this.Request.QueryString["moduleid"] != null) - { - int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); - } - - if (!this.Page.IsPostBack) - { - this.cmdCancel.NavigateUrl = this.ReturnURL; - - this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); - this.cboFolders.Services.Parameters.Add("permission", "ADD"); - if (this.Module != null) - { - this.txtFile.Text = CleanName(this.Module.ModuleTitle); - } - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - protected void OnExportClick(object sender, EventArgs e) { try diff --git a/DNN Platform/Website/admin/Modules/Import.ascx.cs b/DNN Platform/Website/admin/Modules/Import.ascx.cs index 6eb35714b06..0bda46701c1 100644 --- a/DNN Platform/Website/admin/Modules/Import.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Import.ascx.cs @@ -28,13 +28,13 @@ public partial class Import : PortalModuleBase { private readonly INavigationManager _navigationManager; + private new int ModuleId = -1; + private ModuleInfo _module; + public Import() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - - private new int ModuleId = -1; - private ModuleInfo _module; private ModuleInfo Module { @@ -52,6 +52,45 @@ private string ReturnURL } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (this.Request.QueryString["moduleid"] != null) + { + int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); + } + + // Verify that the current user has access to edit this module + if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "IMPORT", this.Module)) + { + this.Response.Redirect(Globals.AccessDeniedURL(), true); + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cboFolders.SelectionChanged += this.OnFoldersIndexChanged; + this.cboFiles.SelectedIndexChanged += this.OnFilesIndexChanged; + this.cmdImport.Click += this.OnImportClick; + + try + { + if (!this.Page.IsPostBack) + { + this.cmdCancel.NavigateUrl = this.ReturnURL; + this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); + this.cboFolders.Services.Parameters.Add("permission", "ADD"); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private string ImportModule() { var strMessage = string.Empty; @@ -120,45 +159,6 @@ private string ImportModule() return strMessage; } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (this.Request.QueryString["moduleid"] != null) - { - int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); - } - - // Verify that the current user has access to edit this module - if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "IMPORT", this.Module)) - { - this.Response.Redirect(Globals.AccessDeniedURL(), true); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cboFolders.SelectionChanged += this.OnFoldersIndexChanged; - this.cboFiles.SelectedIndexChanged += this.OnFilesIndexChanged; - this.cmdImport.Click += this.OnImportClick; - - try - { - if (!this.Page.IsPostBack) - { - this.cmdCancel.NavigateUrl = this.ReturnURL; - this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); - this.cboFolders.Services.Parameters.Add("permission", "ADD"); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } protected void OnFoldersIndexChanged(object sender, EventArgs e) { diff --git a/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs b/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs index 2d5f9d6a39d..1569e249e65 100644 --- a/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs +++ b/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs @@ -30,13 +30,13 @@ public partial class ModulePermissions : PortalModuleBase { private readonly INavigationManager _navigationManager; + private int _moduleId = -1; + private ModuleInfo _module; + public ModulePermissions() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - - private int _moduleId = -1; - private ModuleInfo _module; private ModuleInfo Module { diff --git a/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs b/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs index e653feb8a3c..9088698f048 100644 --- a/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs @@ -45,15 +45,15 @@ public partial class ModuleSettingsPage : PortalModuleBase private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleSettingsPage)); private readonly INavigationManager _navigationManager; + private int _moduleId = -1; + private Control _control; + private ModuleInfo _module; + public ModuleSettingsPage() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private int _moduleId = -1; - private Control _control; - private ModuleInfo _module; - private bool HideDeleteButton => this.Request.QueryString["HideDelete"] == "true"; private bool HideCancelButton => this.Request.QueryString["HideCancel"] == "true"; @@ -81,6 +81,63 @@ private string ReturnURL } } + protected string GetInstalledOnLink(object dataItem) + { + var returnValue = new StringBuilder(); + var tab = dataItem as TabInfo; + if (tab != null) + { + var index = 0; + TabController.Instance.PopulateBreadCrumbs(ref tab); + var defaultAlias = PortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID) + .OrderByDescending(a => a.IsPrimary) + .FirstOrDefault(); + var portalSettings = new PortalSettings(tab.PortalID) + { + PortalAlias = defaultAlias, + }; + + var tabUrl = this._navigationManager.NavigateURL(tab.TabID, portalSettings, string.Empty); + + foreach (TabInfo t in tab.BreadCrumbs) + { + if (index > 0) + { + returnValue.Append(" > "); + } + + if (tab.BreadCrumbs.Count - 1 == index) + { + returnValue.AppendFormat("{1}", tabUrl, t.LocalizedTabName); + } + else + { + returnValue.AppendFormat("{0}", t.LocalizedTabName); + } + + index = index + 1; + } + } + + return returnValue.ToString(); + } + + protected string GetInstalledOnSite(object dataItem) + { + string returnValue = string.Empty; + var tab = dataItem as TabInfo; + if (tab != null) + { + var portal = PortalController.Instance.GetPortal(tab.PortalID); + if (portal != null) + { + returnValue = portal.PortalName; + } + } + + return returnValue; + } + private void BindData() { if (this.Module != null) @@ -246,63 +303,6 @@ private bool GetBooleanSetting(string settingName, bool defaultValue) : bool.Parse(value.ToString()); } - protected string GetInstalledOnLink(object dataItem) - { - var returnValue = new StringBuilder(); - var tab = dataItem as TabInfo; - if (tab != null) - { - var index = 0; - TabController.Instance.PopulateBreadCrumbs(ref tab); - var defaultAlias = PortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID) - .OrderByDescending(a => a.IsPrimary) - .FirstOrDefault(); - var portalSettings = new PortalSettings(tab.PortalID) - { - PortalAlias = defaultAlias, - }; - - var tabUrl = this._navigationManager.NavigateURL(tab.TabID, portalSettings, string.Empty); - - foreach (TabInfo t in tab.BreadCrumbs) - { - if (index > 0) - { - returnValue.Append(" > "); - } - - if (tab.BreadCrumbs.Count - 1 == index) - { - returnValue.AppendFormat("{1}", tabUrl, t.LocalizedTabName); - } - else - { - returnValue.AppendFormat("{0}", t.LocalizedTabName); - } - - index = index + 1; - } - } - - return returnValue.ToString(); - } - - protected string GetInstalledOnSite(object dataItem) - { - string returnValue = string.Empty; - var tab = dataItem as TabInfo; - if (tab != null) - { - var portal = PortalController.Instance.GetPortal(tab.PortalID); - if (portal != null) - { - returnValue = portal.PortalName; - } - } - - return returnValue; - } - protected bool IsSharedViewOnly() { return this.ModuleContext.Configuration.IsShared && this.ModuleContext.Configuration.IsShareableViewOnly; diff --git a/DNN Platform/Website/admin/Modules/viewsource.ascx.cs b/DNN Platform/Website/admin/Modules/viewsource.ascx.cs index 16cc96385ab..213e11bd8c2 100644 --- a/DNN Platform/Website/admin/Modules/viewsource.ascx.cs +++ b/DNN Platform/Website/admin/Modules/viewsource.ascx.cs @@ -54,6 +54,42 @@ private string ReturnURL } } + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cboFile.SelectedIndexChanged += this.OnFileIndexChanged; + this.cmdUpdate.Click += this.OnUpdateClick; + + if (this.Page.IsPostBack == false) + { + this.cmdCancel.NavigateUrl = this.ReturnURL; + + var objModuleControl = ModuleControlController.GetModuleControl(this.ModuleControlId); + if (objModuleControl != null) + { + this.BindFiles(objModuleControl.ControlSrc); + } + + if (this.Request.UrlReferrer != null) + { + this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); + } + else + { + this.ViewState["UrlReferrer"] = string.Empty; + } + } + + this.cmdUpdate.Visible = this.CanEditSource; + this.txtSource.Enabled = this.CanEditSource; + } + + protected void OnFileIndexChanged(object sender, EventArgs e) + { + this.DisplayFile(); + } + private void BindFiles(string controlSrc) { this.cboFile.Items.Clear(); @@ -132,42 +168,6 @@ private void DisplayFile() this.trSource.Visible = displaySource; } } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cboFile.SelectedIndexChanged += this.OnFileIndexChanged; - this.cmdUpdate.Click += this.OnUpdateClick; - - if (this.Page.IsPostBack == false) - { - this.cmdCancel.NavigateUrl = this.ReturnURL; - - var objModuleControl = ModuleControlController.GetModuleControl(this.ModuleControlId); - if (objModuleControl != null) - { - this.BindFiles(objModuleControl.ControlSrc); - } - - if (this.Request.UrlReferrer != null) - { - this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); - } - else - { - this.ViewState["UrlReferrer"] = string.Empty; - } - } - - this.cmdUpdate.Visible = this.CanEditSource; - this.txtSource.Enabled = this.CanEditSource; - } - - protected void OnFileIndexChanged(object sender, EventArgs e) - { - this.DisplayFile(); - } private void OnUpdateClick(object sender, EventArgs e) { diff --git a/DNN Platform/Website/admin/Portal/Message.ascx.cs b/DNN Platform/Website/admin/Portal/Message.ascx.cs index 2b54b5a3804..65a2abae9f4 100644 --- a/DNN Platform/Website/admin/Portal/Message.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Message.ascx.cs @@ -9,15 +9,15 @@ namespace DotNetNuke.Common.Controls public partial class Message : PortalModuleBase { - private void InitializeComponent() - { - this.ID = "Message"; - } - protected override void OnInit(EventArgs e) { base.OnInit(e); this.InitializeComponent(); } + + private void InitializeComponent() + { + this.ID = "Message"; + } } } diff --git a/DNN Platform/Website/admin/Portal/NoContent.ascx.cs b/DNN Platform/Website/admin/Portal/NoContent.ascx.cs index e1f6e8d4115..efd08db0c6a 100644 --- a/DNN Platform/Website/admin/Portal/NoContent.ascx.cs +++ b/DNN Platform/Website/admin/Portal/NoContent.ascx.cs @@ -9,15 +9,15 @@ namespace DotNetNuke.Common.Controls public partial class NoContent : PortalModuleBase { - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); this.InitializeComponent(); } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Portal/Privacy.ascx.cs b/DNN Platform/Website/admin/Portal/Privacy.ascx.cs index a8c058280f4..9deb5d665e0 100644 --- a/DNN Platform/Website/admin/Portal/Privacy.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Privacy.ascx.cs @@ -19,10 +19,6 @@ namespace DotNetNuke.Common.Controls /// ----------------------------------------------------------------------------- public partial class Privacy : PortalModuleBase { - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -54,5 +50,9 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Portal/Terms.ascx.cs b/DNN Platform/Website/admin/Portal/Terms.ascx.cs index 456e71f778f..3127e83a9a5 100644 --- a/DNN Platform/Website/admin/Portal/Terms.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Terms.ascx.cs @@ -11,11 +11,6 @@ namespace DotNetNuke.Common.Controls public partial class Terms : PortalModuleBase { - // This call is required by the Web Form Designer. - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -41,5 +36,10 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + // This call is required by the Web Form Designer. + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs b/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs index 61af1ca0ecf..40166311cf9 100644 --- a/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs +++ b/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs @@ -24,10 +24,6 @@ namespace DotNetNuke.Modules.Admin.Sales public partial class PayPalIPN : PageBase { - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -40,17 +36,17 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - bool blnValid = true; + bool blnValid = true; -// string strTransactionID; + // string strTransactionID; int intRoleID = 0; int intPortalID = this.PortalSettings.PortalId; - int intUserID = 0; + int intUserID = 0; -// string strDescription; - double dblAmount = 0; + // string strDescription; + double dblAmount = 0; -// string strEmail; + // string strEmail; bool blnCancel = false; string strPayPalID = Null.NullString; string strPost = "cmd=_notify-validate"; @@ -83,8 +79,8 @@ protected override void OnLoad(EventArgs e) } break; - case "txn_id": // verify the transaction id for duplicates -// strTransactionID = strValue; + case "txn_id": // verify the transaction id for duplicates + // strTransactionID = strValue; break; case "receiver_email": // verify the PayPalId strPayPalID = strValue; @@ -97,14 +93,14 @@ protected override void OnLoad(EventArgs e) // RoleInfo objRole = objRoles.GetRole(intRoleID, intPortalID); break; - case "item_name": // get the product description -// strDescription = strValue; + case "item_name": // get the product description + // strDescription = strValue; break; case "custom": // get the UserID intUserID = int.Parse(strValue); break; - case "email": // get the email -// strEmail = strValue; + case "email": // get the email + // strEmail = strValue; break; } @@ -218,5 +214,9 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessPageLoadException(exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs b/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs index 977e6e98421..3320a5bb366 100644 --- a/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs +++ b/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs @@ -20,10 +20,6 @@ namespace DotNetNuke.Modules.Admin.Sales public partial class PayPalSubscription : PageBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PayPalSubscription)); - - private void InitializeComponent() - { - } protected override void OnInit(EventArgs e) { @@ -219,6 +215,10 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessPageLoadException(exc); } } + + private void InitializeComponent() + { + } /// /// This methods return the text description of the Frequency value. diff --git a/DNN Platform/Website/admin/Sales/Purchase.ascx.cs b/DNN Platform/Website/admin/Sales/Purchase.ascx.cs index 95fad04a234..b989b870563 100644 --- a/DNN Platform/Website/admin/Sales/Purchase.ascx.cs +++ b/DNN Platform/Website/admin/Sales/Purchase.ascx.cs @@ -31,10 +31,6 @@ public Purchase() this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -139,6 +135,10 @@ protected override void OnLoad(EventArgs e) } } + private void InitializeComponent() + { + } + private void cmdPurchase_Click(object sender, EventArgs e) { try diff --git a/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs b/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs index 32b7f4a8a2c..2e6e66abb38 100644 --- a/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs +++ b/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs @@ -29,15 +29,15 @@ namespace DotNetNuke.Modules.Admin.Security public partial class PasswordReset : UserModuleBase { + private const int RedirectTimeout = 3000; + private readonly INavigationManager _navigationManager; + private string _ipAddress; public PasswordReset() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - - private const int RedirectTimeout = 3000; - private string _ipAddress; private string ResetToken { @@ -106,26 +106,6 @@ protected override void OnLoad(EventArgs e) } } - private void LoadUserInfo() - { - var user = UserController.GetUserByPasswordResetToken(this.PortalId, this.ResetToken); - - if (user == null || user.PasswordResetExpiration < DateTime.Now) - { - this.divPassword.Visible = false; - this.resetMessages.Visible = true; - this.lblHelp.Text = Localization.GetString("ResetLinkExpired", this.LocalResourceFile); - return; - } - - this.txtUsername.Text = user.Username; - if (MembershipProviderConfig.RequiresQuestionAndAnswer) - { - this.lblQuestion.Text = user.Membership.PasswordQuestion; - this.divQA.Visible = true; - } - } - protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); @@ -173,6 +153,88 @@ protected override void OnPreRender(EventArgs e) } } + protected void RedirectAfterLogin() + { + var redirectURL = string.Empty; + + var setting = GetSetting(this.PortalId, "Redirect_AfterLogin"); + + if (Convert.ToInt32(setting) == Null.NullInteger) + { + if (this.Request.QueryString["returnurl"] != null) + { + // return to the url passed to signin + redirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); + + // clean the return url to avoid possible XSS attack. + redirectURL = UrlUtils.ValidReturnUrl(redirectURL); + } + + if (this.Request.Cookies["returnurl"] != null) + { + // return to the url passed to signin + redirectURL = HttpUtility.UrlDecode(this.Request.Cookies["returnurl"].Value); + + // clean the return url to avoid possible XSS attack. + redirectURL = UrlUtils.ValidReturnUrl(redirectURL); + } + + if (string.IsNullOrEmpty(redirectURL)) + { + if (this.PortalSettings.RegisterTabId != -1 && this.PortalSettings.HomeTabId != -1) + { + // redirect to portal home page specified + redirectURL = this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId); + } + else + { + // redirect to current page + redirectURL = this._navigationManager.NavigateURL(); + } + } + } + else // redirect to after login page + { + redirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); + } + + this.AddModuleMessage("ChangeSuccessful", ModuleMessage.ModuleMessageType.GreenSuccess, true); + this.resetMessages.Visible = this.divPassword.Visible = false; + this.lblHelp.Text = this.lblInfo.Text = string.Empty; + + // redirect page after 5 seconds + var script = string.Format("setTimeout(function(){{location.href = '{0}';}}, {1});", redirectURL, RedirectTimeout); + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ChangePasswordSuccessful", script, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ChangePasswordSuccessful", script, true); + } + } + + private void LoadUserInfo() + { + var user = UserController.GetUserByPasswordResetToken(this.PortalId, this.ResetToken); + + if (user == null || user.PasswordResetExpiration < DateTime.Now) + { + this.divPassword.Visible = false; + this.resetMessages.Visible = true; + this.lblHelp.Text = Localization.GetString("ResetLinkExpired", this.LocalResourceFile); + return; + } + + this.txtUsername.Text = user.Username; + if (MembershipProviderConfig.RequiresQuestionAndAnswer) + { + this.lblQuestion.Text = user.Membership.PasswordQuestion; + this.divQA.Visible = true; + } + } + private void cmdChangePassword_Click(object sender, EventArgs e) { string username = this.txtUsername.Text; @@ -263,68 +325,6 @@ private void cmdChangePassword_Click(object sender, EventArgs e) } } - protected void RedirectAfterLogin() - { - var redirectURL = string.Empty; - - var setting = GetSetting(this.PortalId, "Redirect_AfterLogin"); - - if (Convert.ToInt32(setting) == Null.NullInteger) - { - if (this.Request.QueryString["returnurl"] != null) - { - // return to the url passed to signin - redirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); - - // clean the return url to avoid possible XSS attack. - redirectURL = UrlUtils.ValidReturnUrl(redirectURL); - } - - if (this.Request.Cookies["returnurl"] != null) - { - // return to the url passed to signin - redirectURL = HttpUtility.UrlDecode(this.Request.Cookies["returnurl"].Value); - - // clean the return url to avoid possible XSS attack. - redirectURL = UrlUtils.ValidReturnUrl(redirectURL); - } - - if (string.IsNullOrEmpty(redirectURL)) - { - if (this.PortalSettings.RegisterTabId != -1 && this.PortalSettings.HomeTabId != -1) - { - // redirect to portal home page specified - redirectURL = this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId); - } - else - { - // redirect to current page - redirectURL = this._navigationManager.NavigateURL(); - } - } - } - else // redirect to after login page - { - redirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); - } - - this.AddModuleMessage("ChangeSuccessful", ModuleMessage.ModuleMessageType.GreenSuccess, true); - this.resetMessages.Visible = this.divPassword.Visible = false; - this.lblHelp.Text = this.lblInfo.Text = string.Empty; - - // redirect page after 5 seconds - var script = string.Format("setTimeout(function(){{location.href = '{0}';}}, {1});", redirectURL, RedirectTimeout); - if (ScriptManager.GetCurrent(this.Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ChangePasswordSuccessful", script, true); - } - else - { - this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ChangePasswordSuccessful", script, true); - } - } - private void LogSuccess() { this.LogResult(string.Empty); diff --git a/DNN Platform/Website/admin/Security/SendPassword.ascx.cs b/DNN Platform/Website/admin/Security/SendPassword.ascx.cs index 17c7e7f4b98..cf3deabed62 100644 --- a/DNN Platform/Website/admin/Security/SendPassword.ascx.cs +++ b/DNN Platform/Website/admin/Security/SendPassword.ascx.cs @@ -37,15 +37,15 @@ public partial class SendPassword : UserModuleBase private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SendPassword)); private readonly INavigationManager _navigationManager; + private UserInfo _user; + private int _userCount = Null.NullInteger; + private string _ipAddress; + public SendPassword() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private UserInfo _user; - private int _userCount = Null.NullInteger; - private string _ipAddress; - /// /// Gets the Redirect URL (after successful sending of password). /// @@ -62,40 +62,40 @@ protected string RedirectURL _RedirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); } else - { - if (Convert.ToInt32(setting) <= 0) - { - if (this.Request.QueryString["returnurl"] != null) - { - // return to the url passed to register - _RedirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); - - // clean the return url to avoid possible XSS attack. - _RedirectURL = UrlUtils.ValidReturnUrl(_RedirectURL); - - if (_RedirectURL.Contains("?returnurl")) - { - string baseURL = _RedirectURL.Substring( - 0, - _RedirectURL.IndexOf("?returnurl", StringComparison.Ordinal)); - string returnURL = - _RedirectURL.Substring(_RedirectURL.IndexOf("?returnurl", StringComparison.Ordinal) + 11); - - _RedirectURL = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); - } - } + { + if (Convert.ToInt32(setting) <= 0) + { + if (this.Request.QueryString["returnurl"] != null) + { + // return to the url passed to register + _RedirectURL = HttpUtility.UrlDecode(this.Request.QueryString["returnurl"]); - if (string.IsNullOrEmpty(_RedirectURL)) - { - // redirect to current page - _RedirectURL = this._navigationManager.NavigateURL(); + // clean the return url to avoid possible XSS attack. + _RedirectURL = UrlUtils.ValidReturnUrl(_RedirectURL); + + if (_RedirectURL.Contains("?returnurl")) + { + string baseURL = _RedirectURL.Substring( + 0, + _RedirectURL.IndexOf("?returnurl", StringComparison.Ordinal)); + string returnURL = + _RedirectURL.Substring(_RedirectURL.IndexOf("?returnurl", StringComparison.Ordinal) + 11); + + _RedirectURL = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); + } + } + + if (string.IsNullOrEmpty(_RedirectURL)) + { + // redirect to current page + _RedirectURL = this._navigationManager.NavigateURL(); + } + } + else // redirect to after registration page + { + _RedirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); } } - else // redirect to after registration page - { - _RedirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); - } - } return _RedirectURL; } @@ -129,23 +129,6 @@ private bool ShowEmailField } } - private void GetUser() - { - ArrayList arrUsers; - if (this.ShowEmailField && !string.IsNullOrEmpty(this.txtEmail.Text.Trim()) && (string.IsNullOrEmpty(this.txtUsername.Text.Trim()) || this.divUsername.Visible == false)) - { - arrUsers = UserController.GetUsersByEmail(this.PortalSettings.PortalId, this.txtEmail.Text, 0, int.MaxValue, ref this._userCount); - if (arrUsers != null && arrUsers.Count == 1) - { - this._user = (UserInfo)arrUsers[0]; - } - } - else - { - this._user = UserController.GetUserByName(this.PortalSettings.PortalId, this.txtUsername.Text); - } - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -207,6 +190,23 @@ protected override void OnLoad(EventArgs e) this.ctlCaptcha.Text = Localization.GetString("CaptchaText", this.LocalResourceFile); } } + + private void GetUser() + { + ArrayList arrUsers; + if (this.ShowEmailField && !string.IsNullOrEmpty(this.txtEmail.Text.Trim()) && (string.IsNullOrEmpty(this.txtUsername.Text.Trim()) || this.divUsername.Visible == false)) + { + arrUsers = UserController.GetUsersByEmail(this.PortalSettings.PortalId, this.txtEmail.Text, 0, int.MaxValue, ref this._userCount); + if (arrUsers != null && arrUsers.Count == 1) + { + this._user = (UserInfo)arrUsers[0]; + } + } + else + { + this._user = UserController.GetUserByName(this.PortalSettings.PortalId, this.txtUsername.Text); + } + } /// /// cmdSendPassword_Click runs when the Password Reminder button is clicked. diff --git a/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs b/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs index 815b227b534..90d24fa7c1e 100644 --- a/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs +++ b/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs @@ -18,10 +18,6 @@ public partial class CurrentDate : SkinObjectBase public string DateFormat { get; set; } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -40,5 +36,9 @@ protected override void OnLoad(EventArgs e) var user = UserController.Instance.GetCurrentUserInfo(); this.lblDate.Text = !string.IsNullOrEmpty(this.DateFormat) ? user.LocalTime().ToString(this.DateFormat) : user.LocalTime().ToLongDateString(); } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/DotNetNuke.ascx.cs b/DNN Platform/Website/admin/Skins/DotNetNuke.ascx.cs index ab531356b81..cf34edab755 100644 --- a/DNN Platform/Website/admin/Skins/DotNetNuke.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DotNetNuke.ascx.cs @@ -16,10 +16,6 @@ public partial class DotNetNukeControl : SkinObjectBase { public string CssClass { get; set; } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -42,5 +38,9 @@ protected override void OnLoad(EventArgs e) // show copyright credits? this.Visible = Host.DisplayCopyright; } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/Help.ascx.cs b/DNN Platform/Website/admin/Skins/Help.ascx.cs index a2727f9a44b..f03efbc321c 100644 --- a/DNN Platform/Website/admin/Skins/Help.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Help.ascx.cs @@ -19,10 +19,6 @@ public partial class Help : SkinObjectBase { public string CssClass { get; set; } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -61,5 +57,9 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/HostName.ascx.cs b/DNN Platform/Website/admin/Skins/HostName.ascx.cs index 6b829738b7a..ed8f381b4e4 100644 --- a/DNN Platform/Website/admin/Skins/HostName.ascx.cs +++ b/DNN Platform/Website/admin/Skins/HostName.ascx.cs @@ -18,10 +18,6 @@ public partial class HostName : SkinObjectBase { public string CssClass { get; set; } - private void InitializeComponent() - { - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -47,5 +43,9 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/Language.ascx.cs b/DNN Platform/Website/admin/Skins/Language.ascx.cs index 3b4566e3083..f557538f847 100644 --- a/DNN Platform/Website/admin/Skins/Language.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Language.ascx.cs @@ -204,7 +204,7 @@ public bool ShowMenu } } - public bool UseCurrentCultureForTemplate { get; set; } + public bool UseCurrentCultureForTemplate { get; set; } protected string CurrentCulture { @@ -248,67 +248,6 @@ protected LanguageTokenReplace LocalTokenReplace } } - private string parseTemplate(string template, string locale) - { - string strReturnValue = template; - try - { - if (!string.IsNullOrEmpty(locale)) - { - // for non data items use locale - this.LocalTokenReplace.Language = locale; - } - else - { - // for non data items use page culture - this.LocalTokenReplace.Language = this.CurrentCulture; - } - - // perform token replacements - strReturnValue = this.LocalTokenReplace.ReplaceEnvironmentTokens(strReturnValue); - } - catch (Exception ex) - { - Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); - } - - return strReturnValue; - } - - private void handleCommonTemplates() - { - if (string.IsNullOrEmpty(this.CommonHeaderTemplate)) - { - this.litCommonHeaderTemplate.Visible = false; - } - else - { - this.litCommonHeaderTemplate.Text = this.parseTemplate(this.CommonHeaderTemplate, this.CurrentCulture); - } - - if (string.IsNullOrEmpty(this.CommonFooterTemplate)) - { - this.litCommonFooterTemplate.Visible = false; - } - else - { - this.litCommonFooterTemplate.Text = this.parseTemplate(this.CommonFooterTemplate, this.CurrentCulture); - } - } - - private bool LocaleIsAvailable(Locale locale) - { - var tab = this.PortalSettings.ActiveTab; - if (tab.DefaultLanguageTab != null) - { - tab = tab.DefaultLanguageTab; - } - - var localizedTab = TabController.Instance.GetTabByCulture(tab.TabID, tab.PortalID, locale); - - return localizedTab != null && !localizedTab.IsDeleted && TabPermissionController.CanViewPage(localizedTab); - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -391,16 +330,6 @@ protected override void OnLoad(EventArgs e) } } - private void selectCulture_SelectedIndexChanged(object sender, EventArgs e) - { - // Redirect to same page to update all controls for newly selected culture - 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)); - this.Response.Redirect(this.LocalTokenReplace.ReplaceEnvironmentTokens("[URL]")); - } - /// /// Binds data to repeater. a template is used to render the items. /// @@ -474,5 +403,76 @@ protected void rptLanguages_ItemDataBound(object sender, RepeaterItemEventArgs e Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); } } + + private string parseTemplate(string template, string locale) + { + string strReturnValue = template; + try + { + if (!string.IsNullOrEmpty(locale)) + { + // for non data items use locale + this.LocalTokenReplace.Language = locale; + } + else + { + // for non data items use page culture + this.LocalTokenReplace.Language = this.CurrentCulture; + } + + // perform token replacements + strReturnValue = this.LocalTokenReplace.ReplaceEnvironmentTokens(strReturnValue); + } + catch (Exception ex) + { + Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); + } + + return strReturnValue; + } + + private void handleCommonTemplates() + { + if (string.IsNullOrEmpty(this.CommonHeaderTemplate)) + { + this.litCommonHeaderTemplate.Visible = false; + } + else + { + this.litCommonHeaderTemplate.Text = this.parseTemplate(this.CommonHeaderTemplate, this.CurrentCulture); + } + + if (string.IsNullOrEmpty(this.CommonFooterTemplate)) + { + this.litCommonFooterTemplate.Visible = false; + } + else + { + this.litCommonFooterTemplate.Text = this.parseTemplate(this.CommonFooterTemplate, this.CurrentCulture); + } + } + + private bool LocaleIsAvailable(Locale locale) + { + var tab = this.PortalSettings.ActiveTab; + if (tab.DefaultLanguageTab != null) + { + tab = tab.DefaultLanguageTab; + } + + var localizedTab = TabController.Instance.GetTabByCulture(tab.TabID, tab.PortalID, locale); + + return localizedTab != null && !localizedTab.IsDeleted && TabPermissionController.CanViewPage(localizedTab); + } + + private void selectCulture_SelectedIndexChanged(object sender, EventArgs e) + { + // Redirect to same page to update all controls for newly selected culture + 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)); + this.Response.Redirect(this.LocalTokenReplace.ReplaceEnvironmentTokens("[URL]")); + } } } diff --git a/DNN Platform/Website/admin/Skins/Login.ascx.cs b/DNN Platform/Website/admin/Skins/Login.ascx.cs index 8f19b2f06f0..70a0c0a7e1e 100644 --- a/DNN Platform/Website/admin/Skins/Login.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Login.ascx.cs @@ -21,6 +21,8 @@ namespace DotNetNuke.UI.Skins.Controls /// ----------------------------------------------------------------------------- public partial class Login : SkinObjectBase { + private const string MyFileName = "Login.ascx"; + private readonly INavigationManager _navigationManager; public Login() @@ -29,8 +31,6 @@ public Login() this.LegacyMode = true; } - private const string MyFileName = "Login.ascx"; - public string Text { get; set; } public string CssClass { get; set; } diff --git a/DNN Platform/Website/admin/Skins/Logo.ascx.cs b/DNN Platform/Website/admin/Skins/Logo.ascx.cs index 50336380fcc..a0868da4ed8 100644 --- a/DNN Platform/Website/admin/Skins/Logo.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Logo.ascx.cs @@ -22,15 +22,15 @@ namespace DotNetNuke.UI.Skins.Controls public partial class Logo : SkinObjectBase { private readonly INavigationManager _navigationManager; - - public string BorderWidth { get; set; } - - public string CssClass { get; set; } public Logo() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public string BorderWidth { get; set; } + + public string CssClass { get; set; } protected override void OnLoad(EventArgs e) { diff --git a/DNN Platform/Website/admin/Skins/Nav.ascx.cs b/DNN Platform/Website/admin/Skins/Nav.ascx.cs index 4c2362e5305..26495940324 100644 --- a/DNN Platform/Website/admin/Skins/Nav.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Nav.ascx.cs @@ -13,10 +13,6 @@ namespace DotNetNuke.UI.Skins.Controls [Obsolete("Support was removed for SolPart & Similar Modules in DNN 8.x, this control is no-longer functional to that point. Usage of DDRMenu is suggested. Scheduled removal in v10.0.0.")] public partial class Nav : NavObjectBase { - private void InitializeComponent() - { - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -154,6 +150,20 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + protected override void OnInit(EventArgs e) + { + this.InitializeNavControl(this, "SolpartMenuNavigationProvider"); + this.Control.NodeClick += this.Control_NodeClick; + this.Control.PopulateOnDemand += this.Control_PopulateOnDemand; + + base.OnInit(e); + this.InitializeComponent(); + } + + private void InitializeComponent() + { + } private string FixImagePath(string strPath) { @@ -175,16 +185,6 @@ private void BuildNodes(DNNNode objNode) this.Bind(objNodes); } - protected override void OnInit(EventArgs e) - { - this.InitializeNavControl(this, "SolpartMenuNavigationProvider"); - this.Control.NodeClick += this.Control_NodeClick; - this.Control.PopulateOnDemand += this.Control_PopulateOnDemand; - - base.OnInit(e); - this.InitializeComponent(); - } - private void Control_NodeClick(NavigationEventArgs args) { if (args.Node == null) diff --git a/DNN Platform/Website/admin/Skins/Privacy.ascx.cs b/DNN Platform/Website/admin/Skins/Privacy.ascx.cs index a863371717f..8532805db18 100644 --- a/DNN Platform/Website/admin/Skins/Privacy.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Privacy.ascx.cs @@ -19,21 +19,17 @@ namespace DotNetNuke.UI.Skins.Controls /// ----------------------------------------------------------------------------- public partial class Privacy : SkinObjectBase { - private readonly INavigationManager _navigationManager; private const string MyFileName = "Privacy.ascx"; - - public string Text { get; set; } - - public string CssClass { get; set; } + private readonly INavigationManager _navigationManager; public Privacy() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public string Text { get; set; } - private void InitializeComponent() - { - } + public string CssClass { get; set; } protected override void OnInit(EventArgs e) { @@ -69,5 +65,9 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/Search.ascx.cs b/DNN Platform/Website/admin/Skins/Search.ascx.cs index a66dd91e4bd..c1b27a0bf2d 100644 --- a/DNN Platform/Website/admin/Skins/Search.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Search.ascx.cs @@ -23,16 +23,16 @@ namespace DotNetNuke.UI.Skins.Controls public partial class Search : SkinObjectBase { + private const string MyFileName = "Search.ascx"; + private readonly INavigationManager _navigationManager; + private bool _showSite = true; + private bool _showWeb = true; public Search() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - - private const string MyFileName = "Search.ascx"; - private bool _showSite = true; - private bool _showWeb = true; private string _siteIconURL; private string _siteText; private string _siteToolTip; @@ -41,6 +41,8 @@ public Search() private string _webText; private string _webToolTip; private string _webURL; + + private bool _enableWildSearch = true; /// /// Gets or sets the CSS class for the option buttons and search button. @@ -348,15 +350,14 @@ public string WebURL /// Gets or sets the millisecond to delay trigger auto search. /// public int AutoSearchDelayInMilliSecond { get; set; } - - private bool _enableWildSearch = true; /// /// Gets or sets a value indicating whether disable the wild search. /// public bool EnableWildSearch { - get { return this._enableWildSearch; } set { this._enableWildSearch = value; } + get { return this._enableWildSearch; } + set { this._enableWildSearch = value; } } protected int PortalId { get; set; } @@ -364,31 +365,6 @@ public bool EnableWildSearch protected string SearchType { get; set; } protected string CultureCode { get; set; } - - private int GetSearchTabId() - { - int searchTabId = this.PortalSettings.SearchTabId; - if (searchTabId == Null.NullInteger) - { - ArrayList arrModules = ModuleController.Instance.GetModulesByDefinition(this.PortalSettings.PortalId, "Search Results"); - if (arrModules.Count > 1) - { - foreach (ModuleInfo SearchModule in arrModules) - { - if (SearchModule.CultureCode == this.PortalSettings.CultureCode) - { - searchTabId = SearchModule.TabID; - } - } - } - else if (arrModules.Count == 1) - { - searchTabId = ((ModuleInfo)arrModules[0]).TabID; - } - } - - return searchTabId; - } /// /// Executes the search. @@ -514,25 +490,30 @@ protected override void OnLoad(EventArgs e) this.cmdSearchNew.CssClass = this.CssClass; } } - - /// - /// Handles the Click event of the cmdSearch control. - /// - /// The source of the event. - /// The instance containing the event data. - /// This event is only used when UseDropDownList is false. - private void CmdSearchClick(object sender, EventArgs e) + + private int GetSearchTabId() { - this.SearchType = "S"; - if (this.WebRadioButton.Visible) + int searchTabId = this.PortalSettings.SearchTabId; + if (searchTabId == Null.NullInteger) { - if (this.WebRadioButton.Checked) + ArrayList arrModules = ModuleController.Instance.GetModulesByDefinition(this.PortalSettings.PortalId, "Search Results"); + if (arrModules.Count > 1) { - this.SearchType = "W"; + foreach (ModuleInfo SearchModule in arrModules) + { + if (SearchModule.CultureCode == this.PortalSettings.CultureCode) + { + searchTabId = SearchModule.TabID; + } + } + } + else if (arrModules.Count == 1) + { + searchTabId = ((ModuleInfo)arrModules[0]).TabID; } } - - this.ExecuteSearch(this.txtSearch.Text.Trim(), this.SearchType); + + return searchTabId; } /// @@ -606,5 +587,25 @@ protected override void OnPreRender(EventArgs e) this.txtSearch.Attributes.Add("placeholder", this.PlaceHolderText); } } + + /// + /// Handles the Click event of the cmdSearch control. + /// + /// The source of the event. + /// The instance containing the event data. + /// This event is only used when UseDropDownList is false. + private void CmdSearchClick(object sender, EventArgs e) + { + this.SearchType = "S"; + if (this.WebRadioButton.Visible) + { + if (this.WebRadioButton.Checked) + { + this.SearchType = "W"; + } + } + + this.ExecuteSearch(this.txtSearch.Text.Trim(), this.SearchType); + } } } diff --git a/DNN Platform/Website/admin/Skins/Terms.ascx.cs b/DNN Platform/Website/admin/Skins/Terms.ascx.cs index 7107e30a413..2c3603def92 100644 --- a/DNN Platform/Website/admin/Skins/Terms.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Terms.ascx.cs @@ -19,21 +19,17 @@ namespace DotNetNuke.UI.Skins.Controls /// ----------------------------------------------------------------------------- public partial class Terms : SkinObjectBase { - private readonly INavigationManager _navigationManager; private const string MyFileName = "Terms.ascx"; - - public string Text { get; set; } - - public string CssClass { get; set; } + private readonly INavigationManager _navigationManager; public Terms() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + + public string Text { get; set; } - private void InitializeComponent() - { - } + public string CssClass { get; set; } protected override void OnInit(EventArgs e) { @@ -70,5 +66,9 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + private void InitializeComponent() + { + } } } diff --git a/DNN Platform/Website/admin/Skins/Toast.ascx.cs b/DNN Platform/Website/admin/Skins/Toast.ascx.cs index adf833575fd..72c2a3a4483 100644 --- a/DNN Platform/Website/admin/Skins/Toast.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Toast.ascx.cs @@ -23,25 +23,25 @@ namespace DotNetNuke.UI.Skins.Controls public partial class Toast : SkinObjectBase { - private readonly INavigationManager _navigationManager; - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Toast)); - private static readonly string ToastCacheKey = "DNN_Toast_Config"; - private const string MyFileName = "Toast.ascx"; - protected string ServiceModuleName { get; private set; } - - protected string ServiceAction { get; private set; } + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Toast)); + private static readonly string ToastCacheKey = "DNN_Toast_Config"; + private readonly INavigationManager _navigationManager; public Toast() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected string ServiceModuleName { get; private set; } + + protected string ServiceAction { get; private set; } + public bool IsOnline() { - var userInfo = UserController.Instance.GetCurrentUserInfo(); - return userInfo.UserID != -1; + var userInfo = UserController.Instance.GetCurrentUserInfo(); + return userInfo.UserID != -1; } public string GetNotificationLink() @@ -64,6 +64,19 @@ public string GetNotificationLabel() return Localization.GetString("SeeAllNotification", Localization.GetResourceFile(this, MyFileName)); } + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + JavaScript.RequestRegistration(CommonJs.jQueryUI); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/Toast/jquery.toastmessage.js", DotNetNuke.Web.Client.FileOrder.Js.jQuery); + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/components/Toast/jquery.toastmessage.css", DotNetNuke.Web.Client.FileOrder.Css.DefaultCss); + + this.InitializeConfig(); + } + // This method is copied from user skin object private int GetMessageTab() { @@ -110,19 +123,6 @@ private int FindMessageTab() return this.PortalSettings.UserTabId; } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - JavaScript.RequestRegistration(CommonJs.jQueryUI); - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/components/Toast/jquery.toastmessage.js", DotNetNuke.Web.Client.FileOrder.Js.jQuery); - ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/components/Toast/jquery.toastmessage.css", DotNetNuke.Web.Client.FileOrder.Css.DefaultCss); - - this.InitializeConfig(); - } - private void InitializeConfig() { this.ServiceModuleName = "InternalServices"; diff --git a/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs b/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs index 1bd1c840189..3e84895408a 100644 --- a/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs +++ b/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs @@ -45,6 +45,14 @@ public partial class TreeViewMenu : NavObjectBase private int _treeIndentWidth = 10; private string _width = "100%"; + private enum eImageType + { + FolderClosed = 0, + FolderOpen = 1, + Page = 2, + GotoParent = 3, + } + public string BodyCssClass { get @@ -306,6 +314,103 @@ public string Width this._width = value; } } + + /// ----------------------------------------------------------------------------- + /// + /// The Page_Load server event handler on this user control is used + /// to populate the tree with the Pages. + /// + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + try + { + if (this.Page.IsPostBack == false) + { + this.BuildTree(null, false); + + // Main Table Properties + if (!string.IsNullOrEmpty(this.Width)) + { + this.tblMain.Width = this.Width; + } + + if (!string.IsNullOrEmpty(this.CssClass)) + { + this.tblMain.Attributes.Add("class", this.CssClass); + } + + // Header Properties + if (!string.IsNullOrEmpty(this.HeaderCssClass)) + { + this.cellHeader.Attributes.Add("class", this.HeaderCssClass); + } + + if (!string.IsNullOrEmpty(this.HeaderTextCssClass)) + { + this.lblHeader.CssClass = this.HeaderTextCssClass; + } + + // Header Text (if set) + if (!string.IsNullOrEmpty(this.HeaderText)) + { + this.lblHeader.Text = this.HeaderText; + } + + // ResourceKey overrides if found + if (!string.IsNullOrEmpty(this.ResourceKey)) + { + string strHeader = Localization.GetString(this.ResourceKey, Localization.GetResourceFile(this, MyFileName)); + if (!string.IsNullOrEmpty(strHeader)) + { + this.lblHeader.Text = Localization.GetString(this.ResourceKey, Localization.GetResourceFile(this, MyFileName)); + } + } + + // If still not set get default key + if (string.IsNullOrEmpty(this.lblHeader.Text)) + { + string strHeader = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName)); + if (!string.IsNullOrEmpty(strHeader)) + { + this.lblHeader.Text = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName)); + } + else + { + this.lblHeader.Text = "Site Navigation"; + } + } + + this.tblHeader.Visible = this.IncludeHeader; + + // Main Panel Properties + if (!string.IsNullOrEmpty(this.BodyCssClass)) + { + this.cellBody.Attributes.Add("class", this.BodyCssClass); + } + + this.cellBody.NoWrap = this.NoWrap; + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected override void OnInit(EventArgs e) + { + this.InitializeTree(); + this.InitializeNavControl(this.cellBody, "DNNTreeNavigationProvider"); + this.Control.NodeClick += this.DNNTree_NodeClick; + this.Control.PopulateOnDemand += this.DNNTree_PopulateOnDemand; + base.OnInit(e); + this.InitializeComponent(); + } private void InitializeComponent() { @@ -471,93 +576,6 @@ private void InitializeTree() this.CSSControl = this.TreeCssClass; } } - - /// ----------------------------------------------------------------------------- - /// - /// The Page_Load server event handler on this user control is used - /// to populate the tree with the Pages. - /// - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - try - { - if (this.Page.IsPostBack == false) - { - this.BuildTree(null, false); - - // Main Table Properties - if (!string.IsNullOrEmpty(this.Width)) - { - this.tblMain.Width = this.Width; - } - - if (!string.IsNullOrEmpty(this.CssClass)) - { - this.tblMain.Attributes.Add("class", this.CssClass); - } - - // Header Properties - if (!string.IsNullOrEmpty(this.HeaderCssClass)) - { - this.cellHeader.Attributes.Add("class", this.HeaderCssClass); - } - - if (!string.IsNullOrEmpty(this.HeaderTextCssClass)) - { - this.lblHeader.CssClass = this.HeaderTextCssClass; - } - - // Header Text (if set) - if (!string.IsNullOrEmpty(this.HeaderText)) - { - this.lblHeader.Text = this.HeaderText; - } - - // ResourceKey overrides if found - if (!string.IsNullOrEmpty(this.ResourceKey)) - { - string strHeader = Localization.GetString(this.ResourceKey, Localization.GetResourceFile(this, MyFileName)); - if (!string.IsNullOrEmpty(strHeader)) - { - this.lblHeader.Text = Localization.GetString(this.ResourceKey, Localization.GetResourceFile(this, MyFileName)); - } - } - - // If still not set get default key - if (string.IsNullOrEmpty(this.lblHeader.Text)) - { - string strHeader = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName)); - if (!string.IsNullOrEmpty(strHeader)) - { - this.lblHeader.Text = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName)); - } - else - { - this.lblHeader.Text = "Site Navigation"; - } - } - - this.tblHeader.Visible = this.IncludeHeader; - - // Main Panel Properties - if (!string.IsNullOrEmpty(this.BodyCssClass)) - { - this.cellBody.Attributes.Add("class", this.BodyCssClass); - } - - this.cellBody.NoWrap = this.NoWrap; - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } /// ----------------------------------------------------------------------------- /// @@ -587,23 +605,5 @@ private void DNNTree_PopulateOnDemand(NavigationEventArgs args) this.BuildTree(args.Node, true); } - - protected override void OnInit(EventArgs e) - { - this.InitializeTree(); - this.InitializeNavControl(this.cellBody, "DNNTreeNavigationProvider"); - this.Control.NodeClick += this.DNNTree_NodeClick; - this.Control.PopulateOnDemand += this.DNNTree_PopulateOnDemand; - base.OnInit(e); - this.InitializeComponent(); - } - - private enum eImageType - { - FolderClosed = 0, - FolderOpen = 1, - Page = 2, - GotoParent = 3, - } } } diff --git a/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs b/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs index 0c8285432d6..3091051faee 100644 --- a/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs +++ b/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs @@ -27,13 +27,18 @@ public partial class UserAndLogin : SkinObjectBase private const string MyFileName = "UserAndLogin.ascx"; private readonly INavigationManager _navigationManager; - protected string AvatarImageUrl => UserController.Instance.GetUserProfilePictureUrl(this.PortalSettings.UserId, 32, 32); - public UserAndLogin() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + /// + /// Gets or sets a value indicating whether set this to true to show in custom 404/500 page. + /// + public bool ShowInErrorPage { get; set; } + + protected string AvatarImageUrl => UserController.Instance.GetUserProfilePictureUrl(this.PortalSettings.UserId, 32, 32); + protected bool CanRegister { get @@ -129,11 +134,6 @@ protected string UserProfileUrl } } - /// - /// Gets or sets a value indicating whether set this to true to show in custom 404/500 page. - /// - public bool ShowInErrorPage { get; set; } - protected string LocalizeString(string key) { return Localization.GetString(key, Localization.GetResourceFile(this, MyFileName)); diff --git a/DNN Platform/Website/admin/Skins/tags.ascx.cs b/DNN Platform/Website/admin/Skins/tags.ascx.cs index fd5d4d4ce25..d5418547790 100644 --- a/DNN Platform/Website/admin/Skins/tags.ascx.cs +++ b/DNN Platform/Website/admin/Skins/tags.ascx.cs @@ -12,8 +12,8 @@ namespace DotNetNuke.UI.Skins.Controls public partial class Tags : SkinObjectBase { - private readonly INavigationManager _navigationManager; private const string MyFileName = "Tags.ascx"; + private readonly INavigationManager _navigationManager; private string _AddImageUrl = IconController.IconURL("Add"); private bool _AllowTagging = true; private string _CancelImageUrl = IconController.IconURL("Lt"); diff --git a/DNN Platform/Website/admin/Tabs/Export.ascx.cs b/DNN Platform/Website/admin/Tabs/Export.ascx.cs index 07fce226328..0c4365f55d8 100644 --- a/DNN Platform/Website/admin/Tabs/Export.ascx.cs +++ b/DNN Platform/Website/admin/Tabs/Export.ascx.cs @@ -43,20 +43,6 @@ public TabInfo Tab return this._tab; } } - - /// ----------------------------------------------------------------------------- - /// - /// Serializes the Tab. - /// - /// Reference to XmlDocument context. - /// Node to add the serialized objects. - /// ----------------------------------------------------------------------------- - private void SerializeTab(XmlDocument xmlTemplate, XmlNode nodeTabs) - { - var xmlTab = new XmlDocument { XmlResolver = null }; - var nodeTab = TabController.SerializeTab(xmlTab, this.Tab, this.chkContent.Checked); - nodeTabs.AppendChild(xmlTemplate.ImportNode(nodeTab, true)); - } protected override void OnInit(EventArgs e) { @@ -102,10 +88,19 @@ protected override void OnLoad(EventArgs e) } } - private bool IsAccessibleByUser(IFolderInfo folder) + /// ----------------------------------------------------------------------------- + /// + /// Serializes the Tab. + /// + /// Reference to XmlDocument context. + /// Node to add the serialized objects. + /// ----------------------------------------------------------------------------- + private void SerializeTab(XmlDocument xmlTemplate, XmlNode nodeTabs) { - return FolderPermissionController.Instance.CanAddFolder(folder); - } + var xmlTab = new XmlDocument { XmlResolver = null }; + var nodeTab = TabController.SerializeTab(xmlTab, this.Tab, this.chkContent.Checked); + nodeTabs.AppendChild(xmlTemplate.ImportNode(nodeTab, true)); + } protected void OnExportClick(object sender, EventArgs e) { @@ -155,5 +150,10 @@ protected void OnExportClick(object sender, EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } + + private bool IsAccessibleByUser(IFolderInfo folder) + { + return FolderPermissionController.Instance.CanAddFolder(folder); + } } } diff --git a/DNN Platform/Website/admin/Tabs/Import.ascx.cs b/DNN Platform/Website/admin/Tabs/Import.ascx.cs index 8d264ee7cd2..e843961daff 100644 --- a/DNN Platform/Website/admin/Tabs/Import.ascx.cs +++ b/DNN Platform/Website/admin/Tabs/Import.ascx.cs @@ -28,13 +28,13 @@ public partial class Import : PortalModuleBase { private readonly INavigationManager _navigationManager; + private TabInfo _tab; + public Import() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - private TabInfo _tab; - public TabInfo Tab { get @@ -48,6 +48,50 @@ public TabInfo Tab } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (!TabPermissionController.CanImportPage()) + { + this.Response.Redirect(Globals.AccessDeniedURL(), true); + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cboFolders.SelectionChanged += this.OnFolderIndexChanged; + this.cmdImport.Click += this.OnImportClick; + this.cboParentTab.SelectionChanged += this.OnParentTabIndexChanged; + this.cboTemplate.SelectedIndexChanged += this.OnTemplateIndexChanged; + this.optMode.SelectedIndexChanged += this.OptModeSelectedIndexChanged; + + try + { + if (!this.Page.IsPostBack) + { + this.cmdCancel.NavigateUrl = this._navigationManager.NavigateURL(); + this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); + var folders = FolderManager.Instance.GetFolders(this.UserInfo, "BROWSE, ADD"); + var templateFolder = folders.SingleOrDefault(f => f.FolderPath == "Templates/"); + if (templateFolder != null) + { + this.cboFolders.SelectedFolder = templateFolder; + } + + this.BindFiles(); + this.BindTabControls(); + this.DisplayNewRows(); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private void BindBeforeAfterTabControls() { var noneSpecified = "<" + Localization.GetString("None_Specified") + ">"; @@ -106,50 +150,6 @@ private void DisplayNewRows() this.divInsertPositionRow.Visible = this.optMode.SelectedIndex == 0; } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (!TabPermissionController.CanImportPage()) - { - this.Response.Redirect(Globals.AccessDeniedURL(), true); - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cboFolders.SelectionChanged += this.OnFolderIndexChanged; - this.cmdImport.Click += this.OnImportClick; - this.cboParentTab.SelectionChanged += this.OnParentTabIndexChanged; - this.cboTemplate.SelectedIndexChanged += this.OnTemplateIndexChanged; - this.optMode.SelectedIndexChanged += this.OptModeSelectedIndexChanged; - - try - { - if (!this.Page.IsPostBack) - { - this.cmdCancel.NavigateUrl = this._navigationManager.NavigateURL(); - this.cboFolders.UndefinedItem = new ListItem("<" + Localization.GetString("None_Specified") + ">", string.Empty); - var folders = FolderManager.Instance.GetFolders(this.UserInfo, "BROWSE, ADD"); - var templateFolder = folders.SingleOrDefault(f => f.FolderPath == "Templates/"); - if (templateFolder != null) - { - this.cboFolders.SelectedFolder = templateFolder; - } - - this.BindFiles(); - this.BindTabControls(); - this.DisplayNewRows(); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - protected void OnFolderIndexChanged(object sender, EventArgs e) { this.BindFiles(); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs index 74f1bf19dba..ad69e97b122 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs @@ -28,21 +28,21 @@ public class AdminLogsController private PortalSettings _portalSettings; - private PortalSettings PortalSettings + protected Dictionary LogTypeDictionary { get { - this._portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return this._portalSettings; + this._logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); + return this._logTypeDictionary; } } - protected Dictionary LogTypeDictionary + private PortalSettings PortalSettings { get { - this._logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); - return this._logTypeDictionary; + this._portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this._portalSettings; } } @@ -85,7 +85,7 @@ public string GetPropertiesText(object obj) { str.Append(objLogInfo.Exception); } - str.Append("

" + Localization.GetString("ServerName",Constants.LocalResourcesFile) + + str.Append("

" + Localization.GetString("ServerName", Constants.LocalResourcesFile) + HttpUtility.HtmlEncode(objLogInfo.LogServerName) + "

"); } return str.ToString(); @@ -251,10 +251,8 @@ public string EmailLogItems(string subject, string fromEmailAddress, string toEm error = Localization.GetString("EmailFailure", Constants.LocalResourcesFile); } return returnMsg; - } - - #region Private Methods - + } + private XmlDocument GetExceptions(IEnumerable logIds) { var objXml = new XmlDocument { XmlResolver = null }; @@ -269,8 +267,6 @@ private XmlDocument GetExceptions(IEnumerable logIds) } } return objXml; - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs index 1a53560acb3..e323d57abf6 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/BusinessController.cs @@ -38,16 +38,6 @@ public string UpgradeModule(string version) return String.Empty; } - private void UpdateMenuController() - { - PersonaBarRepository.Instance.UpdateMenuController(Dnn.PersonaBar.Vocabularies.Components.Constants.MenuIdentifier, string.Empty); - } - - private bool TelerikAssemblyExists() - { - return File.Exists(Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll")); - } - private static string UpdateTelerikEncryptionKey(string keyName) { var strError = ""; @@ -81,5 +71,15 @@ private static string UpdateTelerikEncryptionKey(string keyName) } return strError; } + + private void UpdateMenuController() + { + PersonaBarRepository.Instance.UpdateMenuController(Dnn.PersonaBar.Vocabularies.Components.Constants.MenuIdentifier, string.Empty); + } + + private bool TelerikAssemblyExists() + { + return File.Exists(Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll")); + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs index 79ae085e502..bd16eae1bf3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs @@ -1,22 +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 Dnn.PersonaBar.ConfigConsole.Components +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Xml; + + using DotNetNuke.Application; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; -#region Usings - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml; -using DotNetNuke.Application; -using DotNetNuke.Common; -using DotNetNuke.Common.Utilities; - -#endregion - -namespace Dnn.PersonaBar.ConfigConsole.Components -{ public class ConfigConsoleController { public IEnumerable GetConfigFilesList() @@ -61,10 +57,8 @@ public void MergeConfigFile(string fileContent) var merge = new DotNetNuke.Services.Installer.XmlMerge(doc, Globals.FormatVersion(app.Version), app.Description); merge.UpdateConfigs(); } - } - - #region Private Functions - + } + private bool IsValidXmlMergDocument(string mergeDocText) { if (string.IsNullOrEmpty(mergeDocText.Trim())) @@ -83,8 +77,6 @@ private void ValidateFilePath(string filePath) { throw new ArgumentException("Invalid File Path"); } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs index f11a38691a5..7007874d948 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs @@ -26,16 +26,11 @@ namespace Dnn.PersonaBar.Extensions.Components public class CreateModuleController : ServiceLocator, ICreateModuleController { - protected INavigationManager NavigationManager { get; } public CreateModuleController() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } - - protected override Func GetFactory() - { - return () => new CreateModuleController(); - } + protected INavigationManager NavigationManager { get; } /// /// create new module. @@ -65,6 +60,17 @@ public int CreateModule(CreateModuleDto createModuleDto, out string newPageUrl, return packageId; } + protected override Func GetFactory() + { + return () => new CreateModuleController(); + } + + private static bool InvalidFilename(string fileName) + { + var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]"); + return invalidFilenameChars.IsMatch(fileName); + } + private int CreateNewModule(CreateModuleDto createModuleDto, out string newPageUrl, out string errorMessage) { newPageUrl = string.Empty; @@ -333,12 +339,6 @@ private string CreateNewPage(ModuleDefinitionInfo moduleDefinition) return string.Empty; } - private static bool InvalidFilename(string fileName) - { - var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]"); - return invalidFilenameChars.IsMatch(fileName); - } - private string CreateControl(CreateModuleDto createModuleDto) { var folder = PathUtils.Instance.RemoveTrailingSlash(this.GetSourceFolder(createModuleDto)); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/AvailablePackagesDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/AvailablePackagesDto.cs index 6b99013815d..7d0ec1ac3e8 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/AvailablePackagesDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/AvailablePackagesDto.cs @@ -1,15 +1,10 @@ // 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.PersonaBar.Extensions.Components.Dto +{ + using System.Collections.Generic; -#region Usings - -using System.Collections.Generic; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ public class AvailablePackagesDto { public string PackageType { get; set; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs index a0c90af278c..4caac598c25 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs @@ -1,15 +1,10 @@ // 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.PersonaBar.Extensions.Components.Dto +{ + using Newtonsoft.Json; -#region Usings - -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ [JsonObject] public class CreateModuleDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs index efd912936f1..53c98992d36 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs @@ -1,17 +1,12 @@ -// 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 -#region Usings - - - -#endregion - namespace Dnn.PersonaBar.Extensions.Components.Dto { public class CreatePackageDto : PackageInfoDto - { - + { + } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DeletePackageDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DeletePackageDto.cs index ae63a81f19f..19fe460e9c8 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DeletePackageDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/DeletePackageDto.cs @@ -1,15 +1,10 @@ // 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.PersonaBar.Extensions.Components.Dto +{ + using Newtonsoft.Json; -#region Usings - -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ [JsonObject] public class DeletePackageDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/AuthSystemPackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/AuthSystemPackageDetailDto.cs index 7dbbe8e6ba0..8a7a4e6f835 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/AuthSystemPackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/AuthSystemPackageDetailDto.cs @@ -1,7 +1,6 @@ // 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.PersonaBar.Extensions.Components.Dto.Editors { using DotNetNuke.Services.Installer.Packages; @@ -10,6 +9,14 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors [JsonObject] public class AuthSystemPackageDetailDto : PackageInfoDto { + public AuthSystemPackageDetailDto() + { + } + + public AuthSystemPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("authenticationType")] public string AuthenticationType { get; set; } @@ -37,14 +44,5 @@ public class AuthSystemPackageDetailDto : PackageInfoDto [JsonProperty("appEnabled")] public bool AppEnabled { get; set; } - - public AuthSystemPackageDetailDto() - { - } - - public AuthSystemPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/CoreLanguagePackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/CoreLanguagePackageDetailDto.cs index 97c1044c3e3..4d31029f0fb 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/CoreLanguagePackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/CoreLanguagePackageDetailDto.cs @@ -1,7 +1,6 @@ // 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.PersonaBar.Extensions.Components.Dto.Editors { using System.Collections.Generic; @@ -12,6 +11,14 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors [JsonObject] public class CoreLanguagePackageDetailDto : PackageInfoDto { + public CoreLanguagePackageDetailDto() + { + } + + public CoreLanguagePackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("locales")] public IEnumerable Locales { get; set; } @@ -23,15 +30,5 @@ public class CoreLanguagePackageDetailDto : PackageInfoDto [JsonProperty("packages")] public IEnumerable Packages { get; set; } - - public CoreLanguagePackageDetailDto() - { - - } - - public CoreLanguagePackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ExtensionLanguagePackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ExtensionLanguagePackageDetailDto.cs index fe450be26bb..dcfc7cc3893 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ExtensionLanguagePackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ExtensionLanguagePackageDetailDto.cs @@ -1,28 +1,23 @@ -// 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 - +// 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.PersonaBar.Extensions.Components.Dto.Editors { - using System.Collections.Generic; - using DotNetNuke.Services.Installer.Packages; using Newtonsoft.Json; [JsonObject] public class ExtensionLanguagePackageDetailDto : CoreLanguagePackageDetailDto { - [JsonProperty("dependentPackageId")] - public int DependentPackageId { get; set; } - public ExtensionLanguagePackageDetailDto() { - } public ExtensionLanguagePackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) { - } + + [JsonProperty("dependentPackageId")] + public int DependentPackageId { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/JsLibraryPackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/JsLibraryPackageDetailDto.cs index ccfdc478d46..bfe7365723e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/JsLibraryPackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/JsLibraryPackageDetailDto.cs @@ -1,7 +1,6 @@ -// 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 - +// 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.PersonaBar.Extensions.Components.Dto.Editors { using System.Collections.Generic; @@ -12,6 +11,14 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors [JsonObject] public class JsLibraryPackageDetailDto : PackageInfoDto { + public JsLibraryPackageDetailDto() + { + } + + public JsLibraryPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("objectName")] public string ObjectName { get; set; } @@ -32,15 +39,5 @@ public class JsLibraryPackageDetailDto : PackageInfoDto [JsonProperty("usedBy")] public IEnumerable UsedBy { get; set; } - - public JsLibraryPackageDetailDto() - { - - } - - public JsLibraryPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleControlDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleControlDto.cs index ac9c8ca1151..cca1448276f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleControlDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleControlDto.cs @@ -1,20 +1,34 @@ -// 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 - -#region Usings - -using DotNetNuke.Entities.Modules; -using DotNetNuke.Security; -using Newtonsoft.Json; - -#endregion - +// 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.PersonaBar.Extensions.Components.Dto.Editors -{ +{ + using DotNetNuke.Entities.Modules; + using DotNetNuke.Security; + using Newtonsoft.Json; + [JsonObject] public class ModuleControlDto { + public ModuleControlDto() + { + } + + public ModuleControlDto(ModuleControlInfo moduleControl) + { + this.Id = moduleControl.ModuleControlID; + this.DefinitionId = moduleControl.ModuleDefID; + this.Key = moduleControl.ControlKey; + this.Title = moduleControl.ControlTitle; + this.Source = moduleControl.ControlSrc; + this.Type = moduleControl.ControlType; + this.Order = moduleControl.ViewOrder; + this.Icon = moduleControl.IconFile; + this.HelpUrl = moduleControl.HelpURL; + this.SupportPopups = moduleControl.SupportsPopUps; + this.SupportPartialRendering = moduleControl.SupportsPartialRendering; + } + [JsonProperty("id")] public int Id { get; set; } @@ -30,7 +44,6 @@ public class ModuleControlDto [JsonProperty("source")] public string Source { get; set; } - [JsonProperty("type")] public SecurityAccessLevel Type { get; set; } @@ -49,26 +62,6 @@ public class ModuleControlDto [JsonProperty("supportPartialRendering")] public bool SupportPartialRendering { get; set; } - public ModuleControlDto() - { - - } - - public ModuleControlDto(ModuleControlInfo moduleControl) - { - this.Id = moduleControl.ModuleControlID; - this.DefinitionId = moduleControl.ModuleDefID; - this.Key = moduleControl.ControlKey; - this.Title = moduleControl.ControlTitle; - this.Source = moduleControl.ControlSrc; - this.Type = moduleControl.ControlType; - this.Order = moduleControl.ViewOrder; - this.Icon = moduleControl.IconFile; - this.HelpUrl = moduleControl.HelpURL; - this.SupportPopups = moduleControl.SupportsPopUps; - this.SupportPartialRendering = moduleControl.SupportsPartialRendering; - } - public ModuleControlInfo ToModuleControlInfo() { return new ModuleControlInfo diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleDefinitionDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleDefinitionDto.cs index 5b5f80c9fb5..30ddda3372a 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleDefinitionDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModuleDefinitionDto.cs @@ -1,41 +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 - -#region Usings - -using System.Collections.Generic; -using DotNetNuke.Entities.Modules.Definitions; -using Newtonsoft.Json; - -#endregion - +// 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.PersonaBar.Extensions.Components.Dto.Editors -{ +{ + using System.Collections.Generic; + + using DotNetNuke.Entities.Modules.Definitions; + using Newtonsoft.Json; + [JsonObject] public class ModuleDefinitionDto { - [JsonProperty("id")] - public int Id { get; set; } - - [JsonProperty("desktopModuleId")] - public int DesktopModuleId { get; set; } - - [JsonProperty("name")] - public string Name { get; set; } - - [JsonProperty("friendlyName")] - public string FriendlyName { get; set; } - - [JsonProperty("cacheTime")] - public int CacheTime { get; set; } - - [JsonProperty("controls")] - public IList Controls { get; set; } = new List(); - public ModuleDefinitionDto() { - } public ModuleDefinitionDto(ModuleDefinitionInfo definition) @@ -52,6 +29,24 @@ public ModuleDefinitionDto(ModuleDefinitionInfo definition) } } + [JsonProperty("id")] + public int Id { get; set; } + + [JsonProperty("desktopModuleId")] + public int DesktopModuleId { get; set; } + + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("friendlyName")] + public string FriendlyName { get; set; } + + [JsonProperty("cacheTime")] + public int CacheTime { get; set; } + + [JsonProperty("controls")] + public IList Controls { get; set; } = new List(); + public ModuleDefinitionInfo ToModuleDefinitionInfo() { return new ModuleDefinitionInfo diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackageDetailDto.cs index 4a1ef2aaa8d..a396e2946e0 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackageDetailDto.cs @@ -1,70 +1,21 @@ -// 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 - -#region Usings - - - -#endregion - -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// 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.PersonaBar.Extensions.Components.Dto.Editors -{ +{ + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class ModulePackageDetailDto : ModulePackagePermissionsDto { - [JsonProperty("moduleName")] - public string ModuleName { get; set; } - - [JsonProperty("folderName")] - public string FolderName { get; set; } - - [JsonProperty("category")] - public string Category { get; set; } - - [JsonProperty("businessController")] - public string BusinessController { get; set; } - - [JsonProperty("dependencies")] - public string Dependencies { get; set; } - - [JsonProperty("hostPermissions")] - public string HostPermissions { get; set; } - - [JsonProperty("portable")] - public bool Portable { get; set; } - - [JsonProperty("searchable")] - public bool Searchable { get; set; } - - [JsonProperty("upgradeable")] - public bool Upgradeable { get; set; } - - [JsonProperty("shareable")] - public ModuleSharing Shareable { get; set; } - - [JsonProperty("premiumModule")] - public bool PremiumModule { get; set; } - - [JsonProperty("assignedPortals")] - public IList AssignedPortals { get; set; } = new List(); - - [JsonProperty("unassignedPortals")] - public IList UnassignedPortals { get; set; } = new List(); - - [JsonProperty("moduleDefinitions")] - public IList ModuleDefinitions { get; set; } = new List(); - public ModulePackageDetailDto() { - } public ModulePackageDetailDto(int portalId, PackageInfo package, DesktopModuleInfo desktopModule) : base(portalId, package) @@ -106,5 +57,47 @@ public ModulePackageDetailDto(int portalId, PackageInfo package, DesktopModuleIn this.ModuleDefinitions.Add(new ModuleDefinitionDto(moduleDefinition)); } } + + [JsonProperty("moduleName")] + public string ModuleName { get; set; } + + [JsonProperty("folderName")] + public string FolderName { get; set; } + + [JsonProperty("category")] + public string Category { get; set; } + + [JsonProperty("businessController")] + public string BusinessController { get; set; } + + [JsonProperty("dependencies")] + public string Dependencies { get; set; } + + [JsonProperty("hostPermissions")] + public string HostPermissions { get; set; } + + [JsonProperty("portable")] + public bool Portable { get; set; } + + [JsonProperty("searchable")] + public bool Searchable { get; set; } + + [JsonProperty("upgradeable")] + public bool Upgradeable { get; set; } + + [JsonProperty("shareable")] + public ModuleSharing Shareable { get; set; } + + [JsonProperty("premiumModule")] + public bool PremiumModule { get; set; } + + [JsonProperty("assignedPortals")] + public IList AssignedPortals { get; set; } = new List(); + + [JsonProperty("unassignedPortals")] + public IList UnassignedPortals { get; set; } = new List(); + + [JsonProperty("moduleDefinitions")] + public IList ModuleDefinitions { get; set; } = new List(); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackagePermissionsDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackagePermissionsDto.cs index 1a6094b5fe2..ce8ca37ed29 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackagePermissionsDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/ModulePackagePermissionsDto.cs @@ -1,36 +1,26 @@ -// 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 - -#region Usings - - - -#endregion - -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - +// 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.PersonaBar.Extensions.Components.Dto.Editors -{ +{ + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class ModulePackagePermissionsDto : PackageInfoDto { - [JsonProperty("desktopModuleId")] - public int DesktopModuleId { get; set; } - - - [JsonProperty("permissions")] - public PermissionsDto Permissions { get; set; } - public ModulePackagePermissionsDto() - { - + { } public ModulePackagePermissionsDto(int portalId, PackageInfo package) : base(portalId, package) - { - + { } + + [JsonProperty("desktopModuleId")] + public int DesktopModuleId { get; set; } + + [JsonProperty("permissions")] + public PermissionsDto Permissions { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinObjectPackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinObjectPackageDetailDto.cs index f06b457bb89..a908f5e8214 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinObjectPackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinObjectPackageDetailDto.cs @@ -1,7 +1,6 @@ -// 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 - +// 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.PersonaBar.Extensions.Components.Dto.Editors { using DotNetNuke.Services.Installer.Packages; @@ -10,6 +9,14 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors [JsonObject] public class SkinObjectPackageDetailDto : PackageInfoDto { + public SkinObjectPackageDetailDto() + { + } + + public SkinObjectPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("controlKey")] public string ControlKey { get; set; } @@ -18,15 +25,5 @@ public class SkinObjectPackageDetailDto : PackageInfoDto [JsonProperty("supportsPartialRendering")] public bool SupportsPartialRendering { get; set; } - - public SkinObjectPackageDetailDto() - { - - } - - public SkinObjectPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinPackageDetailDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinPackageDetailDto.cs index ce56dfeb11c..9c3154799e8 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinPackageDetailDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/Editors/SkinPackageDetailDto.cs @@ -1,7 +1,6 @@ // 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.PersonaBar.Extensions.Components.Dto.Editors { using DotNetNuke.Services.Installer.Packages; @@ -10,17 +9,15 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors [JsonObject] public class SkinPackageDetailDto : PackageInfoDto { - [JsonProperty("themePackageName")] - public string ThemePackageName { get; set; } - public SkinPackageDetailDto() { - } public SkinPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) { - } + + [JsonProperty("themePackageName")] + public string ThemePackageName { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallResultDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallResultDto.cs index 4a33d16004e..fa7507d9ff4 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallResultDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/InstallResultDto.cs @@ -1,18 +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 Dnn.PersonaBar.Extensions.Components.Dto +{ + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Services.Installer.Log; + using Newtonsoft.Json; -#region Usings - -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Services.Installer.Log; -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ [JsonObject] public class InstallResultDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ModuleFolderDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ModuleFolderDto.cs index d9b8b799176..79c46f05b3c 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ModuleFolderDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ModuleFolderDto.cs @@ -1,15 +1,10 @@ // 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.PersonaBar.Extensions.Components.Dto +{ + using Newtonsoft.Json; -#region Usings - -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ [JsonObject] public class ModuleFolderDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoDto.cs index 8ea3af57631..0c3200b6eeb 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoDto.cs @@ -1,29 +1,67 @@ -// 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 - -#region Usings - -using System.Linq; -using Microsoft.Extensions.DependencyInjection; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using DotNetNuke.Web.Components.Controllers.Models; -using Newtonsoft.Json; - -#endregion - +// 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.PersonaBar.Extensions.Components.Dto -{ +{ + using System.Linq; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using DotNetNuke.Web.Components.Controllers.Models; + using Microsoft.Extensions.DependencyInjection; + using Newtonsoft.Json; + [JsonObject] public class PackageInfoDto { + public PackageInfoDto() + { + } + + public PackageInfoDto(int portalId, PackageInfo package) + { + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + + this.PackageType = package.PackageType; + this.FriendlyName = package.FriendlyName; + this.Name = package.Name; + this.PackageId = package.PackageID; + this.Description = package.Description; + this.IsInUse = ExtensionsController.IsPackageInUse(package, portalId); + this.Version = package.Version.ToString(3); + this.UpgradeUrl = ExtensionsController.UpgradeRedirect(package.Version, package.PackageType, package.Name); + this.UpgradeIndicator = ExtensionsController.UpgradeIndicator(package.Version, package.PackageType, package.Name); + this.PackageIcon = ExtensionsController.GetPackageIcon(package); + this.License = package.License; + this.ReleaseNotes = package.ReleaseNotes; + this.Owner = package.Owner; + this.Organization = package.Organization; + this.Url = package.Url; + this.Email = package.Email; + this.CanDelete = !package.IsSystemPackage && + package.PackageID > 0 && + PackageController.CanDeletePackage(package, PortalSettings.Current); + + var authService = AuthenticationController.GetAuthenticationServiceByPackageID(this.PackageId); + this.ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var tabId = portalSettings.ActiveTab.TabID; + this.SiteSettingsLink = this.NavigationManager.NavigateURL(tabId, "EditExtension", + new[] + { + $"packageid={this.PackageId}", + "Display=editor", + "popUp=true", + }); + } + [JsonProperty("packageId")] public int PackageId { get; set; } @@ -83,49 +121,6 @@ public class PackageInfoDto protected INavigationManager NavigationManager { get; } - public PackageInfoDto() - { - - } - - public PackageInfoDto(int portalId, PackageInfo package) - { - this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); - - this.PackageType = package.PackageType; - this.FriendlyName = package.FriendlyName; - this.Name = package.Name; - this.PackageId = package.PackageID; - this.Description = package.Description; - this.IsInUse = ExtensionsController.IsPackageInUse(package, portalId); - this.Version = package.Version.ToString(3); - this.UpgradeUrl = ExtensionsController.UpgradeRedirect(package.Version, package.PackageType, package.Name); - this.UpgradeIndicator = ExtensionsController.UpgradeIndicator(package.Version, package.PackageType, package.Name); - this.PackageIcon = ExtensionsController.GetPackageIcon(package); - this.License = package.License; - this.ReleaseNotes = package.ReleaseNotes; - this.Owner = package.Owner; - this.Organization = package.Organization; - this.Url = package.Url; - this.Email = package.Email; - this.CanDelete = !package.IsSystemPackage && - package.PackageID > 0 && - PackageController.CanDeletePackage(package, PortalSettings.Current); - - var authService = AuthenticationController.GetAuthenticationServiceByPackageID(this.PackageId); - this.ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var tabId = portalSettings.ActiveTab.TabID; - this.SiteSettingsLink = this.NavigationManager.NavigateURL(tabId, "EditExtension", - new[] - { - $"packageid={this.PackageId}", - "Display=editor", - "popUp=true", - }); - } - public PackageInfo ToPackageInfo() { System.Version ver; diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs index c391e46a227..dafde6aecd6 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs @@ -1,22 +1,43 @@ // 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 - -#region Usings - -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Services.Authentication; -using DotNetNuke.Services.Installer.Packages; -using Newtonsoft.Json; - -#endregion - namespace Dnn.PersonaBar.Extensions.Components.Dto { + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Authentication; + using DotNetNuke.Services.Installer.Packages; + using Newtonsoft.Json; + [JsonObject] public class PackageInfoSlimDto { + public PackageInfoSlimDto() + { + } + + public PackageInfoSlimDto(int portalId, PackageInfo package) + { + this.PackageId = package.PackageID; + this.FriendlyName = package.FriendlyName; + this.Name = package.Name; + this.FileName = package.FileName; + this.Description = package.Description; + this.Version = package.Version.ToString(3); + this.IsInUse = ExtensionsController.IsPackageInUse(package, portalId); + this.UpgradeUrl = ExtensionsController.UpgradeRedirect(package.Version, package.PackageType, package.Name); + this.UpgradeIndicator = ExtensionsController.UpgradeIndicator(package.Version, package.PackageType, package.Name); + this.PackageIcon = ExtensionsController.GetPackageIcon(package); + this.Url = package.Url; + this.CanDelete = package.PackageID != Null.NullInteger && !package.IsSystemPackage && PackageController.CanDeletePackage(package, PortalSettings.Current); + + if (package.PackageID != Null.NullInteger) + { + var authService = AuthenticationController.GetAuthenticationServiceByPackageID(this.PackageId); + this.ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; + } + } + [JsonProperty("packageId")] public int PackageId { get; set; } @@ -55,32 +76,5 @@ public class PackageInfoSlimDto [JsonProperty("readOnly")] public bool ReadOnly { get; set; } - - public PackageInfoSlimDto() - { - - } - - public PackageInfoSlimDto(int portalId, PackageInfo package) - { - this.PackageId = package.PackageID; - this.FriendlyName = package.FriendlyName; - this.Name = package.Name; - this.FileName = package.FileName; - this.Description = package.Description; - this.Version = package.Version.ToString(3); - this.IsInUse = ExtensionsController.IsPackageInUse(package, portalId); - this.UpgradeUrl = ExtensionsController.UpgradeRedirect(package.Version, package.PackageType, package.Name); - this.UpgradeIndicator = ExtensionsController.UpgradeIndicator(package.Version, package.PackageType, package.Name); - this.PackageIcon = ExtensionsController.GetPackageIcon(package); - this.Url = package.Url; - this.CanDelete = package.PackageID != Null.NullInteger && !package.IsSystemPackage && PackageController.CanDeletePackage(package, PortalSettings.Current); - - if (package.PackageID != Null.NullInteger) - { - var authService = AuthenticationController.GetAuthenticationServiceByPackageID(this.PackageId); - this.ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; - } - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs index e23c9388f50..e299ae884bd 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs @@ -1,7 +1,6 @@ // 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.PersonaBar.Extensions.Components.Dto { using System.Collections.Generic; @@ -12,6 +11,14 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto [JsonObject] public class PackageManifestDto : PackageInfoDto { + public PackageManifestDto() + { + } + + public PackageManifestDto(int portalId, PackageInfo package) : base(portalId, package) + { + } + [JsonProperty("archiveName")] public string ArchiveName { get; set; } @@ -22,22 +29,12 @@ public class PackageManifestDto : PackageInfoDto public string BasePath { get; set; } [JsonProperty("manifests")] - public IDictionary Manifests { get; set; } = new Dictionary(); + public IDictionary Manifests { get; set; } = new Dictionary(); [JsonProperty("assemblies")] public IList Assemblies { get; set; } = new List(); [JsonProperty("files")] public IList Files { get; set; } = new List(); - - public PackageManifestDto() - { - - } - - public PackageManifestDto(int portalId, PackageInfo package) : base(portalId, package) - { - - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageSettingsDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageSettingsDto.cs index dbebb78aa7a..aaed1077c83 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageSettingsDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageSettingsDto.cs @@ -1,16 +1,12 @@ // 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.PersonaBar.Extensions.Components.Dto +{ + using System.Collections.Generic; + + using Newtonsoft.Json; -#region Usings - -using System.Collections.Generic; -using Newtonsoft.Json; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components.Dto -{ [JsonObject] public class PackageSettingsDto { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs index c6c1f489e36..e3dc21a2531 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs @@ -1,25 +1,29 @@ -// 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 - -#region Usings - -using System.Collections.Generic; -using System.Linq; -using DotNetNuke.Collections; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Services.Installer.Log; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using Newtonsoft.Json; - -#endregion - +// 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.PersonaBar.Extensions.Components.Dto -{ +{ + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Collections; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Services.Installer.Log; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using Newtonsoft.Json; + [JsonObject] public class ParseResultDto : PackageInfoDto { + public ParseResultDto() + { + } + + public ParseResultDto(PackageInfo package) : base(Null.NullInteger, package) + { + } + [JsonProperty("success")] public bool Success { get; set; } = true; @@ -50,16 +54,6 @@ public class ParseResultDto : PackageInfoDto [JsonProperty("logs")] public IList Logs { get; set; } - public ParseResultDto() - { - - } - - public ParseResultDto(PackageInfo package) : base(Null.NullInteger, package) - { - - } - public void Failed(string message, IList logs = null) { this.Success = false; diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs index 214fa563c12..79901e44950 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs @@ -21,9 +21,8 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class AuthSystemPackageEditor : IPackageEditor { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthSystemPackageEditor)); - private static readonly INavigationManager NavigationManager = Globals.DependencyProvider.GetRequiredService(); - #region IPackageEditor Implementation - + private static readonly INavigationManager NavigationManager = Globals.DependencyProvider.GetRequiredService(); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); @@ -94,12 +93,8 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion - - #region Private Methods - + } + private static string GetSettingUrl(int portalId, int authSystemPackageId) { return NavigationManager.NavigateURL(PortalSettings.Current.ActiveTab.TabID, PortalSettings.Current, "EditExtension", @@ -175,8 +170,6 @@ private static void SaveCustomSettings(PackageSettingsDto packageSettings) break; } } - } - - #endregion + } } } 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 a3563e7938c..f97f17ef188 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs @@ -20,11 +20,11 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class CoreLanguagePackageEditor : IPackageEditor { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); - protected INavigationManager NavigationManager { get; } public CoreLanguagePackageEditor() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { 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 209ffa29281..fabb3230d98 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs @@ -20,12 +20,12 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class ExtensionLanguagePackageEditor : IPackageEditor { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); - protected INavigationManager NavigationManager { get; } - public ExtensionLanguagePackageEditor() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + + protected INavigationManager NavigationManager { get; } public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs index 4b6a614f6d8..8d0b62d7473 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs @@ -16,13 +16,11 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class JsLibraryPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); - - #region IPackageEditor Implementation - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { - var usedBy = PackageController.Instance.GetPackageDependencies(d => + var usedBy = PackageController.Instance.GetPackageDependencies(d => d.PackageName.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && d.Version <= package.Version).Select(d => d.PackageId); @@ -74,8 +72,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion + } } } 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 971e889258e..a88d43efdb3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs @@ -24,19 +24,17 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class ModulePackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageEditor)); - - #region IPackageEditor Implementation - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); - if(desktopModule == null) + if (desktopModule == null) { return new PackageInfoDto(portalId, package); - } - + } + var isHostUser = UserController.Instance.GetCurrentUserInfo().IsSuperUser; var detail = isHostUser ? new ModulePackageDetailDto(portalId, package, desktopModule) @@ -65,7 +63,7 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e this.UpdatePermissions(desktopModule, packageSettings); - if(isHostUser) + if (isHostUser) { foreach (var settingName in packageSettings.EditorActions.Keys) { @@ -92,7 +90,7 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e desktopModule.IsPremium = Convert.ToBoolean(settingValue); break; case "shareable": - desktopModule.Shareable = (ModuleSharing) Convert.ToInt32(settingValue); + desktopModule.Shareable = (ModuleSharing)Convert.ToInt32(settingValue); break; case "assignportal": AssignPortals(desktopModule, JsonConvert.DeserializeObject>(settingValue)); @@ -127,12 +125,16 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion - - #region Private Methods + } + private static void UnassignPortals(DesktopModuleInfo desktopModule, IList portals) + { + foreach (var portal in portals) + { + DesktopModuleController.RemoveDesktopModuleFromPortal(portal.Id, desktopModule.DesktopModuleID, true); + } + } + private PermissionsDto GetPermissionsData(int portalId, int desktopModuleId) { var permissions = new PermissionsDto(true); @@ -225,8 +227,7 @@ private void UpdatePermissions(DesktopModuleInfo desktopModule, PackageSettingsD } } } - - + //add user permissions if (permissions.UserPermissions != null) { @@ -261,17 +262,9 @@ private void UpdatePermissions(DesktopModuleInfo desktopModule, PackageSettingsD DataCache.RemoveCache(string.Format(DataCache.PortalDesktopModuleCacheKey, portalSettings.PortalId)); } - private static void UnassignPortals(DesktopModuleInfo desktopModule, IList portals) - { - foreach (var portal in portals) - { - DesktopModuleController.RemoveDesktopModuleFromPortal(portal.Id, desktopModule.DesktopModuleID, true); - } - } - private static void AssignPortals(DesktopModuleInfo desktopModule, IList portals) { - foreach(var portal in portals) + foreach (var portal in portals) { DesktopModuleController.AddDesktopModuleToPortal(portal.Id, desktopModule.DesktopModuleID, true, true); } @@ -297,10 +290,6 @@ private static void SaveModuleControl(ModuleControlDto moduleControlDto) private static void DeleteModuleControl(int controlId) { ModuleControlController.DeleteModuleControl(controlId); - } - - - #endregion - + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs index f79b04ab268..96441b935ac 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs @@ -15,10 +15,8 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class SkinObjectPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinObjectPackageEditor)); - - #region IPackageEditor Implementation - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinObjectPackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var skinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); @@ -28,8 +26,8 @@ public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) detail.ControlKey = skinControl.ControlKey; detail.ControlSrc = skinControl.ControlSrc; detail.SupportsPartialRendering = skinControl.SupportsPartialRendering; - detail.ReadOnly |= !isHostUser; - + detail.ReadOnly |= !isHostUser; + return detail; } @@ -69,8 +67,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs index 050c293b77c..e495362bcb3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs @@ -15,10 +15,8 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class SkinPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinPackageEditor)); - - #region IPackageEditor Implementation - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinPackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var isHostUser = UserController.Instance.GetCurrentUserInfo().IsSuperUser; @@ -61,8 +59,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs index 773060a5304..c51115e76dc 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs @@ -1,42 +1,38 @@ // 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.PersonaBar.Extensions.Components +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Web; + using System.Xml; + + using Dnn.PersonaBar.Extensions.Components.Dto; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Localization; + using DotNetNuke.Services.Upgrade; + using DotNetNuke.Services.Upgrade.Internals; + using Microsoft.Extensions.DependencyInjection; -#region Usings - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Web; -using System.Xml; -using Microsoft.Extensions.DependencyInjection; -using Dnn.PersonaBar.Extensions.Components.Dto; -using DotNetNuke.Common; -using DotNetNuke.Abstractions; -using DotNetNuke.Common.Utilities; -using DotNetNuke.Entities.Modules; -using DotNetNuke.Entities.Portals; -using DotNetNuke.Entities.Tabs; -using DotNetNuke.Services.Installer.Packages; -using DotNetNuke.Services.Localization; -using DotNetNuke.Services.Upgrade; -using DotNetNuke.Services.Upgrade.Internals; - -#endregion - -namespace Dnn.PersonaBar.Extensions.Components -{ public class ExtensionsController { private const string OwnerUpdateService = "DotNetNuke Update Service"; - protected INavigationManager NavigationManager { get; } public ExtensionsController() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } public IDictionary GetPackageTypes() { @@ -152,6 +148,16 @@ public List GetAvailablePackages(string packageType) return packages; } + public List GetPackageUsage(int portalId, int packageId) + { + IDictionary tabs = BuildData(portalId, packageId); + if (tabs != null && tabs.Count > 0) + { + return tabs.Values.ToList(); + } + return null; + } + private void GetAvaialableLanguagePacks(IDictionary validPackages) { try @@ -226,16 +232,6 @@ private void GetAvaialableLanguagePacks(IDictionary validPa } } - public List GetPackageUsage(int portalId, int packageId) - { - IDictionary tabs = BuildData(portalId, packageId); - if (tabs != null && tabs.Count > 0) - { - return tabs.Values.ToList(); - } - return null; - } - public string GetFormattedTabLink(int portalId, TabInfo tab) { var returnValue = new StringBuilder(); @@ -267,19 +263,7 @@ public string GetFormattedTabLink(int portalId, TabInfo tab) } return returnValue.ToString(); - } - - #region Private Functions - - private static void AddModulesToList(int portalId, List packages) - { - Dictionary portalModules = DesktopModuleController.GetPortalDesktopModulesByPortalID(portalId); - packages.AddRange(from modulePackage in PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "Module") - let desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(modulePackage.PackageID) - from portalModule in portalModules.Values - where desktopModule != null && portalModule.DesktopModuleID == desktopModule.DesktopModuleID - select modulePackage); - } + } internal static string IsPackageInUse(PackageInfo packageInfo, int portalId) { @@ -301,6 +285,16 @@ internal static string IsPackageInUse(PackageInfo packageInfo, int portalId) } return string.Empty; } + + private static void AddModulesToList(int portalId, List packages) + { + Dictionary portalModules = DesktopModuleController.GetPortalDesktopModulesByPortalID(portalId); + packages.AddRange(from modulePackage in PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "Module") + let desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(modulePackage.PackageID) + from portalModule in portalModules.Values + where desktopModule != null && portalModule.DesktopModuleID == desktopModule.DesktopModuleID + select modulePackage); + } internal static string UpgradeRedirect(Version version, string packageType, string packageName) { @@ -333,7 +327,7 @@ internal static string GetPackageIcon(PackageInfo package) return IconExists(package.IconFile) ? FixIconUrl(package.IconFile) : Globals.ImagePath + Constants.DefaultAuthenicationImage; case "corelanguagepack": case "extensionlanguagepack": - return package.IconFile != "N\\A" && IconExists(package.IconFile) ? FixIconUrl(package.IconFile) : Globals.ImagePath + Constants.DefaultLanguageImage; + return package.IconFile != "N\\A" && IconExists(package.IconFile) ? FixIconUrl(package.IconFile) : Globals.ImagePath + Constants.DefaultLanguageImage; case "provider": return IconExists(package.IconFile) ? FixIconUrl(package.IconFile) : Globals.ImagePath + Constants.DefaultProviderImage; case "widget": @@ -347,6 +341,11 @@ internal static string GetPackageIcon(PackageInfo package) } } + internal static IDictionary GetPackagesInUse(bool forHost) + { + return PackageController.GetModulePackagesInUse(PortalController.Instance.GetCurrentPortalSettings().PortalId, forHost); + } + private static string FixIconUrl(string url) { return !string.IsNullOrEmpty(Globals.ApplicationPath) @@ -354,11 +353,6 @@ private static string FixIconUrl(string url) : url; } - internal static IDictionary GetPackagesInUse(bool forHost) - { - return PackageController.GetModulePackagesInUse(PortalController.Instance.GetCurrentPortalSettings().PortalId, forHost); - } - private static IDictionary BuildData(int portalId, int packageId) { IDictionary tabsWithModule = TabController.Instance.GetTabsByPackageID(portalId, packageId, false); @@ -404,8 +398,6 @@ private static bool IconExists(string imagePath) return false; } - } - - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs index c19bbab1b9f..1431b4dbbc5 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs @@ -26,11 +26,6 @@ public class InstallController : ServiceLocator GetFactory() - { - return () => new InstallController(); - } - public ParseResultDto ParsePackage(PortalSettings portalSettings, UserInfo user, string filePath, Stream stream) { var parseResult = new ParseResultDto(); @@ -94,6 +89,11 @@ public ParseResultDto ParsePackage(PortalSettings portalSettings, UserInfo user, return parseResult; } + protected override Func GetFactory() + { + return () => new InstallController(); + } + public InstallResultDto InstallPackage(PortalSettings portalSettings, UserInfo user, string legacySkin, string filePath, Stream stream, bool isPortalPackage = false) { var installResult = new InstallResultDto(); @@ -171,7 +171,7 @@ private static Installer GetInstaller(Stream stream, string fileName, int portal // We always assume we are installing from //Host/Extensions (in the previous releases) // This will not work when we try to install a skin/container under a specific portal. - installer.InstallerInfo.PortalID = isPortalPackage ? portalId: Null.NullInteger; + installer.InstallerInfo.PortalID = isPortalPackage ? portalId : Null.NullInteger; //Read the manifest if (installer.InstallerInfo.ManifestFile != null) @@ -226,9 +226,9 @@ private static void DeleteInstallFile(string installerFile) try { if (File.Exists(installerFile)) - { - File.SetAttributes(installerFile, FileAttributes.Normal); - File.Delete(installerFile); + { + File.SetAttributes(installerFile, FileAttributes.Normal); + File.Delete(installerFile); } } catch (Exception ex) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs index 2bb9c7bc428..612ce37ed8a 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs @@ -18,7 +18,7 @@ public static class Utility public static IEnumerable GetAllLanguagesList() { var locales = LocaleController.Instance.GetLocales(Null.NullInteger).Values; - return locales.Select(l => new ListItemDto {Id = l.LanguageId, Name = l.EnglishName}); + return locales.Select(l => new ListItemDto { Id = l.LanguageId, Name = l.EnglishName }); } public static IEnumerable GetAllPackagesListExceptLangPacks() diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs index 8bad1a1343e..d18a9995b8d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs @@ -26,8 +26,8 @@ namespace Dnn.PersonaBar.Pages.Components public class BulkPagesController : ServiceLocator, IBulkPagesController { - private static readonly Regex TabNameRegex = new Regex(">*(.*)", RegexOptions.Compiled); private const string DefaultPageTemplate = "Default.page.template"; + private static readonly Regex TabNameRegex = new Regex(">*(.*)", RegexOptions.Compiled); public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) { @@ -56,14 +56,14 @@ public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) foreach (var strLine in pages) { - var tab = new TabInfo - { - TabName = TabNameRegex.Replace(strLine, "${1}"), - Level = strLine.LastIndexOf(">", StringComparison.Ordinal) + 1, - KeyWords = page.Keywords, - StartDate = page.StartDate ?? Null.NullDate, - EndDate = page.EndDate ?? Null.NullDate, - IsVisible = page.IncludeInMenu + var tab = new TabInfo + { + TabName = TabNameRegex.Replace(strLine, "${1}"), + Level = strLine.LastIndexOf(">", StringComparison.Ordinal) + 1, + KeyWords = page.Keywords, + StartDate = page.StartDate ?? Null.NullDate, + EndDate = page.EndDate ?? Null.NullDate, + IsVisible = page.IncludeInMenu }; tab.Terms.AddRange(TermHelper.ToTabTerms(page.Tags, portalId)); tabs.Add(tab); @@ -106,6 +106,11 @@ public BulkPageResponse AddBulkPages(BulkPage page, bool validateOnly) return response; } + protected override Func GetFactory() + { + return () => new BulkPagesController(); + } + private static BulkPageResponseItem ToBulkPageResponseItem(TabInfo tab, string error) { return new BulkPageResponseItem @@ -117,6 +122,25 @@ private static BulkPageResponseItem ToBulkPageResponseItem(TabInfo tab, string e }; } + private static int GetParentTabId(List lstTabs, int currentIndex, int parentLevel) + { + var oParent = lstTabs[0]; + + for (var i = 0; i < lstTabs.Count; i++) + { + if (i == currentIndex) + { + return oParent.TabID; + } + if (lstTabs[i].Level == parentLevel) + { + oParent = lstTabs[i]; + } + } + + return Null.NullInteger; + } + private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, TabInfo oTab, int parentId, bool validateOnly, out string errorMessage) { var tab = new TabInfo @@ -240,25 +264,6 @@ private int CreateTabFromParent(PortalSettings portalSettings, TabInfo objRoot, return tab.TabID; } - private static int GetParentTabId(List lstTabs, int currentIndex, int parentLevel) - { - var oParent = lstTabs[0]; - - for (var i = 0; i < lstTabs.Count; i++) - { - if (i == currentIndex) - { - return oParent.TabID; - } - if (lstTabs[i].Level == parentLevel) - { - oParent = lstTabs[i]; - } - } - - return Null.NullInteger; - } - private void ApplyDefaultTabTemplate(TabInfo tab) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -316,10 +321,5 @@ private bool IsValidTabPath(TabInfo tab, string newTabPath, out string errorMess return valid; } - - protected override Func GetFactory() - { - return () => new BulkPagesController(); - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/CloneModuleExecutionContext.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/CloneModuleExecutionContext.cs index 404b5f90af2..fde30aeeeee 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/CloneModuleExecutionContext.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/CloneModuleExecutionContext.cs @@ -13,15 +13,15 @@ public class CloneModuleExecutionContext : ServiceLocator GetFactory() - { - return () => new CloneModuleExecutionContext(); - } - public void SetCloneModuleContext(bool cloneModule) { var slot = Thread.GetNamedDataSlot(CloneModuleSlotName); Thread.SetData(slot, cloneModule ? bool.TrueString : bool.FalseString); } + + protected override Func GetFactory() + { + return () => new CloneModuleExecutionContext(); + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Constants.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Constants.cs index d58cb455200..3056596d308 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Constants.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Constants.cs @@ -6,7 +6,7 @@ namespace Dnn.PersonaBar.Pages.Components { public class Constants { - internal const string LocalResourceFile = Library.Constants.PersonaBarRelativePath + "Modules/Dnn.Pages/App_LocalResources/Pages.resx"; public const string PagesCategory = "Prompt_PagesCategory"; + internal const string LocalResourceFile = Library.Constants.PersonaBarRelativePath + "Modules/Dnn.Pages/App_LocalResources/Pages.resx"; } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs index ebdefa5e964..a12b3e1108f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs @@ -70,29 +70,6 @@ public static class Converters AllTabs = module.AllTabs }; - private static string GetModuleEditSettingUrl(ModuleInfo module) - { - var parameters = new List { "ModuleId=" + module.ModuleID, "popUp=true" }; - return _navigationManager.NavigateURL(module.TabID, PortalSettings.Current, "Module", parameters.ToArray()); - } - - private static string GetModuleEditContentUrl(ModuleInfo module) - { - var moduleControl = ModuleControlController.GetModuleControlByControlKey("Edit", module.ModuleDefID); - if(moduleControl != null && moduleControl.ControlType == SecurityAccessLevel.Edit && !string.IsNullOrEmpty(moduleControl.ControlTitle)) - { - var parameters = new List{ "mid=" + module.ModuleID }; - if (moduleControl.SupportsPopUps) - { - parameters.Add("popUp=true"); - } - - return _navigationManager.NavigateURL(module.TabID, PortalSettings.Current, moduleControl.ControlKey, parameters.ToArray()); - } - - return string.Empty; - } - public static T ConvertToPageSettings(TabInfo tab) where T : PageSettings, new() { if (tab == null) @@ -163,6 +140,29 @@ private static string GetModuleEditContentUrl(ModuleInfo module) }; } + private static string GetModuleEditSettingUrl(ModuleInfo module) + { + var parameters = new List { "ModuleId=" + module.ModuleID, "popUp=true" }; + return _navigationManager.NavigateURL(module.TabID, PortalSettings.Current, "Module", parameters.ToArray()); + } + + private static string GetModuleEditContentUrl(ModuleInfo module) + { + var moduleControl = ModuleControlController.GetModuleControlByControlKey("Edit", module.ModuleDefID); + if (moduleControl != null && moduleControl.ControlType == SecurityAccessLevel.Edit && !string.IsNullOrEmpty(moduleControl.ControlTitle)) + { + var parameters = new List { "mid=" + module.ModuleID }; + if (moduleControl.SupportsPopUps) + { + parameters.Add("popUp=true"); + } + + return _navigationManager.NavigateURL(module.TabID, PortalSettings.Current, moduleControl.ControlKey, parameters.ToArray()); + } + + return string.Empty; + } + private static ThemeFileInfo GetThemeFileFromSkinSrc(string skinSrc) { if (string.IsNullOrWhiteSpace(skinSrc)) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs index 162628c3e70..8b8092f0fce 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs @@ -8,11 +8,11 @@ namespace Dnn.PersonaBar.Pages.Components.Exceptions public class BulkPagesException : Exception { - public string Field { get; set; } - public BulkPagesException(string field, string message) : base(message) { this.Field = field; } + + public string Field { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageException.cs index 1fa357d3850..670aef2ec0e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageException.cs @@ -8,7 +8,7 @@ namespace Dnn.PersonaBar.Pages.Components.Exceptions public class PageException : Exception { - public PageException(string message): base(message) + public PageException(string message) : base(message) { } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs index 7918003c54d..1a99c6cef95 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs @@ -8,11 +8,11 @@ namespace Dnn.PersonaBar.Pages.Components.Exceptions public class PageValidationException : Exception { - public string Field { get; set; } - public PageValidationException(string field, string message) : base(message) { this.Field = field; } + + public string Field { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/TemplateException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/TemplateException.cs index 59be42752d2..0116910b5db 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/TemplateException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/TemplateException.cs @@ -8,7 +8,7 @@ namespace Dnn.PersonaBar.Pages.Components.Exceptions public class TemplateException : Exception { - public TemplateException(string message): base(message) + public TemplateException(string message) : base(message) { } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs index e20999e3539..c1e210691f7 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs @@ -12,8 +12,8 @@ public class FriendlyUrlWrapper : IFriendlyUrlWrapper 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); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ICloneModuleExecutionContext.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ICloneModuleExecutionContext.cs index 28c7e48fc9a..7054e6cf1c3 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ICloneModuleExecutionContext.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/ICloneModuleExecutionContext.cs @@ -5,7 +5,7 @@ namespace Dnn.PersonaBar.Pages.Components { /// - /// Provides an abstraction over the current context of the Clone Module thread + /// Provides an abstraction over the current context of the Clone Module thread. /// public interface ICloneModuleExecutionContext { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IDefaultPortalThemeController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IDefaultPortalThemeController.cs index 601c7b58d1b..639dea864d2 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IDefaultPortalThemeController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IDefaultPortalThemeController.cs @@ -5,18 +5,18 @@ namespace Dnn.PersonaBar.Pages.Components { /// - /// Theme controller + /// Theme controller. /// public interface IDefaultPortalThemeController { /// - /// Returns the default current portal container + /// Returns the default current portal container. /// /// string GetDefaultPortalContainer(); /// - /// Returns the default current portal layout + /// Returns the default current portal layout. /// /// string GetDefaultPortalLayout(); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageManagementController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageManagementController.cs index c6b34e0a392..55e91e9da0b 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageManagementController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPageManagementController.cs @@ -14,11 +14,9 @@ public interface IPageManagementController string GetTabUrl(TabInfo tab); - /// - /// Returns true if tab has children, false otherwise - /// - /// Tab info object - /// Returns true if tab has children, false otherwise + /// Gets a value indicating whether the given has children. + /// Tab info object. + /// Returns true if tab has children, false otherwise. bool TabHasChildren(TabInfo tabInfo); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs index 789d25f7e5f..a818e69be8f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs @@ -16,8 +16,8 @@ public interface IPagesController { bool IsValidTabPath(TabInfo tab, string newTabPath, string newTabName, out string errorMessage); - IEnumerable GetPageList(PortalSettings portalSettings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false); - + IEnumerable GetPageList(PortalSettings portalSettings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false); + IEnumerable GetPageList(PortalSettings portalSettings, bool? deleted, string tabName, string tabTitle, string tabPath, string tabSkin, bool? visible, int parentId, out int total, string searchKey = "", int pageIndex = -1, int pageSize = 10, bool includeSubpages = false); @@ -43,23 +43,23 @@ IEnumerable SearchPages(out int totalRecords, string searchKey = "", st void DeleteTabModule(int pageId, int moduleId); /// - /// Returns a clean tab relative url based on Advanced Management Url settings + /// Returns a clean tab relative url based on Advanced Management Url settings. /// - /// Url not cleaned, this could containes blank space or invalid characters - /// Cleaned Url + /// Url not cleaned, this could containes blank space or invalid characters. + /// Cleaned Url. string CleanTabUrl(string url); /// - /// Copy the given theme to all descendant pages + /// Copy the given theme to all descendant pages. /// - /// page identifier - /// Theme + /// page identifier. + /// Theme. void CopyThemeToDescendantPages(int pageId, Theme theme); /// - /// Copy the current page permissions to all descendant pages + /// Copy the current page permissions to all descendant pages. /// - /// page identifier + /// page identifier. void CopyPermissionsToDescendantPages(int pageId); IEnumerable GetPageUrls(int tabId); @@ -67,6 +67,6 @@ IEnumerable SearchPages(out int totalRecords, string searchKey = "", st PageUrlResult CreateCustomUrl(SeoUrl dto); PageUrlResult UpdateCustomUrl(SeoUrl dto); PageUrlResult DeleteCustomUrl(UrlIdDto dto); - PagePermissions GetPermissionsData(int pageId); + PagePermissions GetPermissionsData(int pageId); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs index fc44372d780..9b0f46888a6 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs @@ -22,11 +22,8 @@ public class PageManagementController : ServiceLocator GetFactory() { return () => new PageManagementController(); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs index 5ae636bc8f4..ee31b7bdd07 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs @@ -22,11 +22,28 @@ namespace Dnn.PersonaBar.Pages.Components public class PageUrlsController : ServiceLocator, IPageUrlsController { - private enum SortingFields { None = 0, Url, Locale, Status }; + private enum SortingFields + { + None = 0, + Url, + Locale, + Status, + } - public IEnumerable GetPageUrls(TabInfo tab, int portalId) + protected IEnumerable> StatusCodes { - + get + { + return new[] + { + new KeyValuePair(200, "Active (200)"), + new KeyValuePair(301, "Redirect (301)") + }; + } + } + + public IEnumerable GetPageUrls(TabInfo tab, int portalId) + { var locales = new Lazy>(() => LocaleController.Instance.GetLocales(portalId)); var customUrls = this.GetSortedUrls(tab, portalId, locales, 1, true, false); var automaticUrls = this.GetSortedUrls(tab, portalId, locales, 1, true, true).ToList(); @@ -47,7 +64,7 @@ public PageUrlResult CreateCustomUrl(SaveUrlDto dto, TabInfo tab) Success = false, ErrorMessage = Localization.GetString("CustomUrlPortalAlias.Error"), SuggestedUrlPath = String.Empty - }; + }; } var urlPath = dto.Path.ValueOrEmpty().TrimStart('/'); @@ -58,7 +75,8 @@ public PageUrlResult CreateCustomUrl(SaveUrlDto dto, TabInfo tab) urlPath = FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); if (modified) { - return new PageUrlResult { + return new PageUrlResult + { Success = false, ErrorMessage = Localization.GetString("CustomUrlPathCleaned.Error"), SuggestedUrlPath = "/" + urlPath @@ -69,7 +87,8 @@ public PageUrlResult CreateCustomUrl(SaveUrlDto dto, TabInfo tab) urlPath = FriendlyUrlController.ValidateUrl(urlPath, -1, portalSettings, out modified); if (modified) { - return new PageUrlResult { + return new PageUrlResult + { Success = false, ErrorMessage = Localization.GetString("UrlPathNotUnique.Error"), SuggestedUrlPath = "/" + urlPath @@ -79,7 +98,8 @@ public PageUrlResult CreateCustomUrl(SaveUrlDto dto, TabInfo tab) if (tab.TabUrls.Any(u => u.Url.ToLowerInvariant() == dto.Path.ValueOrEmpty().ToLowerInvariant() && (u.PortalAliasId == dto.SiteAliasKey || u.PortalAliasId == -1))) { - return new PageUrlResult { + return new PageUrlResult + { Success = false, ErrorMessage = Localization.GetString("DuplicateUrl.Error") }; @@ -265,8 +285,7 @@ public PageUrlResult UpdateCustomUrl(SaveUrlDto dto, TabInfo tab) TabController.Instance.SaveTabUrl(tabUrl, portalSettings.PortalId, true); } } - - + return new PageUrlResult { Success = true @@ -286,6 +305,11 @@ public PageUrlResult DeleteCustomUrl(int id, TabInfo tab) }; } + protected override Func GetFactory() + { + return () => new PageUrlsController(); + } + private IEnumerable GetSortedUrls(TabInfo tab, int portalId, Lazy> locales, int sortColumn, bool sortOrder, bool isSystem) { var friendlyUrlSettings = new FriendlyUrlSettings(tab.PortalID); @@ -458,18 +482,6 @@ private void AddUrlToList(List tabs, int portalId, int id, PortalAliasInfo UserName = userName }); } - - protected IEnumerable> StatusCodes - { - get - { - return new[] - { - new KeyValuePair(200, "Active (200)"), - new KeyValuePair(301, "Redirect (301)") - }; - } - } private string GetCleanPath(string path, FriendlyUrlSettings friendlyUrlSettings) { if (string.IsNullOrEmpty(path)) @@ -489,10 +501,5 @@ public int Compare(KeyValuePair pair1, KeyValuePair pa return String.Compare(pair1.Value, pair2.Value, StringComparison.OrdinalIgnoreCase); } } - - protected override Func GetFactory() - { - return () => new PageUrlsController(); - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs index 2ec15477809..a210d9ace2e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs @@ -1,7 +1,6 @@ // 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.PersonaBar.Pages.Components { using System; @@ -38,6 +37,8 @@ namespace Dnn.PersonaBar.Pages.Components public class PagesControllerImpl : IPagesController { + public const string PageTagsVocabulary = "PageTags"; + private readonly ITabController _tabController; private readonly IModuleController _moduleController; private readonly IPageUrlsController _pageUrlsController; @@ -48,11 +49,7 @@ public class PagesControllerImpl : IPagesController private readonly IFriendlyUrlWrapper _friendlyUrlWrapper; private readonly IContentVerifier _contentVerifier; private readonly IPortalController _portalController; - - public const string PageTagsVocabulary = "PageTags"; - private static readonly IList TabSettingKeys = new List { "CustomStylesheet" }; - - private PortalSettings PortalSettings { get; set; } + private static readonly IList TabSettingKeys = new List { "CustomStylesheet" }; public PagesControllerImpl() : this( @@ -92,9 +89,10 @@ public PagesControllerImpl( this._friendlyUrlWrapper = friendlyUrlWrapper; this._contentVerifier = contentVerifier; this._portalController = portalController; - } - + } + private PortalSettings PortalSettings { get; set; } + public bool IsValidTabPath(TabInfo tab, string newTabPath, string newTabName, out string errorMessage) { var portalSettings = this.PortalSettings ?? PortalController.Instance.GetCurrentPortalSettings(); @@ -168,8 +166,7 @@ public List GetPageHierarchy(int pageId) return paths; } - - + public TabInfo MovePage(PageMoveRequest request) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -317,6 +314,24 @@ public TabInfo SavePageDetails(PortalSettings settings, PageSettings pageSetting return TabController.Instance.GetTab(tabId, this.PortalSettings.PortalId); } + public IEnumerable GetPageList(PortalSettings settings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false) + { + var portalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); + var adminTabId = portalSettings.AdminTabId; + + var tabs = TabController.GetPortalTabs(portalSettings.PortalId, adminTabId, false, includeHidden, includeDeleted, true); + var pages = from t in tabs + where (t.ParentId != adminTabId || t.ParentId == Null.NullInteger) && + !t.IsSystem && + ((string.IsNullOrEmpty(searchKey) && (includeSubpages || t.ParentId == parentId)) + || (!string.IsNullOrEmpty(searchKey) && + (t.TabName.IndexOf(searchKey, StringComparison.OrdinalIgnoreCase) > Null.NullInteger + || t.LocalizedTabName.IndexOf(searchKey, StringComparison.OrdinalIgnoreCase) > Null.NullInteger))) + select t; + + return includeSubpages ? pages.OrderBy(x => x.ParentId > -1 ? x.ParentId : x.TabID).ThenBy(x => x.TabID) : pages; + } + private bool IsChild(int portalId, int tabId, int parentId) { if (parentId == Null.NullInteger) @@ -343,24 +358,6 @@ private bool IsChild(int portalId, int tabId, int parentId) return false; } - public IEnumerable GetPageList(PortalSettings settings, int parentId = -1, string searchKey = "", bool includeHidden = true, bool includeDeleted = false, bool includeSubpages = false) - { - var portalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); - var adminTabId = portalSettings.AdminTabId; - - var tabs = TabController.GetPortalTabs(portalSettings.PortalId, adminTabId, false, includeHidden, includeDeleted, true); - var pages = from t in tabs - where (t.ParentId != adminTabId || t.ParentId == Null.NullInteger) && - !t.IsSystem && - ((string.IsNullOrEmpty(searchKey) && (includeSubpages || t.ParentId == parentId)) - || (!string.IsNullOrEmpty(searchKey) && - (t.TabName.IndexOf(searchKey, StringComparison.OrdinalIgnoreCase) > Null.NullInteger - || t.LocalizedTabName.IndexOf(searchKey, StringComparison.OrdinalIgnoreCase) > Null.NullInteger))) - select t; - - return includeSubpages ? pages.OrderBy(x => x.ParentId > -1 ? x.ParentId : x.TabID).ThenBy(x => x.TabID) : pages; - } - public IEnumerable GetPageList(PortalSettings portalSettings, bool? deleted, string tabName, string tabTitle, string tabPath, string tabSkin, bool? visible, int parentId, out int total, string searchKey = "", int pageIndex = -1, int pageSize = 10, bool includeSubpages = false) { @@ -390,7 +387,7 @@ public IEnumerable GetPageList(PortalSettings portalSettings, bool? del Regex.IsMatch(tab.TabPath, tabPath.Replace("*", ".*"), RegexOptions.IgnoreCase); if (!string.IsNullOrEmpty(tabSkin)) { - var escapedString = Regex.Replace(tabSkin, "([^\\w^\\*\\s]+)+", @"\$1", RegexOptions.Compiled|RegexOptions.ECMAScript|RegexOptions.IgnoreCase|RegexOptions.Multiline); + var escapedString = Regex.Replace(tabSkin, "([^\\w^\\*\\s]+)+", @"\$1", RegexOptions.Compiled | RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline); bIsMatch = bIsMatch & Regex.IsMatch(tab.SkinSrc, escapedString.Replace("*", ".*"), RegexOptions.IgnoreCase); } @@ -468,6 +465,45 @@ public IEnumerable SearchPages(out int totalRecords, string searchKey = return pageIndex == -1 || pageSize == -1 ? pages : pages.Skip(pageIndex * pageSize).Take(pageSize); } + public IEnumerable GetModules(int pageId) + { + var tabModules = this._moduleController.GetTabModules(pageId); + return tabModules.Values.Where(m => !m.IsDeleted); + } + + public bool ValidatePageUrlSettings(PortalSettings portalSettings, PageSettings pageSettings, TabInfo tab, ref string invalidField, ref string errorMessage) + { + var urlPath = pageSettings.Url; + + if (string.IsNullOrEmpty(urlPath)) + { + return true; + } + + bool modified; + //Clean Url + var options = this._urlRewriterUtilsWrapper.GetExtendOptionsForURLs(portalSettings.PortalId); + urlPath = this.GetLocalPath(urlPath); + urlPath = this._friendlyUrlWrapper.CleanNameForUrl(urlPath, options, out modified); + if (modified) + { + errorMessage = Localization.GetString("UrlPathCleaned"); + invalidField = "url"; + return false; + } + + //Validate for uniqueness + this._friendlyUrlWrapper.ValidateUrl(urlPath, tab?.TabID ?? Null.NullInteger, portalSettings, out modified); + if (modified) + { + errorMessage = Localization.GetString("UrlPathNotUnique"); + invalidField = "url"; + return false; + } + + return true; + } + private TabInfo GetPageDetails(int pageId) { var portalSettings = this._portalController.GetCurrentPortalSettings(); @@ -480,12 +516,6 @@ private TabInfo GetPageDetails(int pageId) return tab; } - public IEnumerable GetModules(int pageId) - { - var tabModules = this._moduleController.GetTabModules(pageId); - return tabModules.Values.Where(m => !m.IsDeleted); - } - protected virtual bool ValidatePageSettingsData(PortalSettings portalSettings, PageSettings pageSettings, TabInfo tab, out string invalidField, out string errorMessage) { errorMessage = string.Empty; @@ -578,39 +608,6 @@ protected virtual int GetTemplateParentId(int portalId) return Null.NullInteger; } - public bool ValidatePageUrlSettings(PortalSettings portalSettings, PageSettings pageSettings, TabInfo tab, ref string invalidField, ref string errorMessage) - { - var urlPath = pageSettings.Url; - - if (string.IsNullOrEmpty(urlPath)) - { - return true; - } - - bool modified; - //Clean Url - var options = this._urlRewriterUtilsWrapper.GetExtendOptionsForURLs(portalSettings.PortalId); - urlPath = this.GetLocalPath(urlPath); - urlPath = this._friendlyUrlWrapper.CleanNameForUrl(urlPath, options, out modified); - if (modified) - { - errorMessage = Localization.GetString("UrlPathCleaned"); - invalidField = "url"; - return false; - } - - //Validate for uniqueness - this._friendlyUrlWrapper.ValidateUrl(urlPath, tab?.TabID ?? Null.NullInteger, portalSettings, out modified); - if (modified) - { - errorMessage = Localization.GetString("UrlPathNotUnique"); - invalidField = "url"; - return false; - } - - return true; - } - public virtual int AddTab(PortalSettings settings, PageSettings pageSettings) { var portalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); @@ -656,18 +653,96 @@ public virtual int AddTab(PortalSettings settings, PageSettings pageSettings) return tab.TabID; } - private void MovePageIfNeeded(PageSettings pageSettings, TabInfo tab) + public void SaveTabUrl(TabInfo tab, PageSettings pageSettings) { - if (pageSettings.ParentId.HasValue && pageSettings.ParentId.Value != tab.ParentId) + if (!pageSettings.CustomUrlEnabled) { - var request = new PageMoveRequest + return; + } + + if (tab.IsSuperTab) + { + return; + } + + var url = pageSettings.Url; + var tabUrl = tab.TabUrls.SingleOrDefault(t => t.IsSystem + && t.HttpStatus == "200" + && t.SeqNum == 0); + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (!String.IsNullOrEmpty(url) && url != "/") + { + url = this.CleanTabUrl(url); + + string currentUrl = String.Empty; + var friendlyUrlSettings = new FriendlyUrlSettings(portalSettings.PortalId); + if (tab.TabID > -1) { - Action = "parent", - PageId = tab.TabID, - ParentId = pageSettings.ParentId.Value - }; + var baseUrl = Globals.AddHTTP(portalSettings.PortalAlias.HTTPAlias) + "/Default.aspx?TabId=" + tab.TabID; + var path = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, + baseUrl, + Globals.glbDefaultPage, + portalSettings.PortalAlias.HTTPAlias, + false, + friendlyUrlSettings, + Guid.Empty); - this.MovePage(request); + currentUrl = path.Replace(Globals.AddHTTP(portalSettings.PortalAlias.HTTPAlias), ""); + } + + if (url == currentUrl) + { + return; + } + + if (tabUrl == null) + { + //Add new custom url + tabUrl = new TabUrlInfo + { + TabId = tab.TabID, + SeqNum = 0, + PortalAliasId = -1, + PortalAliasUsage = PortalAliasUsageType.Default, + QueryString = String.Empty, + Url = url, + HttpStatus = "200", + CultureCode = String.Empty, + IsSystem = true + }; + //Save url + this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); + } + else + { + //Change the original 200 url to a redirect + tabUrl.HttpStatus = "301"; + tabUrl.SeqNum = tab.TabUrls.Max(t => t.SeqNum) + 1; + this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); + + //Add new custom url + tabUrl.Url = url; + tabUrl.HttpStatus = "200"; + tabUrl.SeqNum = 0; + this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); + } + + //Delete any redirects to the same url + foreach (var redirecturl in this._tabController.GetTabUrls(tab.TabID, tab.PortalID)) + { + if (redirecturl.Url == url && redirecturl.HttpStatus != "200") + { + this._tabController.DeleteTabUrl(redirecturl, tab.PortalID, true); + } + } + } + else + { + if (url == "/" && tabUrl != null) + { + this._tabController.DeleteTabUrl(tabUrl, portalSettings.PortalId, true); + } } } @@ -811,8 +886,33 @@ protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings p else { tab.IconFileLarge = null; + } + + } + + private static string GetExternalUrlRedirection(string url) + { + if (url == null) + { + return null; + } + + return url.ToLower() == "http://" ? "" : Globals.AddHTTP(url); + } + + private void MovePageIfNeeded(PageSettings pageSettings, TabInfo tab) + { + if (pageSettings.ParentId.HasValue && pageSettings.ParentId.Value != tab.ParentId) + { + var request = new PageMoveRequest + { + Action = "parent", + PageId = tab.TabID, + ParentId = pageSettings.ParentId.Value + }; + + this.MovePage(request); } - } private string GetContainerSrc(PageSettings pageSettings) @@ -854,22 +954,12 @@ private string GetInternalUrl(PageSettings pageSettings) } } - private static string GetExternalUrlRedirection(string url) - { - if (url == null) - { - return null; - } - - return url.ToLower() == "http://" ? "" : Globals.AddHTTP(url); - } - /// /// If the tab description is equal to the portal description - /// we store null so the system will serve the portal description instead + /// we store null so the system will serve the portal description instead. /// /// - /// Tab Description value to be stored + /// Tab Description value to be stored. private string GetTabDescription(PageSettings pageSettings) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -879,10 +969,10 @@ private string GetTabDescription(PageSettings pageSettings) /// /// If the tab keywords is equal to the portal keywords - /// we store null so the system will serve the portal keywords instead + /// we store null so the system will serve the portal keywords instead. /// /// - /// Tab Keywords value to be stored + /// Tab Keywords value to be stored. private string GetKeyWords(PageSettings pageSettings) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -890,100 +980,6 @@ private string GetKeyWords(PageSettings pageSettings) ? pageSettings.Keywords : null; } - public void SaveTabUrl(TabInfo tab, PageSettings pageSettings) - { - if (!pageSettings.CustomUrlEnabled) - { - return; - } - - if (tab.IsSuperTab) - { - return; - } - - var url = pageSettings.Url; - var tabUrl = tab.TabUrls.SingleOrDefault(t => t.IsSystem - && t.HttpStatus == "200" - && t.SeqNum == 0); - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (!String.IsNullOrEmpty(url) && url != "/") - { - url = this.CleanTabUrl(url); - - string currentUrl = String.Empty; - var friendlyUrlSettings = new FriendlyUrlSettings(portalSettings.PortalId); - if (tab.TabID > -1) - { - var baseUrl = Globals.AddHTTP(portalSettings.PortalAlias.HTTPAlias) + "/Default.aspx?TabId=" + tab.TabID; - var path = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab, - baseUrl, - Globals.glbDefaultPage, - portalSettings.PortalAlias.HTTPAlias, - false, - friendlyUrlSettings, - Guid.Empty); - - currentUrl = path.Replace(Globals.AddHTTP(portalSettings.PortalAlias.HTTPAlias), ""); - } - - if (url == currentUrl) - { - return; - } - - if (tabUrl == null) - { - //Add new custom url - tabUrl = new TabUrlInfo - { - TabId = tab.TabID, - SeqNum = 0, - PortalAliasId = -1, - PortalAliasUsage = PortalAliasUsageType.Default, - QueryString = String.Empty, - Url = url, - HttpStatus = "200", - CultureCode = String.Empty, - IsSystem = true - }; - //Save url - this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); - } - else - { - //Change the original 200 url to a redirect - tabUrl.HttpStatus = "301"; - tabUrl.SeqNum = tab.TabUrls.Max(t => t.SeqNum) + 1; - this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); - - //Add new custom url - tabUrl.Url = url; - tabUrl.HttpStatus = "200"; - tabUrl.SeqNum = 0; - this._tabController.SaveTabUrl(tabUrl, portalSettings.PortalId, true); - } - - - //Delete any redirects to the same url - foreach (var redirecturl in this._tabController.GetTabUrls(tab.TabID, tab.PortalID)) - { - if (redirecturl.Url == url && redirecturl.HttpStatus != "200") - { - this._tabController.DeleteTabUrl(redirecturl, tab.PortalID, true); - } - } - } - else - { - if (url == "/" && tabUrl != null) - { - this._tabController.DeleteTabUrl(tabUrl, portalSettings.PortalId, true); - } - } - } - public string CleanTabUrl(string url) { if (string.IsNullOrEmpty(url)) @@ -1053,8 +1049,8 @@ public PageSettings GetPageSettings(int pageId, PortalSettings requestPortalSett if (!this._contentVerifier.IsContentExistsForRequestedPortal(tab.PortalID, portalSettings)) { throw new PageNotFoundException(); - } - + } + var page = Converters.ConvertToPageSettings(tab); page.Modules = this.GetModules(page.TabId).Select(Converters.ConvertToModuleItem); page.PageUrls = this.GetPageUrls(page.TabId); @@ -1066,7 +1062,8 @@ public PageSettings GetPageSettings(int pageId, PortalSettings requestPortalSett // icons var iconFile = string.IsNullOrEmpty(tab.IconFile) ? null : FileManager.Instance.GetFile(tab.PortalID, tab.IconFileRaw); - if (iconFile != null) { + if (iconFile != null) + { page.IconFile = new FileDto { fileId = iconFile.FileId, @@ -1107,27 +1104,6 @@ public PageUrlResult DeleteCustomUrl(UrlIdDto dto) var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); return this._pageUrlsController.DeleteCustomUrl(dto.Id, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); } - protected IOrderedEnumerable> GetLocales(int portalId) - { - var locales = new Lazy>(() => LocaleController.Instance.GetLocales(portalId)); - return locales.Value.Values.Select(local => new KeyValuePair(local.KeyID, local.EnglishName)).OrderBy(x => x.Value); - } - protected IEnumerable> GetSiteAliases(int portalId) - { - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); - return aliases.Select(alias => new KeyValuePair(alias.KeyID, alias.HTTPAlias)).OrderBy(x => x.Value); - } - - protected int? GetPrimaryAliasId(int portalId, string cultureCode) - { - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); - var primary = aliases.Where(a => a.IsPrimary - && (a.CultureCode == cultureCode || String.IsNullOrEmpty(a.CultureCode))) - .OrderByDescending(a => a.CultureCode) - .FirstOrDefault(); - return primary == null ? (int?)null : primary.KeyID; - } - public void CreateOrUpdateContentItem(TabInfo tab) { var contentController = Util.GetContentController(); @@ -1145,14 +1121,34 @@ public void CreateOrUpdateContentItem(TabInfo tab) (from t in typeController.GetContentTypes() where t.ContentType == "Tab" select t).SingleOrDefault(); - - + if (contentType != null) { tab.ContentTypeId = contentType.ContentTypeId; } contentController.AddContentItem(tab); } + + protected IOrderedEnumerable> GetLocales(int portalId) + { + var locales = new Lazy>(() => LocaleController.Instance.GetLocales(portalId)); + return locales.Value.Values.Select(local => new KeyValuePair(local.KeyID, local.EnglishName)).OrderBy(x => x.Value); + } + protected IEnumerable> GetSiteAliases(int portalId) + { + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); + return aliases.Select(alias => new KeyValuePair(alias.KeyID, alias.HTTPAlias)).OrderBy(x => x.Value); + } + + protected int? GetPrimaryAliasId(int portalId, string cultureCode) + { + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); + var primary = aliases.Where(a => a.IsPrimary + && (a.CultureCode == cultureCode || String.IsNullOrEmpty(a.CultureCode))) + .OrderByDescending(a => a.CultureCode) + .FirstOrDefault(); + return primary == null ? (int?)null : primary.KeyID; + } public int UpdateTab(TabInfo tab, PageSettings pageSettings) { @@ -1215,8 +1211,7 @@ public void SavePagePermissions(TabInfo tab, PagePermissions permissions) } } } - - + //add user permissions if (permissions.UserPermissions != null) { @@ -1242,20 +1237,6 @@ public void SavePagePermissions(TabInfo tab, PagePermissions permissions) } } - private static Func NoLocked() - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return r => !(r.Locked && r.RoleId != portalSettings.AdministratorRoleId); - } - - private static bool HasAdminPermissions(PagePermissions permissions) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return permissions.RolePermissions != null && (bool)permissions.RolePermissions?.Any(permission => - permission.RoleId == portalSettings.AdministratorRoleId && - permission.Permissions.Count != 0); - } - public virtual PageSettings GetDefaultSettings(int pageId = 0) { var pageSettings = new PageSettings @@ -1276,6 +1257,20 @@ public virtual PageSettings GetDefaultSettings(int pageId = 0) return pageSettings; } + private static Func NoLocked() + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return r => !(r.Locked && r.RoleId != portalSettings.AdministratorRoleId); + } + + private static bool HasAdminPermissions(PagePermissions permissions) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return permissions.RolePermissions != null && (bool)permissions.RolePermissions?.Any(permission => + permission.RoleId == portalSettings.AdministratorRoleId && + permission.Permissions.Count != 0); + } + public PagePermissions GetPermissionsData(int pageId) { var permissions = new PagePermissions(true); @@ -1332,8 +1327,7 @@ public void DeleteTabModule(int pageId, int moduleId) this._moduleController.DeleteTabModule(pageId, moduleId, true); this._moduleController.ClearCache(pageId); } - - + public void CopyContentFromSourceTab(TabInfo tab, int sourceTabId, IEnumerable includedModules) { var sourceTab = this._tabController.GetTab(sourceTabId, tab.PortalID); @@ -1348,6 +1342,11 @@ public void CopyContentFromSourceTab(TabInfo tab, int sourceTabId, IEnumerable terms) + { + return tags.Split(',').All(tag => terms.Any(t => string.Compare(t.Name, tag, StringComparison.CurrentCultureIgnoreCase) == 0)); + } + private string GetLocalPath(string url) { url = url.TrimEnd(new[] { '/' }); @@ -1471,10 +1470,5 @@ private void CopyModulesFromSourceTab(TabInfo tab, TabInfo sourceTab, IEnumerabl } } } - - private static bool HasTags(string tags, IEnumerable terms) - { - return tags.Split(',').All(tag => terms.Any(t => string.Compare(t.Name, tag, StringComparison.CurrentCultureIgnoreCase) == 0)); - } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/DeletePage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/DeletePage.cs index a0acb234d6a..11756291362 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/DeletePage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/DeletePage.cs @@ -17,22 +17,25 @@ namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands [ConsoleCommand("delete-page", Constants.PagesCategory, "Prompt_DeletePage_Description")] public class DeletePage : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("name", "Prompt_DeletePage_FlagName", "String")] private const string FlagName = "name"; + [FlagParameter("id", "Prompt_DeletePage_FlagId", "Integer")] private const string FlagId = "id"; + [FlagParameter("parentid", "Prompt_DeletePage_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; + public override string LocalResourceFile => Constants.LocalResourceFile; + private int PageId { get; set; } = -1; + private string PageName { get; set; } + private int ParentId { get; set; } = -1; public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) - { - + { this.PageId = this.GetFlagValue(FlagId, "Page Id", -1, false, true); this.PageName = this.GetFlagValue(FlagName, "Page Name", string.Empty); this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", -1); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GetPage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GetPage.cs index ed0f5b54d78..187acec3242 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GetPage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GetPage.cs @@ -19,8 +19,6 @@ namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands [ConsoleCommand("get-page", Constants.PagesCategory, "Prompt_GetPage_Description")] public class GetPage : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("name", "Prompt_GetPage_FlagName", "String")] private const string FlagName = "name"; [FlagParameter("id", "Prompt_GetPage_FlagId", "Integer")] @@ -28,19 +26,20 @@ public class GetPage : ConsoleCommandBase [FlagParameter("parentid", "Prompt_GetPage_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; + public override string LocalResourceFile => Constants.LocalResourceFile; private readonly ITabController _tabController; private readonly ISecurityService _securityService; private readonly IContentVerifier _contentVerifier; - private int PageId { get; set; } = -1; - private string PageName { get; set; } - private int ParentId { get; set; } = -1; - public GetPage() : this(TabController.Instance, SecurityService.Instance, new ContentVerifier()) { } + private int PageId { get; set; } = -1; + private string PageName { get; set; } + private int ParentId { get; set; } = -1; + public GetPage( ITabController tabController, ISecurityService securityService, diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GotoPage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs similarity index 96% rename from Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GotoPage.cs rename to Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs index 0e125510c3c..7a9297c9617 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/GotoPage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs @@ -15,7 +15,6 @@ namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands [ConsoleCommand("goto", Constants.PagesCategory, "Prompt_Goto_Description")] public class Goto : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; [FlagParameter("name", "Prompt_Goto_FlagName", "String")] private const string FlagName = "name"; [FlagParameter("id", "Prompt_Goto_FlagId", "Integer")] @@ -23,13 +22,14 @@ public class Goto : ConsoleCommandBase [FlagParameter("parentid", "Prompt_Goto_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; + public override string LocalResourceFile => Constants.LocalResourceFile; private int PageId { get; set; } = -1; private string PageName { get; set; } private int ParentId { get; set; } = -1; public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) - { - + { + this.PageId = this.GetFlagValue(FlagId, "Page Id", -1, false, true); this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", -1); this.PageName = this.GetFlagValue(FlagName, "Page Name", string.Empty); @@ -56,7 +56,7 @@ public override ConsoleResultModel Run() { return new ConsoleErrorResultModel(this.LocalizeString("MethodPermissionDenied")); } - return new ConsoleResultModel(tab.FullUrl) {MustReload = true}; + return new ConsoleResultModel(tab.FullUrl) { MustReload = true }; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/ListPages.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/ListPages.cs index 43e84a0cbf2..7ad3fd39cbe 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/ListPages.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/ListPages.cs @@ -17,8 +17,6 @@ namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands [ConsoleCommand("list-pages", Constants.PagesCategory, "Prompt_ListPages_Description")] public class ListPages : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("parentid", "Prompt_ListPages_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; @@ -45,6 +43,8 @@ public class ListPages : ConsoleCommandBase [FlagParameter("max", "Prompt_ListRoles_FlagMax", "Integer", "10")] private const string FlagMax = "max"; + + public override string LocalResourceFile => Constants.LocalResourceFile; private int? ParentId { get; set; } = -1; private bool? Deleted { get; set; } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/NewPage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/NewPage.cs index dfed261c7bf..5fbe6fbf6a0 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/NewPage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/NewPage.cs @@ -19,8 +19,6 @@ namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands [ConsoleCommand("new-page", Constants.PagesCategory, "Prompt_NewPage_Description")] public class NewPage : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("parentid", "Prompt_NewPage_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; @@ -41,6 +39,8 @@ public class NewPage : ConsoleCommandBase [FlagParameter("visible", "Prompt_NewPage_FlagVisible", "Boolean", "true")] private const string FlagVisible = "visible"; + + public override string LocalResourceFile => Constants.LocalResourceFile; private string Title { get; set; } private string Name { get; set; } @@ -51,8 +51,8 @@ public class NewPage : ConsoleCommandBase private bool? Visible { get; set; } public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) - { - + { + this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", null, false, false, true); this.Title = this.GetFlagValue(FlagTitle, "Title", string.Empty); this.Name = this.GetFlagValue(FlagName, "Page Name", string.Empty, true, true); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/SetPage.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/SetPage.cs index 02074b022f2..74d013d24ce 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/SetPage.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/SetPage.cs @@ -19,8 +19,6 @@ namespace Dnn.PersonaBar.Pages.Components.Prompt.Commands [ConsoleCommand("set-page", Constants.PagesCategory, "Prompt_SetPage_Description")] public class SetPage : ConsoleCommandBase { - public override string LocalResourceFile => Constants.LocalResourceFile; - [FlagParameter("id", "Prompt_SetPage_FlagId", "Integer", true)] private const string FlagId = "id"; @@ -44,6 +42,8 @@ public class SetPage : ConsoleCommandBase [FlagParameter("parentid", "Prompt_SetPage_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; + + public override string LocalResourceFile => Constants.LocalResourceFile; private int PageId { get; set; } private int? ParentId { get; set; } @@ -55,8 +55,8 @@ public class SetPage : ConsoleCommandBase private bool? Visible { get; set; } public override void Init(string[] args, PortalSettings portalSettings, UserInfo userInfo, int activeTabId) - { - + { + this.PageId = this.GetFlagValue(FlagId, "Page Id", -1, true, true, true); this.ParentId = this.GetFlagValue(FlagParentId, "Parent Id", null); this.Title = this.GetFlagValue(FlagTitle, "Title", string.Empty); @@ -82,7 +82,7 @@ public override ConsoleResultModel Run() } pageSettings.Name = !string.IsNullOrEmpty(this.Name) ? this.Name : pageSettings.Name; pageSettings.Title = !string.IsNullOrEmpty(this.Title) ? this.Title : pageSettings.Title; - pageSettings.Url = !string.IsNullOrEmpty(this.Url) ? this.Url : pageSettings.Url; + pageSettings.Url = !string.IsNullOrEmpty(this.Url) ? this.Url : pageSettings.Url; pageSettings.Description = !string.IsNullOrEmpty(this.Description) ? this.Description : pageSettings.Description; pageSettings.Keywords = !string.IsNullOrEmpty(this.Keywords) ? this.Keywords : pageSettings.Keywords; pageSettings.ParentId = this.ParentId.HasValue ? this.ParentId : pageSettings.ParentId; @@ -104,6 +104,6 @@ public override ConsoleResultModel Run() { return new ConsoleErrorResultModel(ex.Message); } - } + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModel.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModel.cs index 8667fe2e5a5..af7ed662341 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModel.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModel.cs @@ -6,20 +6,20 @@ namespace Dnn.PersonaBar.Pages.Components.Prompt.Models { public class PageModel : PageModelBase { - public string Container { get; set; } - public string Url { get; set; } - public string Keywords { get; set; } - public string Description { get; set; } - public PageModel() { } - public PageModel(DotNetNuke.Entities.Tabs.TabInfo tab): base(tab) + + public PageModel(DotNetNuke.Entities.Tabs.TabInfo tab) : base(tab) { this.Container = tab.ContainerSrc; this.Url = tab.Url; this.Keywords = tab.KeyWords; this.Description = tab.Description; } + public string Container { get; set; } + public string Url { get; set; } + public string Keywords { get; set; } + public string Description { get; set; } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModelBase.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModelBase.cs index 405739d5bb4..a4b489f9b42 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModelBase.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Models/PageModelBase.cs @@ -6,6 +6,10 @@ namespace Dnn.PersonaBar.Pages.Components.Prompt.Models { public class PageModelBase { + public PageModelBase() + { + } + public int TabId { get; set; } public string Name { get; set; } public string Title { get; set; } @@ -13,23 +17,15 @@ public class PageModelBase public string Skin { get; set; } public string Path { get; set; } public bool IncludeInMenu { get; set; } - public bool IsDeleted { get; set; } - - #region Command Links + public bool IsDeleted { get; set; } + public string __TabId => $"get-page {this.TabId}"; public string __ParentId => $"list-pages --parentid {this.ParentId}"; public string __IncludeInMenu => $"list-pages --visible{(this.IncludeInMenu ? "" : " false")}"; - public string __IsDeleted => $"list-pages --deleted{(this.IsDeleted ? "" : " false")}"; - - #endregion - - #region constructors - public PageModelBase() - { - } + public string __IsDeleted => $"list-pages --deleted{(this.IsDeleted ? "" : " false")}"; public PageModelBase(DotNetNuke.Entities.Tabs.TabInfo tab) { this.Name = tab.TabName; @@ -40,7 +36,6 @@ public PageModelBase(DotNetNuke.Entities.Tabs.TabInfo tab) this.Title = tab.Title; this.IncludeInMenu = tab.IsVisible; this.IsDeleted = tab.IsDeleted; - } - #endregion + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs index 2a36e956a3d..df330e9705d 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs @@ -54,18 +54,6 @@ public virtual bool IsVisible(MenuItem menuItem) return this.IsPageAdminUser() || this.CanViewPageList(menuItem.MenuId); } - private bool IsPageAdmin() - { - return //TabPermissionController.CanAddContentToPage() || - TabPermissionController.CanAddPage() - || TabPermissionController.CanAdminPage() - || TabPermissionController.CanCopyPage() - || TabPermissionController.CanDeletePage() - || TabPermissionController.CanExportPage() - || TabPermissionController.CanImportPage() - || TabPermissionController.CanManagePage(); - } - public virtual JObject GetCurrentPagePermissions() { var permissions = new JObject @@ -83,6 +71,18 @@ public virtual JObject GetCurrentPagePermissions() return permissions; } + private bool IsPageAdmin() + { + return //TabPermissionController.CanAddContentToPage() || + TabPermissionController.CanAddPage() + || TabPermissionController.CanAdminPage() + || TabPermissionController.CanCopyPage() + || TabPermissionController.CanDeletePage() + || TabPermissionController.CanExportPage() + || TabPermissionController.CanImportPage() + || TabPermissionController.CanManagePage(); + } + public virtual JObject GetPagePermissions(TabInfo tab) { var permissions = new JObject diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs index 86bb516593e..2fdf72b23be 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs @@ -38,7 +38,8 @@ public TemplateController() public string SaveAsTemplate(PageTemplate template) { string filename; - try { + try + { var folder = GetTemplateFolder(); if (folder == null) @@ -60,9 +61,9 @@ public string SaveAsTemplate(PageTemplate template) //Serialize tabs var nodeTabs = nodePortal.AppendChild(xmlTemplate.CreateElement("tabs")); - this.SerializeTab(template, xmlTemplate, nodeTabs); - - //add file to Files table + this.SerializeTab(template, xmlTemplate, nodeTabs); + + //add file to Files table using (var fileContent = new MemoryStream(Encoding.UTF8.GetBytes(xmlTemplate.OuterXml))) { FileManager.Instance.AddFile(folder, template.Name + ".page.template", fileContent, true, false, "application/octet-stream"); @@ -79,6 +80,30 @@ public string SaveAsTemplate(PageTemplate template) return filename; } + public IEnumerable